index
int64 0
0
| repo_id
stringclasses 829
values | file_path
stringlengths 34
254
| content
stringlengths 6
5.38M
|
|---|---|---|---|
0
|
code_files/vets-api-private/app/services/debt_transaction_log
|
code_files/vets-api-private/app/services/debt_transaction_log/summary_builders/dispute_summary_builder.rb
|
# frozen_string_literal: true
class DebtTransactionLog::SummaryBuilders::DisputeSummaryBuilder
def self.build(submission)
file_count = submission.respond_to?(:files) && submission.files&.attached? ? submission.files.count : 0
{
debt_types: submission.public_metadata&.dig('debt_types') || [],
dispute_reasons: submission.public_metadata&.dig('dispute_reasons') || [],
file_count:
}
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/hca/overrides_parser.rb
|
# frozen_string_literal: true
module HCA
class OverridesParser
STATE_OVERRIDES = {
'MEX' => {
'aguascalientes' => 'AGS.',
'baja-california-norte' => 'B.C.',
'baja-california-sur' => 'B.C.S.',
'campeche' => 'CAM.',
'chiapas' => 'CHIS.',
'chihuahua' => 'CHIH.',
'coahuila' => 'COAH.',
'colima' => 'COL.',
'distrito-federal' => 'D.F.',
'durango' => 'DGO.',
'guanajuato' => 'GTO.',
'guerrero' => 'GRO.',
'hidalgo' => 'HGO.',
'jalisco' => 'JAL.',
'mexico' => 'MEX.',
'michoacan' => 'MICH.',
'morelos' => 'MOR.',
'nayarit' => 'NAY.',
'nuevo-leon' => 'N.L.',
'oaxaca' => 'OAX.',
'puebla' => 'PUE.',
'queretaro' => 'QRO.',
'quintana-roo' => 'Q.ROO.',
'san-luis-potosi' => 'S.L.P.',
'sinaloa' => 'SIN.',
'sonora' => 'SON.',
'tabasco' => 'TAB.',
'tamaulipas' => 'TAMPS.',
'tlaxcala' => 'TLAX.',
'veracruz' => 'VER.',
'yucatan' => 'YUC.',
'zacatecas' => 'ZAC.'
}
}.freeze
attr_accessor :params, :form
def initialize(form)
@form = form
end
def override
override_address_states
form
end
def override_address_states
%w[veteranHomeAddress veteranAddress spouseAddress].each do |target|
override_individual_address(target)
end
end
def override_individual_address(key)
country = form.dig(key, 'country')
state = form.dig(key, 'state')
return unless STATE_OVERRIDES.key?(country)
return unless STATE_OVERRIDES[country]&.key?(state)
form[key]['state'] = STATE_OVERRIDES[country][state]
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/identity/errors.rb
|
# frozen_string_literal: true
module Identity
module Errors
class CernerProvisionerError < StandardError; end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/identity/cerner_provisioner.rb
|
# frozen_string_literal: true
require 'map/sign_up/service'
module Identity
class CernerProvisioner
include ActiveModel::Validations
COOKIE_NAME = 'CERNER_CONSENT'
COOKIE_VALUE = 'ACCEPTED'
COOKIE_PATH = '/'
COOKIE_EXPIRATION = 2.minutes
COOKIE_DOMAIN = '.va.gov'
attr_reader :icn, :source
validates :icn, presence: true
def initialize(icn:, source: nil)
@icn = icn
@source = source
validate!
rescue ActiveModel::ValidationError => e
log_provisioner_error(e)
raise Errors::CernerProvisionerError, e.message
end
def perform
response = update_provisioning
if response[:agreement_signed].blank?
Rails.logger.error('[Identity] [CernerProvisioner] update_provisioning error', { icn:, response:, source: })
raise(Errors::CernerProvisionerError, 'Agreement not accepted')
end
if response[:cerner_provisioned].blank?
Rails.logger.error('[Identity] [CernerProvisioner] update_provisioning error', { icn:, response:, source: })
raise(Errors::CernerProvisionerError, 'Account not Provisioned')
end
Rails.logger.info('[Identity] [CernerProvisioner] update_provisioning success', { icn:, source: })
rescue Common::Client::Errors::ClientError => e
log_provisioner_error(e)
raise Errors::CernerProvisionerError, e.message
end
private
def update_provisioning
MAP::SignUp::Service.new.update_provisioning(icn:, first_name:, last_name:, mpi_gcids:)
end
def log_provisioner_error(error)
Rails.logger.error("[Identity] [CernerProvisioner] Error: #{error.message}", { icn:, source: })
end
def mpi_profile
@mpi_profile ||= MPI::Service.new.find_profile_by_identifier(identifier: icn,
identifier_type: MPI::Constants::ICN)&.profile
end
def first_name
mpi_profile.given_names.first
end
def last_name
mpi_profile.family_name
end
def mpi_gcids
mpi_profile.full_mvi_ids.join('|')
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/base_assertion_validator.rb
|
# frozen_string_literal: true
module SignIn
class BaseAssertionValidator
private
def decode_assertion!(assertion)
payload, _header = JWT.decode(assertion, nil, true, jwt_decode_options, &method(:jwt_keyfinder))
payload.deep_symbolize_keys
rescue JWT::InvalidAudError, JWT::InvalidIatError, JWT::InvalidIssuerError,
JWT::InvalidSubError, JWT::MissingRequiredClaim => e
raise attributes_error_class.new(message: e.message)
rescue JWT::VerificationError
raise signature_mismatch_error_class.new(message: signature_mismatch_message)
rescue JWT::ExpiredSignature
raise expired_error_class.new(message: expired_message)
rescue JWT::DecodeError
raise malformed_error_class.new(message: malformed_message)
end
def jwt_keyfinder(_header, _payload)
certs = active_certs
raise Errors::AssertionCertificateExpiredError.new message: 'Certificates are expired' if certs.blank?
certs.map(&:public_key)
end
def hostname
return localhost_hostname if Settings.vsp_environment == 'localhost'
return staging_hostname if Settings.review_instance_slug.present?
"https://#{Settings.hostname}"
end
def algorithm = Constants::Auth::ASSERTION_ENCODE_ALGORITHM
def token_route = "#{hostname}#{Constants::Auth::TOKEN_ROUTE_PATH}"
def staging_hostname = 'https://staging-api.va.gov'
def localhost_hostname = "http://localhost:#{URI("http://#{Settings.hostname}").port}"
def signature_mismatch_message = 'Assertion body does not match signature'
def expired_message = 'Assertion has expired'
def malformed_message = 'Assertion is malformed'
def attributes_error_class = raise NotImplementedError
def signature_mismatch_error_class = raise NotImplementedError
def expired_error_class = raise NotImplementedError
def malformed_error_class = raise NotImplementedError
def active_certs = raise NotImplementedError
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/errors.rb
|
# frozen_string_literal: true
module SignIn
module Errors
class StandardError < StandardError
attr_reader :code
def initialize(message:, code: Constants::ErrorCode::INVALID_REQUEST)
@code = code
super(message)
end
end
class AccessDeniedError < StandardError; end
class AccessTokenExpiredError < StandardError; end
class AccessTokenMalformedJWTError < StandardError; end
class AccessTokenSignatureMismatchError < StandardError; end
class AccessTokenUnauthenticatedError < StandardError; end
class AntiCSRFMismatchError < StandardError; end
class AssertionExpiredError < StandardError; end
class AssertionMalformedJWTError < StandardError; end
class AssertionSignatureMismatchError < StandardError; end
class AssertionCertificateExpiredError < StandardError; end
class AttributeMismatchError < StandardError; end
class ClientAssertionAttributesError < StandardError; end
class ClientAssertionExpiredError < StandardError; end
class ClientAssertionInvalidError < StandardError; end
class ClientAssertionMalformedJWTError < StandardError; end
class ClientAssertionSignatureMismatchError < StandardError; end
class ClientAssertionTypeInvalidError < StandardError; end
class CodeChallengeMalformedError < StandardError; end
class CodeChallengeMethodMismatchError < StandardError; end
class CodeChallengeMismatchError < StandardError; end
class CodeInvalidError < StandardError; end
class CodeVerifierMalformedError < StandardError; end
class CredentialLockedError < StandardError; end
class CredentialMissingAttributeError < StandardError; end
class CredentialProviderError < StandardError; end
class GrantTypeValueError < StandardError; end
class InvalidAccessTokenAttributeError < StandardError; end
class InvalidAcrError < StandardError; end
class InvalidAudienceError < StandardError; end
class InvalidClientConfigError < StandardError; end
class InvalidCredentialLevelError < StandardError; end
class InvalidScope < StandardError; end
class InvalidServiceAccountScope < StandardError; end
class InvalidSSORequestError < StandardError; end
class InvalidTokenError < StandardError; end
class InvalidTokenTypeError < StandardError; end
class InvalidTypeError < StandardError; end
class LogingovRiscEventHandlerError < StandardError; end
class LogoutAuthorizationError < StandardError; end
class MalformedParamsError < StandardError; end
class MHVMissingMPIRecordError < StandardError; end
class MissingParamsError < StandardError; end
class MPILockedAccountError < StandardError; end
class MPIMalformedAccountError < StandardError; end
class MPIUserCreationFailedError < StandardError; end
class RefreshNonceMismatchError < StandardError; end
class RefreshTokenDecryptionError < StandardError; end
class RefreshTokenMalformedError < StandardError; end
class RefreshVersionMismatchError < StandardError; end
class ServiceAccountAssertionAttributesError < StandardError; end
class ServiceAccountConfigNotFound < StandardError; end
class SessionNotAuthorizedError < StandardError; end
class SessionNotFoundError < StandardError; end
class StateCodeInvalidError < StandardError; end
class StatePayloadError < StandardError; end
class StatePayloadMalformedJWTError < StandardError; end
class StatePayloadSignatureMismatchError < StandardError; end
class TermsOfUseNotAcceptedError < StandardError; end
class TokenTheftDetectedError < StandardError; end
class UnverifiedCredentialBlockedError < StandardError; end
class UserAccountNotFoundError < StandardError; end
class UserAttributesMalformedError < StandardError; end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/service_account_access_token_jwt_decoder.rb
|
# frozen_string_literal: true
module SignIn
class ServiceAccountAccessTokenJwtDecoder
attr_reader :service_account_access_token_jwt
def initialize(service_account_access_token_jwt:)
@service_account_access_token_jwt = service_account_access_token_jwt
end
def perform(with_validation: true)
decoded_token = jwt_decode_service_account_access_token(with_validation)
ServiceAccountAccessToken.new(service_account_id: decoded_token.service_account_id,
audience: decoded_token.aud,
scopes: decoded_token.scopes,
user_attributes: decoded_token.user_attributes,
user_identifier: decoded_token.sub,
uuid: decoded_token.jti,
version: decoded_token.version,
expiration_time: Time.zone.at(decoded_token.exp),
created_time: Time.zone.at(decoded_token.iat))
end
private
def jwt_decode_service_account_access_token(with_validation)
decoded_jwt = JWT.decode(
service_account_access_token_jwt,
decode_key_array,
with_validation,
{
verify_expiration: with_validation,
algorithm: Constants::ServiceAccountAccessToken::JWT_ENCODE_ALGORITHM
}
)&.first
OpenStruct.new(decoded_jwt)
rescue JWT::VerificationError
raise Errors::AccessTokenSignatureMismatchError.new(
message: 'Service Account access token body does not match signature'
)
rescue JWT::ExpiredSignature
raise Errors::AccessTokenExpiredError.new message: 'Service Account access token has expired'
rescue JWT::DecodeError
raise Errors::AccessTokenMalformedJWTError.new message: 'Service Account access token JWT is malformed'
end
def decode_key_array
[public_key, public_key_old].compact
end
def public_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_encode_key)).public_key
end
def public_key_old
return unless IdentitySettings.sign_in.jwt_old_encode_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_old_encode_key)).public_key
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/token_exchanger.rb
|
# frozen_string_literal: true
module SignIn
class TokenExchanger
include ActiveModel::Validations
attr_reader :subject_token, :subject_token_type, :actor_token, :actor_token_type, :client_id
validate :validate_subject_token!,
:validate_subject_token_type!,
:validate_actor_token!,
:validate_actor_token_type!,
:validate_client_id!,
:validate_shared_sessions_client!,
:validate_device_sso!
def initialize(subject_token:, subject_token_type:, actor_token:, actor_token_type:, client_id:)
@subject_token = subject_token
@subject_token_type = subject_token_type
@actor_token = actor_token
@actor_token_type = actor_token_type
@client_id = client_id
end
def perform
validate!
create_new_session
end
private
def validate_subject_token!
unless subject_token && current_access_token
raise Errors::InvalidTokenError.new message: 'subject token is invalid'
end
end
def validate_subject_token_type!
unless subject_token_type == Constants::Urn::ACCESS_TOKEN
raise Errors::InvalidTokenTypeError.new message: 'subject token type is invalid'
end
end
def validate_actor_token_type!
unless actor_token_type == Constants::Urn::DEVICE_SECRET
raise Errors::InvalidTokenTypeError.new message: 'actor token type is invalid'
end
end
def validate_actor_token!
raise Errors::InvalidTokenError.new message: 'actor token is invalid' unless valid_actor_token?
end
def valid_actor_token?
hashed_actor_token == current_session.hashed_device_secret &&
hashed_actor_token == current_access_token.device_secret_hash
end
def hashed_actor_token
@hashed_actor_token ||= Digest::SHA256.hexdigest(actor_token)
end
def validate_client_id!
unless new_session_client_config
raise Errors::InvalidClientConfigError.new message: 'client configuration not found'
end
end
def validate_shared_sessions_client!
unless new_session_client_config.shared_sessions
raise Errors::InvalidClientConfigError.new message: 'tokens requested for client without shared sessions'
end
end
def validate_device_sso!
unless current_client_config.api_sso_enabled?
raise Errors::InvalidSSORequestError.new message: 'token exchange requested from invalid client'
end
end
def create_new_session
SessionSpawner.new(current_session:, new_session_client_config:).perform
end
def new_session_client_config
@new_session_client_config ||= ClientConfig.find_by(client_id:)
end
def current_access_token
@current_access_token ||= AccessTokenJwtDecoder.new(access_token_jwt: subject_token).perform
end
def current_session
@current_session ||= OAuthSession.find_by(handle: current_access_token.session_handle)
end
def current_client_config
@current_client_config ||= ClientConfig.find_by(client_id: current_access_token.client_id)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/user_info_generator.rb
|
# frozen_string_literal: true
module SignIn
class UserInfoGenerator
attr_reader :user
def initialize(user:)
@user = user
end
def perform
SignIn::UserInfo.new(sub:, ial:, aal:, csp_type:, csp_uuid:, email:, full_name:, birth_date:, ssn:, gender:,
address_street1:, address_street2:, address_city:, address_state:, address_country:,
address_postal_code:, phone_number:, person_types:, icn:, sec_id:, edipi:, mhv_ien:,
npi_id:, cerner_id:, corp_id:, birls:, gcids:)
end
private
def sub = user_verification.credential_identifier
def ial = user_verification.verified? ? Constants::Auth::IAL_TWO : Constants::Auth::IAL_ONE
def aal = AAL::LOGIN_GOV_AAL2
def csp_uuid = user_verification.credential_identifier
def email = user.user_verification&.user_credential_email&.credential_email
def full_name = user.full_name_normalized.values.compact.join(' ')
def birth_date = user.birth_date
def ssn = user.ssn
def gender = user.gender
def address_street1 = user.address[:street]
def address_street2 = user.address[:street2]
def address_city = user.address[:city]
def address_state = user.address[:state]
def address_country = user.address[:country]
def address_postal_code = user.address[:postal_code]
def phone_number = user.home_phone
def person_types = user.person_types&.join('|') || ''
def icn = user.icn
def sec_id = user.sec_id
def edipi = user.edipi
def mhv_ien = user.mhv_ien
def npi_id = user.npi_id
def cerner_id = user.cerner_id
def corp_id = user.participant_id
def birls = user.birls_id
def gcids = filter_gcids.join('|')
def user_verification
@user_verification ||= user.user_verification
end
def csp_type
case user_verification.credential_type
when 'idme'
MPI::Constants::IDME_IDENTIFIER
when 'logingov'
MPI::Constants::LOGINGOV_IDENTIFIER
end
end
def filter_gcids
return [] if user.mpi_gcids.blank?
user.mpi_gcids.filter do |gcid|
code = gcid.to_s.split('^', 4)[2]
next false if code.blank?
UserInfo::ALLOWED_GCID_CODES.key?(code) || code.match?(UserInfo::NUMERIC_GCID_CODE)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/access_token_audience_generator.rb
|
# frozen_string_literal: true
module SignIn
class AccessTokenAudienceGenerator
SHARED_SESSION_CLIENT_IDS_CACHE_KEY = 'sis_shared_sessions_client_ids'
def initialize(client_config:)
@client_config = client_config
end
def perform
generate_audience
end
private
attr_reader :client_config
def generate_audience
return shared_session_client_ids if client_config.shared_sessions?
[client_config.client_id]
end
def shared_session_client_ids
@shared_session_client_ids ||= Rails.cache.fetch(SHARED_SESSION_CLIENT_IDS_CACHE_KEY, expires_in: 5.minutes) do
ClientConfig.where(shared_sessions: true).pluck(:client_id)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/service_account_access_token_jwt_encoder.rb
|
# frozen_string_literal: true
module SignIn
class ServiceAccountAccessTokenJwtEncoder
attr_reader :service_account_access_token
def initialize(service_account_access_token:)
@service_account_access_token = service_account_access_token
end
def perform
jwt_encode_service_account_access_token
end
private
def jwt_encode_service_account_access_token
JWT.encode(payload, private_key, Constants::ServiceAccountAccessToken::JWT_ENCODE_ALGORITHM, jwt_header)
end
def payload
{
iss: Constants::ServiceAccountAccessToken::ISSUER,
aud: service_account_access_token.audience,
jti: service_account_access_token.uuid,
sub: service_account_access_token.user_identifier,
exp: service_account_access_token.expiration_time.to_i,
iat: service_account_access_token.created_time.to_i,
nbf: service_account_access_token.created_time.to_i,
version: service_account_access_token.version,
scopes: service_account_access_token.scopes,
service_account_id: service_account_access_token.service_account_id,
user_attributes: service_account_access_token.user_attributes
}
end
def private_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_encode_key))
end
def jwt_header
{
typ: 'JWT',
kid: JWT::JWK.new(private_key).kid
}
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/refresh_token_decryptor.rb
|
# frozen_string_literal: true
module SignIn
class RefreshTokenDecryptor
attr_reader :encrypted_refresh_token
def initialize(encrypted_refresh_token:)
@encrypted_refresh_token = encrypted_refresh_token
end
def perform
decrypted_component = get_decrypted_component
validate_token!(decrypted_component)
RefreshToken.new(
session_handle: decrypted_component.session_handle,
uuid: decrypted_component.uuid,
user_uuid: decrypted_component.user_uuid,
parent_refresh_token_hash: decrypted_component.parent_refresh_token_hash,
anti_csrf_token: decrypted_component.anti_csrf_token,
nonce: decrypted_component.nonce,
version: decrypted_component.version
)
end
private
def validate_token!(decrypted_component)
if decrypted_component.version != version_from_split_token
raise Errors::RefreshVersionMismatchError.new message: 'Refresh token version is invalid'
end
if decrypted_component.nonce != nonce_from_split_token
raise Errors::RefreshNonceMismatchError.new message: 'Refresh nonce is invalid'
end
end
def get_decrypted_component
decrypted_string = decrypt_refresh_token(split_token_array[Constants::RefreshToken::ENCRYPTED_POSITION])
deserialize_token(decrypted_string)
end
def nonce_from_split_token
split_token_array[Constants::RefreshToken::NONCE_POSITION]
end
def version_from_split_token
split_token_array[Constants::RefreshToken::VERSION_POSITION]
end
def decrypt_refresh_token(encrypted_part)
message_encryptor.decrypt(encrypted_part)
rescue KmsEncrypted::DecryptionError
Rails.logger.info("[RefreshTokenDecryptor] Token cannot be decrypted, refresh_token: #{encrypted_refresh_token}")
raise Errors::RefreshTokenDecryptionError.new message: 'Refresh token cannot be decrypted'
end
def deserialize_token(decrypted_string)
JSON.parse(decrypted_string, object_class: OpenStruct)
end
def split_token_array
@split_token_array ||= encrypted_refresh_token.split('.', Constants::RefreshToken::ENCRYPTED_ARRAY.length)
end
def message_encryptor
KmsEncrypted::Box.new
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/logout_redirect_generator.rb
|
# frozen_string_literal: true
require 'sign_in/logingov/service'
module SignIn
class LogoutRedirectGenerator
attr_reader :credential_type, :client_config
def initialize(client_config:, credential_type: nil)
@credential_type = credential_type
@client_config = client_config
end
def perform
return unless logout_redirect_uri
if authenticated_with_logingov?
logingov_service.render_logout(logout_redirect_uri)
else
parse_logout_redirect_uri
end
end
private
def parse_logout_redirect_uri
URI.parse(logout_redirect_uri).to_s
end
def authenticated_with_logingov?
credential_type == Constants::Auth::LOGINGOV
end
def logout_redirect_uri
@logout_redirect_uri ||= client_config&.logout_redirect_uri
end
def logingov_service
AuthenticationServiceRetriever.new(type: Constants::Auth::LOGINGOV).perform
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/credential_level_creator.rb
|
# frozen_string_literal: true
module SignIn
class CredentialLevelCreator
attr_reader :requested_acr,
:type,
:logingov_acr,
:verified_at,
:mhv_assurance,
:dslogon_assurance,
:level_of_assurance,
:credential_ial,
:credential_uuid
def initialize(requested_acr:, type:, logingov_acr:, user_info:)
@requested_acr = requested_acr
@type = type
@logingov_acr = logingov_acr
@verified_at = user_info.verified_at
@mhv_assurance = user_info.mhv_assurance
@dslogon_assurance = user_info.dslogon_assurance
@level_of_assurance = user_info.level_of_assurance
@credential_ial = user_info.credential_ial
@credential_uuid = user_info.sub
end
def perform
check_required_verification_level
create_credential_level
end
private
def check_required_verification_level
if unverified_account_with_forced_verification?
case type
when Constants::Auth::MHV
raise_unverified_credential_blocked_error(code: Constants::ErrorCode::MHV_UNVERIFIED_BLOCKED)
else
raise_unverified_credential_blocked_error(code: Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE)
end
end
end
def raise_unverified_credential_blocked_error(code:)
raise Errors::UnverifiedCredentialBlockedError.new(
message: 'Unverified credential for authorization requiring verified credential', code:
)
end
def create_credential_level
CredentialLevel.new(requested_acr:,
credential_type: type,
current_ial:,
max_ial:,
auto_uplevel: false)
rescue ActiveModel::ValidationError => e
Rails.logger.info("[SignIn][CredentialLevelCreator] error: #{e.message}", credential_type: type,
requested_acr:,
current_ial:,
max_ial:,
credential_uuid:)
raise Errors::InvalidCredentialLevelError.new message: 'Unsupported credential authorization levels'
end
def max_ial
case type
when Constants::Auth::LOGINGOV
logingov_max_ial
when Constants::Auth::MHV
mhv_max_ial
when Constants::Auth::DSLOGON
dslogon_max_ial
else
idme_max_ial
end
end
def current_ial
case type
when Constants::Auth::LOGINGOV
logingov_current_ial
when Constants::Auth::MHV
mhv_current_ial
when Constants::Auth::DSLOGON
dslogon_current_ial
else
idme_current_ial
end
end
def logingov_max_ial
verified_ial_level(verified_at || previously_verified?(:logingov_uuid))
end
def mhv_max_ial
verified_ial_level(mhv_premium_verified?)
end
def dslogon_max_ial
Rails.logger.info(
"[CredentialLevelCreator] DSLogon level of assurance: #{dslogon_assurance}, " \
"credential_uuid: #{credential_uuid}"
)
verified_ial_level(dslogon_premium_verified?)
end
def idme_max_ial
if ial2_enabled?
verified_ial_level(idme_ial2? || idme_loa3_and_previously_verified?)
else
verified_ial_level(idme_loa3_or_previously_verified?)
end
end
def logingov_current_ial
verified_ial_level(logingov_ial2?)
end
def mhv_current_ial
verified_ial_level(requested_verified_account? && mhv_premium_verified?)
end
def dslogon_current_ial
verified_ial_level(requested_verified_account? && dslogon_premium_verified?)
end
def idme_current_ial
if ial2_enabled?
verified_ial_level(idme_ial2? || idme_classic_loa3_and_previously_verified?)
else
verified_ial_level(idme_classic_loa3_or_ial2?)
end
end
def mhv_premium_verified?
Constants::Auth::MHV_PREMIUM_VERIFIED.include?(mhv_assurance)
end
def dslogon_premium_verified?
Constants::Auth::DSLOGON_PREMIUM_VERIFIED.include?(dslogon_assurance)
end
def logingov_ial2?
logingov_acr == Constants::Auth::LOGIN_GOV_IAL2
end
def idme_loa3_or_previously_verified?
level_of_assurance == Constants::Auth::LOA_THREE || previously_verified?(:idme_uuid)
end
def idme_loa3_and_previously_verified?
level_of_assurance == Constants::Auth::LOA_THREE && previously_verified?(:idme_uuid)
end
def idme_classic_loa3_and_previously_verified?
credential_ial == Constants::Auth::IDME_CLASSIC_LOA3 && previously_verified?(:idme_uuid)
end
def idme_ial2?
credential_ial == Constants::Auth::IAL_TWO
end
def idme_classic_loa3_or_ial2?
[Constants::Auth::IDME_CLASSIC_LOA3, Constants::Auth::IAL_TWO].include?(credential_ial)
end
def verified_ial_level(verified)
verified ? Constants::Auth::IAL_TWO : Constants::Auth::IAL_ONE
end
def requested_verified_account?
[Constants::Auth::IAL2, Constants::Auth::LOA3, Constants::Auth::MIN].include?(requested_acr)
end
def unverified_account_with_forced_verification?
requires_verified_account? && current_ial < Constants::Auth::IAL_TWO
end
def requires_verified_account?
[Constants::Auth::IAL2, Constants::Auth::LOA3].include?(requested_acr)
end
def previously_verified?(identifier_type)
user_verification = UserVerification.find_by(identifier_type => credential_uuid)
user_verification&.verified?
end
def ial2_enabled?
Flipper.enabled?(:identity_ial2_enforcement) && Settings.vsp_environment != 'production'
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/authentication_service_retriever.rb
|
# frozen_string_literal: true
require 'sign_in/logingov/service'
require 'sign_in/idme/service'
require 'credential/service'
module SignIn
class AuthenticationServiceRetriever
attr_reader :type, :client_config
def initialize(type:, client_config: nil)
@type = type
@client_config = client_config
end
def perform
if client_config&.mock_auth?
mock_auth_service
else
auth_service
end
end
private
def auth_service
case type
when Constants::Auth::LOGINGOV
logingov_auth_service
else
idme_auth_service
end
end
def idme_auth_service
@idme_auth_service ||= Idme::Service.new(type:, optional_scopes: idme_optional_scopes)
end
def logingov_auth_service
@logingov_auth_service ||= Logingov::Service.new(optional_scopes: logingov_optional_scopes)
end
def mock_auth_service
@mock_auth_service ||= begin
@mock_auth_service = MockedAuthentication::Credential::Service.new
@mock_auth_service.type = type
@mock_auth_service
end
end
def idme_optional_scopes
return nil if client_config.blank?
client_config.access_token_attributes & Idme::Service::OPTIONAL_SCOPES
end
def logingov_optional_scopes
return [] if client_config.blank?
client_config.access_token_attributes & Logingov::Service::OPTIONAL_SCOPES
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/client_assertion_validator.rb
|
# frozen_string_literal: true
module SignIn
class ClientAssertionValidator < BaseAssertionValidator
attr_reader :client_assertion, :client_assertion_type, :client_config, :decoded_assertion
def initialize(client_assertion:, client_assertion_type:, client_config:)
super()
@client_assertion = client_assertion
@client_assertion_type = client_assertion_type
@client_config = client_config
end
def perform
validate_client_assertion_type
@decoded_assertion = decode_assertion!(client_assertion)
true
end
private
def validate_client_assertion_type
return if client_assertion_type == Constants::Urn::JWT_BEARER_CLIENT_AUTHENTICATION
raise Errors::ClientAssertionTypeInvalidError.new message: 'Client assertion type is not valid'
end
def jwt_decode_options
{
aud: [token_route],
sub: client_config.client_id,
iss: client_config.client_id,
verify_sub: true,
verify_aud: true,
verify_iss: true,
verify_iat: true,
verify_expiration: true,
required_claims: %w[iat sub exp iss],
algorithms: [algorithm]
}
end
def active_certs
@active_certs ||= client_config.certs.active
end
def attributes_error_class = Errors::ClientAssertionAttributesError
def signature_mismatch_error_class = Errors::ClientAssertionSignatureMismatchError
def expired_error_class = Errors::ClientAssertionExpiredError
def malformed_error_class = Errors::ClientAssertionMalformedJWTError
def signature_mismatch_message = 'Client assertion body does not match signature'
def expired_message = 'Client assertion has expired'
def malformed_message = 'Client assertion is malformed'
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/code_validator.rb
|
# frozen_string_literal: true
module SignIn
class CodeValidator
attr_reader :code, :code_verifier, :client_assertion, :client_assertion_type
def initialize(code:, code_verifier:, client_assertion:, client_assertion_type:)
@code = code
@code_verifier = code_verifier
@client_assertion = client_assertion
@client_assertion_type = client_assertion_type
end
def perform
validations
validated_credential
ensure
code_container&.destroy
end
private
def validations
validate_code_container
if client_config.pkce?
validate_code_challenge
else
validate_client_assertion
end
end
def validate_client_assertion
SignIn::ClientAssertionValidator.new(client_assertion:, client_assertion_type:, client_config:).perform
end
def validate_code_container
raise Errors::CodeInvalidError.new message: 'Code is not valid' unless code_container
end
def validate_code_challenge
if code_challenge != code_container.code_challenge
raise Errors::CodeChallengeMismatchError.new message: 'Code Verifier is not valid'
end
end
def user_verification
@user_verification ||= UserVerification.find(code_container.user_verification_id)
end
def code_challenge
@code_challenge ||= remove_base64_padding(Digest::SHA256.base64digest(code_verifier))
end
def code_container
@code_container ||= CodeContainer.find(code)
end
def remove_base64_padding(data)
Base64.urlsafe_encode64(Base64.urlsafe_decode64(data.to_s), padding: false)
rescue ArgumentError
raise Errors::CodeVerifierMalformedError.new message: 'Code Verifier is malformed'
end
def validated_credential
@validated_credential ||= ValidatedCredential.new(user_verification:,
credential_email: code_container.credential_email,
client_config:,
user_attributes: code_container.user_attributes,
device_sso: code_container.device_sso,
web_sso_session_id: code_container.web_sso_session_id)
end
def client_config
@client_config ||= SignIn::ClientConfig.find_by(client_id: code_container.client_id)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/session_revoker.rb
|
# frozen_string_literal: true
require 'sign_in/logger'
module SignIn
class SessionRevoker
attr_reader :access_token, :refresh_token, :anti_csrf_token, :session, :device_secret
def initialize(anti_csrf_token:, access_token: nil, refresh_token: nil, device_secret: nil)
@refresh_token = refresh_token
@anti_csrf_token = anti_csrf_token
@access_token = access_token
@device_secret = device_secret
end
def perform
find_valid_oauth_session
anti_csrf_check if anti_csrf_enabled_client?
delete_session!
delete_device_sessions if device_secret.present?
end
private
def anti_csrf_check
if anti_csrf_token != revoking_token.anti_csrf_token
raise Errors::AntiCSRFMismatchError.new message: 'Anti CSRF token is not valid'
end
end
def find_valid_oauth_session
@session ||= OAuthSession.find_by(handle: revoking_token.session_handle)
raise Errors::SessionNotAuthorizedError.new message: 'No valid Session found' unless session&.active?
end
def detect_token_theft
unless refresh_token_in_session? || parent_refresh_token_in_session?
raise Errors::TokenTheftDetectedError.new message: 'Token theft detected'
end
end
def refresh_token_in_session?
session.hashed_refresh_token == double_refresh_token_hash
end
def parent_refresh_token_in_session?
session.hashed_refresh_token == double_parent_refresh_token_hash
end
def double_refresh_token_hash
@double_refresh_token_hash ||= get_hash(refresh_token_hash)
end
def double_parent_refresh_token_hash
@double_parent_refresh_token_hash ||= get_hash(refresh_token.parent_refresh_token_hash)
end
def refresh_token_hash
@refresh_token_hash ||= get_hash(refresh_token.to_json)
end
def revoking_token
@revoking_token ||= access_token || refresh_token
end
def client_config
@client_config ||= SignIn::ClientConfig.find_by!(client_id: session.client_id)
end
def anti_csrf_enabled_client?
client_config.anti_csrf
end
def get_hash(object)
Digest::SHA256.hexdigest(object)
end
def delete_session!
detect_token_theft if refresh_token
ensure
session.destroy!
end
def delete_device_sessions
hashed_device_secret = get_hash(device_secret)
OAuthSession.where(hashed_device_secret:).destroy_all
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/access_token_jwt_encoder.rb
|
# frozen_string_literal: true
module SignIn
class AccessTokenJwtEncoder
attr_reader :access_token
def initialize(access_token:)
@access_token = access_token
end
def perform
jwt_encode_access_token
end
private
def payload
{
iss: Constants::AccessToken::ISSUER,
aud: access_token.audience,
client_id: access_token.client_id,
jti: access_token.uuid,
sub: access_token.user_uuid,
exp: access_token.expiration_time.to_i,
iat: access_token.created_time.to_i,
session_handle: access_token.session_handle,
refresh_token_hash: access_token.refresh_token_hash,
device_secret_hash: access_token.device_secret_hash,
parent_refresh_token_hash: access_token.parent_refresh_token_hash,
anti_csrf_token: access_token.anti_csrf_token,
last_regeneration_time: access_token.last_regeneration_time.to_i,
version: access_token.version,
user_attributes: access_token.user_attributes
}
end
def jwt_encode_access_token
JWT.encode(payload, private_key, Constants::AccessToken::JWT_ENCODE_ALGORITHM)
end
def private_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_encode_key))
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/token_serializer.rb
|
# frozen_string_literal: true
module SignIn
class TokenSerializer
attr_reader :session_container, :cookies
def initialize(session_container:, cookies:)
@session_container = session_container
@cookies = cookies
end
def perform
if cookie_authentication_client?
set_cookies
{}
elsif api_authentication_client?
token_json_response
elsif mock_authentication_client?
set_cookies
token_json_response
end
end
private
def set_cookies
set_cookie!(name: Constants::Auth::ACCESS_TOKEN_COOKIE_NAME,
value: encoded_access_token,
httponly: true,
domain: :all)
set_cookie!(name: Constants::Auth::REFRESH_TOKEN_COOKIE_NAME,
value: encrypted_refresh_token,
httponly: true,
path: Constants::Auth::REFRESH_ROUTE_PATH)
set_cookie!(name: Constants::Auth::INFO_COOKIE_NAME,
value: info_cookie_value.to_json,
httponly: false,
domain: IdentitySettings.sign_in.info_cookie_domain)
if anti_csrf_enabled_client?
set_cookie!(name: Constants::Auth::ANTI_CSRF_COOKIE_NAME,
value: anti_csrf_token,
httponly: true)
end
end
def set_cookie!(name:, value:, httponly:, domain: nil, path: '/')
cookies[name] = {
value:,
expires: session_expiration,
secure: IdentitySettings.sign_in.cookies_secure,
httponly:,
path:,
domain:
}.compact
end
def info_cookie_value
{
access_token_expiration:,
refresh_token_expiration: session_expiration
}
end
def token_json_response
return { data: token_json_payload } if json_api_compatibility_client?
token_json_payload
end
def token_json_payload
payload = {}
payload[:refresh_token] = encrypted_refresh_token unless web_sso_client?
payload[:access_token] = encoded_access_token
payload[:anti_csrf_token] = anti_csrf_token if anti_csrf_enabled_client?
payload[:device_secret] = device_secret if device_secret_enabled_client?
payload
end
def device_secret_enabled_client?
api_authentication_client? && client_config.shared_sessions && device_secret
end
def cookie_authentication_client?
client_config.cookie_auth?
end
def api_authentication_client?
client_config.api_auth?
end
def mock_authentication_client?
client_config.mock_auth?
end
def anti_csrf_enabled_client?
client_config.anti_csrf
end
def json_api_compatibility_client?
client_config.json_api_compatibility
end
def device_secret
@device_secret ||= session_container.device_secret
end
def session_expiration
@session_expiration ||= session_container.session.refresh_expiration
end
def access_token_expiration
@access_token_expiration ||= session_container.access_token.expiration_time
end
def encrypted_refresh_token
@encrypted_refresh_token ||=
RefreshTokenEncryptor.new(refresh_token: session_container.refresh_token).perform
end
def encoded_access_token
@encoded_access_token ||= AccessTokenJwtEncoder.new(access_token: session_container.access_token).perform
end
def anti_csrf_token
@anti_csrf_token ||= session_container.anti_csrf_token
end
def client_config
@client_config ||= session_container.client_config
end
def web_sso_client?
@web_sso_client ||= session_container.web_sso_client
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/state_payload_verifier.rb
|
# frozen_string_literal: true
module SignIn
class StatePayloadVerifier
attr_reader :state_payload
def initialize(state_payload:)
@state_payload = state_payload
end
def perform
validate_state_code
end
private
def state_code
@state_code ||= StateCode.find(state_payload.code)
end
def validate_state_code
raise Errors::StateCodeInvalidError.new message: 'Code in state is not valid' unless state_code
ensure
state_code&.destroy
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/state_payload_jwt_decoder.rb
|
# frozen_string_literal: true
module SignIn
class StatePayloadJwtDecoder
attr_reader :state_payload_jwt
def initialize(state_payload_jwt:)
@state_payload_jwt = state_payload_jwt
end
def perform
create_state_payload
end
private
def create_state_payload
StatePayload.new(
acr: decoded_jwt.acr,
client_id: decoded_jwt.client_id,
type: decoded_jwt.type,
code_challenge: decoded_jwt.code_challenge,
client_state: decoded_jwt.client_state,
code: decoded_jwt.code,
created_at: decoded_jwt.created_at,
scope: decoded_jwt.scope
)
end
def decoded_jwt
@decoded_jwt ||= begin
with_validation = true
decoded_jwt = JWT.decode(
state_payload_jwt,
decode_key_array,
with_validation,
{
algorithm: Constants::Auth::JWT_ENCODE_ALGORITHM
}
)&.first
OpenStruct.new(decoded_jwt)
end
rescue JWT::VerificationError
raise Errors::StatePayloadSignatureMismatchError.new message: 'State JWT body does not match signature'
rescue JWT::DecodeError
raise Errors::StatePayloadMalformedJWTError.new message: 'State JWT is malformed'
end
def decode_key_array
[public_key, public_key_old].compact
end
def public_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_encode_key)).public_key
end
def public_key_old
return unless IdentitySettings.sign_in.jwt_old_encode_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_old_encode_key)).public_key
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/logger.rb
|
# frozen_string_literal: true
require 'sign_in/constants/auth'
module SignIn
class Logger
attr_reader :prefix
def initialize(prefix:)
@prefix = prefix
end
def info(message, context = {})
Rails.logger.info("[SignInService] [#{prefix}] #{message}", context)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/session_refresher.rb
|
# frozen_string_literal: true
module SignIn
class SessionRefresher
attr_reader :refresh_token, :anti_csrf_token, :session
def initialize(refresh_token:, anti_csrf_token:)
@refresh_token = refresh_token
@anti_csrf_token = anti_csrf_token
end
def perform
find_valid_oauth_session
validate_credential_lock
validate_terms_of_use if client_config.enforced_terms.present?
anti_csrf_check if anti_csrf_enabled_client?
detect_token_theft
update_session! if parent_refresh_token_in_session?
create_new_tokens
end
private
def validate_credential_lock
if session.user_verification.locked
raise SignIn::Errors::CredentialLockedError.new(message: 'Credential is locked')
end
end
def validate_terms_of_use
if session.user_account.needs_accepted_terms_of_use?
raise Errors::TermsOfUseNotAcceptedError.new message: 'Terms of Use has not been accepted'
end
end
def anti_csrf_check
if anti_csrf_token != refresh_token.anti_csrf_token
raise Errors::AntiCSRFMismatchError.new message: 'Anti CSRF token is not valid'
end
end
def find_valid_oauth_session
@session ||= OAuthSession.find_by(handle: refresh_token.session_handle)
raise Errors::SessionNotAuthorizedError.new message: 'No valid Session found' unless session&.active?
end
def detect_token_theft
unless refresh_token_in_session? || parent_refresh_token_in_session?
session.destroy!
raise Errors::TokenTheftDetectedError.new message: 'Token theft detected'
end
end
def refresh_token_in_session?
session.hashed_refresh_token == double_refresh_token_hash
end
def parent_refresh_token_in_session?
session.hashed_refresh_token == double_parent_refresh_token_hash
end
def create_new_tokens
SessionContainer.new(session:,
refresh_token: child_refresh_token,
access_token:,
client_config:,
anti_csrf_token: updated_anti_csrf_token)
end
def update_session!
session.hashed_refresh_token = double_refresh_token_hash
session.refresh_expiration = refresh_expiration
session.save!
end
def create_child_refresh_token
RefreshToken.new(
session_handle: session.handle,
user_uuid: refresh_token.user_uuid,
anti_csrf_token: updated_anti_csrf_token,
parent_refresh_token_hash: refresh_token_hash
)
end
def create_access_token
AccessToken.new(
session_handle: session.handle,
client_id:,
user_uuid: refresh_token.user_uuid,
audience:,
refresh_token_hash: get_hash(child_refresh_token.to_json),
parent_refresh_token_hash: refresh_token_hash,
anti_csrf_token: updated_anti_csrf_token,
last_regeneration_time:,
user_attributes: session.user_attributes_hash,
device_secret_hash: session.hashed_device_secret
)
end
def last_regeneration_time
@last_regeneration_time ||= Time.zone.now
end
def refresh_expiration
@refresh_expiration ||= Time.zone.now + validity_length
end
def validity_length
client_config.refresh_token_duration
end
def updated_anti_csrf_token
@updated_anti_csrf_token ||= SecureRandom.hex
end
def anti_csrf_enabled_client?
client_config.anti_csrf
end
def audience
@audience ||= AccessTokenAudienceGenerator.new(client_config:).perform
end
def client_config
@client_config ||= SignIn::ClientConfig.find_by!(client_id:)
end
def client_id
@client_id ||= session.client_id
end
def get_hash(object)
Digest::SHA256.hexdigest(object)
end
def refresh_token_hash
@refresh_token_hash ||= get_hash(refresh_token.to_json)
end
def double_refresh_token_hash
@double_refresh_token_hash ||= get_hash(refresh_token_hash)
end
def double_parent_refresh_token_hash
@double_parent_refresh_token_hash ||= get_hash(refresh_token.parent_refresh_token_hash)
end
def child_refresh_token
@child_refresh_token ||= create_child_refresh_token
end
def access_token
@access_token ||= create_access_token
end
def hashed_device_secret
return unless validated_credential.device_sso
@hashed_device_secret ||= get_hash(device_secret)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/session_creator.rb
|
# frozen_string_literal: true
module SignIn
class SessionCreator
attr_reader :validated_credential
def initialize(validated_credential:)
@validated_credential = validated_credential
end
def perform
validate_credential_lock
validate_terms_of_use
SessionContainer.new(session: create_new_session,
refresh_token:,
access_token: create_new_access_token,
anti_csrf_token:,
client_config:,
device_secret:,
web_sso_client: web_sso_session_id.present?)
end
private
def validate_credential_lock
raise SignIn::Errors::CredentialLockedError.new(message: 'Credential is locked') if user_verification.locked
end
def validate_terms_of_use
if client_config.enforced_terms.present? && user_verification.user_account.needs_accepted_terms_of_use?
raise Errors::TermsOfUseNotAcceptedError.new message: 'Terms of Use has not been accepted'
end
end
def anti_csrf_token
@anti_csrf_token ||= SecureRandom.hex
end
def refresh_token
@refresh_token ||= create_new_refresh_token(parent_refresh_token_hash:)
end
def double_parent_refresh_token_hash
@double_parent_refresh_token_hash ||= get_hash(parent_refresh_token_hash)
end
def refresh_token_hash
@refresh_token_hash ||= get_hash(refresh_token.to_json)
end
def parent_refresh_token_hash
@parent_refresh_token_hash ||= get_hash(create_new_refresh_token.to_json)
end
def hashed_device_secret
return unless validated_credential.device_sso
@hashed_device_secret ||= get_hash(device_secret)
end
def create_new_access_token
AccessToken.new(
session_handle: handle,
client_id: client_config.client_id,
user_uuid:,
audience: AccessTokenAudienceGenerator.new(client_config:).perform,
refresh_token_hash:,
parent_refresh_token_hash:,
anti_csrf_token:,
last_regeneration_time: refresh_created_time,
user_attributes:,
device_secret_hash: hashed_device_secret
)
end
def create_new_refresh_token(parent_refresh_token_hash: nil)
RefreshToken.new(
session_handle: handle,
user_uuid:,
parent_refresh_token_hash:,
anti_csrf_token:
)
end
def create_new_session
OAuthSession.create!(user_account: user_verification.user_account,
user_verification:,
client_id: client_config.client_id,
credential_email: validated_credential.credential_email,
handle:,
hashed_refresh_token: double_parent_refresh_token_hash,
refresh_expiration: refresh_expiration_time,
refresh_creation: refresh_created_time,
user_attributes: user_attributes.to_json,
hashed_device_secret:)
end
def refresh_created_time
@refresh_created_time ||= web_sso_session_creation || Time.zone.now
end
def refresh_expiration_time
@refresh_expiration_time ||= refresh_created_time + client_config.refresh_token_duration
end
def get_hash(object)
Digest::SHA256.hexdigest(object)
end
def device_secret
return unless validated_credential.device_sso
@device_secret ||= SecureRandom.hex
end
def user_verification
@user_verification ||= validated_credential.user_verification
end
def user_attributes
@user_attributes ||= validated_credential.user_attributes
end
def user_uuid
@user_uuid ||= user_verification.user_account.id
end
def handle
@handle ||= SecureRandom.uuid
end
def client_config
@client_config ||= validated_credential.client_config
end
def web_sso_session_id
@web_sso_session_id ||= validated_credential.web_sso_session_id
end
def web_sso_session_creation
OAuthSession.find_by(id: web_sso_session_id)&.refresh_creation
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/user_code_map_creator.rb
|
# frozen_string_literal: true
module SignIn
class UserCodeMapCreator
attr_reader :state_payload,
:idme_uuid,
:logingov_uuid,
:credential_email,
:all_credential_emails,
:verified_icn,
:edipi,
:mhv_credential_uuid,
:request_ip,
:first_name,
:last_name,
:web_sso_session_id,
:credential_attributes_digest
def initialize(user_attributes:, state_payload:, verified_icn:, request_ip:)
@state_payload = state_payload
@idme_uuid = user_attributes[:idme_uuid]
@logingov_uuid = user_attributes[:logingov_uuid]
@credential_email = user_attributes[:csp_email]
@all_credential_emails = user_attributes[:all_csp_emails]
@edipi = user_attributes[:edipi]
@mhv_credential_uuid = user_attributes[:mhv_credential_uuid]
@verified_icn = verified_icn
@request_ip = request_ip
@first_name = user_attributes[:first_name]
@last_name = user_attributes[:last_name]
@web_sso_session_id = user_attributes[:session_id]
@credential_attributes_digest = user_attributes[:digest]
end
def perform
create_credential_email
create_user_acceptable_verified_credential
create_terms_code_container if needs_accepted_terms_of_use?
create_code_container
user_code_map
end
private
def create_credential_email
Login::UserCredentialEmailUpdater.new(credential_email:,
user_verification:).perform
end
def create_user_acceptable_verified_credential
Login::UserAcceptableVerifiedCredentialUpdater.new(user_account:).perform
end
def create_terms_code_container
TermsCodeContainer.new(code: terms_code, user_account_uuid: user_account.id).save!
end
def create_code_container
CodeContainer.new(code: login_code,
client_id: state_payload.client_id,
code_challenge: state_payload.code_challenge,
user_verification_id: user_verification.id,
credential_email:,
user_attributes: access_token_attributes,
device_sso:,
web_sso_session_id:).save!
end
def device_sso
state_payload.scope == Constants::Auth::DEVICE_SSO
end
def user_code_map
@user_code_map ||= UserCodeMap.new(login_code:,
type: state_payload.type,
client_state: state_payload.client_state,
client_config:,
terms_code:)
end
def user_verification
@user_verification ||= Login::UserVerifier.new(login_type: sign_in[:service_name],
auth_broker: sign_in[:auth_broker],
mhv_uuid: mhv_credential_uuid,
idme_uuid:,
dslogon_uuid: edipi,
logingov_uuid:,
icn: verified_icn,
credential_attributes_digest:).perform
end
def user_account
@user_account ||= user_verification.user_account
end
def sign_in
@sign_in ||= {
service_name: state_payload.type,
auth_broker: Constants::Auth::BROKER_CODE,
client_id: state_payload.client_id
}
end
def access_token_attributes
{ first_name:,
last_name:,
email: credential_email,
all_emails: all_credential_emails }.compact
end
def needs_accepted_terms_of_use?
client_config.va_terms_enforced? && user_account.needs_accepted_terms_of_use?
end
def client_config
@client_config ||= SignIn::ClientConfig.find_by!(client_id: state_payload.client_id)
end
def login_code
@login_code ||= SecureRandom.uuid
end
def terms_code
return nil unless needs_accepted_terms_of_use?
@terms_code ||= SecureRandom.uuid
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/redirect_url_generator.rb
|
# frozen_string_literal: true
module SignIn
class RedirectUrlGenerator
attr_reader :redirect_uri, :params_hash, :terms_code, :terms_redirect_uri
def initialize(redirect_uri:, terms_redirect_uri: nil, terms_code: nil, params_hash: {})
@redirect_uri = redirect_uri
@terms_redirect_uri = terms_redirect_uri
@terms_code = terms_code
@params_hash = params_hash
end
def perform
renderer.render(template: 'oauth_get_form',
locals: { url: full_redirect_uri },
format: :html)
end
private
def full_redirect_uri
if terms_code
Rails.logger.info('Redirecting to /terms-of-use', type: :sis)
return terms_of_use_redirect_url
end
original_redirect_uri_with_params
end
def original_redirect_uri_with_params
"#{redirect_uri}?#{params_hash.to_query}"
end
def renderer
@renderer ||= begin
renderer = ActionController::Base.renderer
renderer.controller.prepend_view_path(Rails.root.join('lib', 'sign_in', 'templates'))
renderer
end
end
def terms_of_use_redirect_url
"#{terms_redirect_uri}?#{terms_of_use_params.to_query}"
end
def terms_of_use_params
{ redirect_url: original_redirect_uri_with_params, terms_code: }
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/refresh_token_encryptor.rb
|
# frozen_string_literal: true
module SignIn
class RefreshTokenEncryptor
attr_reader :refresh_token, :version, :nonce
def initialize(refresh_token:)
@refresh_token = refresh_token
validate_input
@version = refresh_token.version
@nonce = refresh_token.nonce
end
def perform
encrypted_refresh_token = serialize_and_encrypt_refresh_token
build_refresh_token_string(encrypted_refresh_token)
end
private
def validate_input
unless refresh_token.version && refresh_token.nonce
raise Errors::RefreshTokenMalformedError.new message: 'Refresh token is malformed'
end
end
def build_refresh_token_string(encrypted_refresh_token)
string_array = []
string_array[Constants::RefreshToken::ENCRYPTED_POSITION] = encrypted_refresh_token
string_array[Constants::RefreshToken::NONCE_POSITION] = nonce
string_array[Constants::RefreshToken::VERSION_POSITION] = version
string_array.join('.')
end
def serialize_and_encrypt_refresh_token
serialized_refresh_token = refresh_token.to_json
message_encryptor.encrypt(serialized_refresh_token)
end
def message_encryptor
KmsEncrypted::Box.new
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/assertion_validator.rb
|
# frozen_string_literal: true
module SignIn
class AssertionValidator < BaseAssertionValidator
attr_reader :assertion, :decoded_assertion, :service_account_config
def initialize(assertion:)
super()
@assertion = assertion
end
def perform
@decoded_assertion = decode_assertion!(assertion)
validate_issuer
validate_scopes
validate_user_attributes
create_new_access_token
end
private
delegate :service_account_id, to: :service_account_config
def create_new_access_token
ServiceAccountAccessToken.new(
service_account_id:,
audience: config_audience,
scopes: assertion_scopes,
user_attributes: assertion_user_attributes,
user_identifier: assertion_user_identifier
)
end
def validate_issuer
if assertion_iss != service_account_id && assertion_iss != config_audience
raise Errors::ServiceAccountAssertionAttributesError.new message: 'Invalid issuer'
end
end
def validate_scopes
return if assertion_scopes_in_config?
raise Errors::ServiceAccountAssertionAttributesError.new message: 'Invalid scopes'
end
def validate_user_attributes
if (assertion_user_attributes.keys.map(&:to_s) - service_account_config.access_token_user_attributes).any?
raise Errors::ServiceAccountAssertionAttributesError.new message: 'Invalid user attributes'
end
end
def jwt_decode_options
{
aud: [token_route],
verify_aud: true,
verify_iat: true,
verify_expiration: true,
required_claims: %w[iat sub exp iss],
algorithms: [algorithm]
}
end
def jwt_keyfinder(header, payload)
@service_account_config = find_service_account_config(payload)
super(header, payload)
end
def active_certs
@active_certs ||= service_account_config.certs.active
end
def find_service_account_config(payload)
service_account_id = payload['service_account_id'] || payload['iss']
if service_account_id.blank?
raise Errors::ServiceAccountAssertionAttributesError.new message: 'Invalid client identifier'
end
ServiceAccountConfig.find_by!(service_account_id:)
rescue ActiveRecord::RecordNotFound
raise Errors::ServiceAccountConfigNotFound.new message: 'Service account config not found'
end
def assertion_scopes_in_config?
return service_account_config.scopes.blank? if assertion_scopes.blank?
(assertion_scopes - service_account_config.scopes).empty?
end
def config_audience = service_account_config.access_token_audience
def assertion_scopes = Array(decoded_assertion[:scopes])
def assertion_user_attributes = decoded_assertion[:user_attributes] || {}
def assertion_user_identifier = decoded_assertion[:sub]
def assertion_iss = decoded_assertion[:iss]
def attributes_error_class = Errors::ServiceAccountAssertionAttributesError
def signature_mismatch_error_class = Errors::AssertionSignatureMismatchError
def expired_error_class = Errors::AssertionExpiredError
def malformed_error_class = Errors::AssertionMalformedJWTError
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/token_params_validator.rb
|
# frozen_string_literal: true
module SignIn
class TokenParamsValidator
include ActiveModel::Validations
attr_reader :grant_type, :code, :code_verifier, :client_assertion, :client_assertion_type, :assertion,
:subject_token, :subject_token_type, :actor_token, :actor_token_type, :client_id
# rubocop:disable Rails/I18nLocaleTexts
validates :grant_type, inclusion: {
in: [
Constants::Auth::AUTH_CODE_GRANT,
Constants::Auth::JWT_BEARER_GRANT,
Constants::Auth::TOKEN_EXCHANGE_GRANT
],
message: 'is not valid'
}
with_options if: :authorization_code_grant? do
validates :client_assertion_type, inclusion: {
in: [Constants::Urn::JWT_BEARER_CLIENT_AUTHENTICATION],
message: 'is not valid'
}, if: :client_assertion_type_present?
validates :code, :client_assertion, :client_assertion_type, presence: true, if: :client_assertion_type_present?
validates :code, :code_verifier, presence: true, unless: :client_assertion_type_present?
end
# rubocop:enable Rails/I18nLocaleTexts
with_options if: :jwt_bearer_grant? do
validates :assertion, presence: true
end
with_options if: :token_exchange_grant? do
validates :subject_token, :subject_token_type, :actor_token, :actor_token_type, :client_id, presence: true
end
def initialize(params:)
@grant_type = params[:grant_type]
@code = params[:code]
@code_verifier = params[:code_verifier]
@client_assertion = params[:client_assertion]
@client_assertion_type = params[:client_assertion_type]
@assertion = params[:assertion]
@subject_token = params[:subject_token]
@subject_token_type = params[:subject_token_type]
@actor_token = params[:actor_token]
@actor_token_type = params[:actor_token_type]
@client_id = params[:client_id]
end
def perform
validate!
rescue ActiveModel::ValidationError => e
log_error_and_raise(e.model.errors.full_messages.to_sentence)
rescue => e
log_error_and_raise(e.message)
end
private
def authorization_code_grant?
grant_type == Constants::Auth::AUTH_CODE_GRANT
end
def jwt_bearer_grant?
grant_type == Constants::Auth::JWT_BEARER_GRANT
end
def token_exchange_grant?
grant_type == Constants::Auth::TOKEN_EXCHANGE_GRANT
end
def client_assertion_type_present?
client_assertion_type.present?
end
def log_error_and_raise(message)
Rails.logger.error('[SignIn][TokenParamsValidator] error', { errors: message })
raise Errors::MalformedParamsError.new(message:)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/session_spawner.rb
|
# frozen_string_literal: true
module SignIn
class SessionSpawner
include ActiveModel::Validations
attr_reader :credential_email,
:user_verification,
:user_attributes,
:client_config,
:hashed_device_secret,
:refresh_creation
validate :validate_credential_lock!,
:validate_terms_of_use!
def initialize(current_session:, new_session_client_config:)
@credential_email = current_session.credential_email
@user_verification = current_session.user_verification
@user_attributes = current_session.user_attributes
@client_config = new_session_client_config
@hashed_device_secret = current_session.hashed_device_secret
@refresh_creation = current_session.refresh_creation
end
def perform
validate!
SessionContainer.new(
session: create_new_session,
refresh_token:,
access_token: create_new_access_token,
anti_csrf_token:,
client_config:
)
end
private
def validate_credential_lock!
raise SignIn::Errors::CredentialLockedError.new message: 'Credential is locked' if user_verification.locked
end
def validate_terms_of_use!
if client_config.enforced_terms.present? && user_verification.user_account.needs_accepted_terms_of_use?
raise Errors::TermsOfUseNotAcceptedError.new message: 'Terms of Use has not been accepted'
end
end
def anti_csrf_token
@anti_csrf_token ||= SecureRandom.hex
end
def refresh_token
@refresh_token ||= create_new_refresh_token(parent_refresh_token_hash:)
end
def double_parent_refresh_token_hash
@double_parent_refresh_token_hash ||= get_hash(parent_refresh_token_hash)
end
def refresh_token_hash
@refresh_token_hash ||= get_hash(refresh_token.to_json)
end
def parent_refresh_token_hash
@parent_refresh_token_hash ||= get_hash(create_new_refresh_token.to_json)
end
def create_new_access_token
AccessToken.new(
session_handle: handle,
client_id: client_config.client_id,
user_uuid:,
audience: AccessTokenAudienceGenerator.new(client_config:).perform,
refresh_token_hash:,
parent_refresh_token_hash:,
anti_csrf_token:,
last_regeneration_time:,
user_attributes: JSON.parse(user_attributes)
)
end
def create_new_refresh_token(parent_refresh_token_hash: nil)
RefreshToken.new(
session_handle: handle,
user_uuid:,
parent_refresh_token_hash:,
anti_csrf_token:
)
end
def create_new_session
OAuthSession.create!(
user_account: user_verification.user_account,
user_verification:,
client_id: client_config.client_id,
credential_email:,
handle:,
hashed_refresh_token: double_parent_refresh_token_hash,
refresh_expiration: refresh_expiration_time,
refresh_creation:,
user_attributes:,
hashed_device_secret:
)
end
def refresh_expiration_time
@refresh_expiration_time ||= last_regeneration_time + client_config.refresh_token_duration
end
def last_regeneration_time
@last_regeneration_time ||= Time.zone.now
end
def get_hash(object)
Digest::SHA256.hexdigest(object)
end
def user_uuid
@user_uuid ||= user_verification.user_account.id
end
def handle
@handle ||= SecureRandom.uuid
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/openid_connect_certificates_presenter.rb
|
# frozen_string_literal: true
module SignIn
class OpenidConnectCertificatesPresenter
def perform
{
keys: public_keys_jwk
}
end
private
def public_keys_jwk
public_keys.map do |public_key|
JWT::JWK.new(public_key, { alg: 'RS256', use: 'sig' }).export
end
end
def public_keys
public_keys = [private_key.public_key]
old_key_file_path = IdentitySettings.sign_in.jwt_old_encode_key
public_keys.push private_key(file_path: old_key_file_path).public_key if old_key_file_path
public_keys
end
def private_key(file_path: IdentitySettings.sign_in.jwt_encode_key)
OpenSSL::PKey::RSA.new(File.read(file_path))
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/attribute_validator.rb
|
# frozen_string_literal: true
module SignIn
class AttributeValidator
def initialize(user_attributes:)
@user_attributes = user_attributes
end
def perform
return unless verified_credential?
validate_credential_attributes
if mhv_auth?
validate_mhv_mpi_record
validate_existing_mpi_attributes
elsif mpi_record_exists?
validate_existing_mpi_attributes
validate_sec_id
update_mpi_correlation_record
else
add_mpi_user
validate_existing_mpi_attributes
end
verified_icn
end
private
attr_reader :user_attributes
def validate_existing_mpi_attributes
check_lock_flag(mpi_response_profile.id_theft_flag, 'Theft Flag', Constants::ErrorCode::MPI_LOCKED_ACCOUNT)
check_lock_flag(mpi_response_profile.deceased_date, 'Death Flag', Constants::ErrorCode::MPI_LOCKED_ACCOUNT)
check_id_mismatch(mpi_response_profile.edipis, 'EDIPI', Constants::ErrorCode::MULTIPLE_EDIPI)
check_id_mismatch(mpi_response_profile.participant_ids, 'CORP_ID', Constants::ErrorCode::MULTIPLE_CORP_ID)
check_id_mismatch(mpi_response_profile.mhv_iens, 'MHV_ID', Constants::ErrorCode::MULTIPLE_MHV_IEN,
raise_error: false)
end
def validate_sec_id
return if sec_id.present?
sign_in_logger.info('mpi record missing sec_id', icn: verified_icn, pce_status: sec_id_pce_status)
end
def add_mpi_user
add_person_response = mpi_service.add_person_implicit_search(first_name:,
last_name:,
ssn:,
birth_date:,
email: credential_email,
address:,
idme_uuid:,
logingov_uuid:)
unless add_person_response.ok?
handle_error('User MPI record cannot be created',
Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE,
error: Errors::MPIUserCreationFailedError)
end
end
def update_mpi_correlation_record
return if auto_uplevel
user_attribute_mismatch_checks
return unless credential_attributes_digest_changed?
update_profile_response = mpi_service.update_profile(last_name:,
ssn:,
birth_date:,
icn: verified_icn,
email: credential_email,
address:,
idme_uuid:,
logingov_uuid:,
edipi:,
first_name:)
unless update_profile_response&.ok?
handle_error('User MPI record cannot be updated', Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE)
end
end
def user_attribute_mismatch_checks
attribute_mismatch_check(:first_name, first_name, mpi_response_profile.given_names.first)
attribute_mismatch_check(:last_name, last_name, mpi_response_profile.family_name)
attribute_mismatch_check(:birth_date, birth_date, mpi_response_profile.birth_date)
attribute_mismatch_check(:ssn, ssn, mpi_response_profile.ssn, prevent_auth: true)
end
def validate_credential_attributes
if mhv_auth?
credential_attribute_check(:icn, mhv_icn)
credential_attribute_check(:mhv_uuid, mhv_credential_uuid)
else
credential_attribute_check(:dslogon_uuid, edipi) if dslogon_auth?
credential_attribute_check(:last_name, last_name) unless auto_uplevel
credential_attribute_check(:birth_date, birth_date) unless auto_uplevel
end
credential_attribute_check(:uuid, logingov_uuid || idme_uuid)
credential_attribute_check(:email, credential_email)
end
def credential_attribute_check(type, credential_attribute)
return if credential_attribute.present?
handle_error("Missing attribute in credential: #{type}",
Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE,
error: Errors::CredentialMissingAttributeError)
end
def attribute_mismatch_check(type, credential_attribute, mpi_attribute, prevent_auth: false)
return unless mpi_attribute
if scrub_attribute(credential_attribute) != scrub_attribute(mpi_attribute)
error = prevent_auth ? Errors::AttributeMismatchError : nil
handle_error("Attribute mismatch, #{type} in credential does not match MPI attribute",
Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE,
error:)
end
end
def scrub_attribute(attribute)
attribute.tr('-', '').downcase
end
def validate_mhv_mpi_record
unless mpi_response_profile
handle_error('No MPI Record for MHV Account',
Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE,
error: Errors::MHVMissingMPIRecordError)
end
attribute_mismatch_check(:icn, mhv_icn, verified_icn)
end
def check_lock_flag(attribute, attribute_description, code)
handle_error("#{attribute_description} Detected", code, error: Errors::MPILockedAccountError) if attribute
end
def check_id_mismatch(id_array, id_description, code, raise_error: true)
if id_array && id_array.compact.uniq.size > 1
handle_error("User attributes contain multiple distinct #{id_description} values",
code,
error: Errors::MPIMalformedAccountError, raise_error:)
end
end
def credential_attributes_digest_changed?
user_verification&.credential_attributes_digest != credential_attributes_digest
end
def handle_error(error_message, error_code, error: nil, raise_error: true)
sign_in_logger.info('attribute validator error', { errors: error_message,
credential_uuid:,
mhv_icn:,
type: service_name }.compact)
raise error.new message: error_message, code: error_code if error && raise_error
end
def mpi_response_profile
@mpi_response_profile ||=
if mhv_credential_uuid
mpi_service.find_profile_by_identifier(identifier: mhv_credential_uuid,
identifier_type: MPI::Constants::MHV_UUID)&.profile
elsif idme_uuid
mpi_service.find_profile_by_identifier(identifier: idme_uuid,
identifier_type: MPI::Constants::IDME_UUID)&.profile
elsif logingov_uuid
mpi_service.find_profile_by_identifier(identifier: logingov_uuid,
identifier_type: MPI::Constants::LOGINGOV_UUID)&.profile
elsif mhv_icn
mpi_service.find_profile_by_identifier(identifier: mhv_icn, identifier_type: MPI::Constants::ICN)&.profile
end
end
def verified_icn
@verified_icn ||= mpi_response_profile.icn
end
def sec_id
@sec_id ||= mpi_response_profile.sec_id
end
def sec_id_pce_status
@sec_id_pce_status ||= mpi_response_profile.full_mvi_ids.any? { |id| id.include? '200PROV^USDVA^PCE' }
end
def credential_uuid
@credential_uuid ||= idme_uuid || logingov_uuid
end
def mpi_record_exists?
mpi_response_profile.present?
end
def mpi_service
@mpi_service ||= MPI::Service.new
end
def loa
@loa ||= { current: Constants::Auth::LOA_THREE, highest: Constants::Auth::LOA_THREE }
end
def mhv_auth?
service_name == Constants::Auth::MHV
end
def dslogon_auth?
service_name == Constants::Auth::DSLOGON
end
def verified_credential?
current_ial == Constants::Auth::IAL_TWO
end
def user_verification
@user_verification ||= UserVerification.find_by_type(service_name, user_verification_identifier)
end
def idme_uuid = user_attributes[:idme_uuid]
def logingov_uuid = user_attributes[:logingov_uuid]
def auto_uplevel = user_attributes[:auto_uplevel]
def current_ial = user_attributes[:current_ial]
def service_name = user_attributes[:service_name]
def first_name = user_attributes[:first_name]
def last_name = user_attributes[:last_name]
def birth_date = user_attributes[:birth_date]
def credential_email = user_attributes[:csp_email]
def address = user_attributes[:address]
def ssn = user_attributes[:ssn]
def mhv_icn = user_attributes[:mhv_icn]
def edipi = user_attributes[:edipi]
def mhv_credential_uuid = user_attributes[:mhv_credential_uuid]
def credential_attributes_digest = user_attributes[:digest]
def user_verification_identifier
case service_name
when Constants::Auth::MHV then mhv_credential_uuid
when Constants::Auth::IDME then idme_uuid
when Constants::Auth::DSLOGON then edipi
when Constants::Auth::LOGINGOV then logingov_uuid
end
end
def sign_in_logger
@sign_in_logger = Logger.new(prefix: self.class)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/acr_translator.rb
|
# frozen_string_literal: true
module SignIn
class AcrTranslator
attr_reader :acr, :type, :uplevel
def initialize(acr:, type:, uplevel: false)
@acr = acr
@type = type
@uplevel = uplevel
end
def perform
{ acr: translate_acr, acr_comparison: translate_acr_comparison }.compact
end
private
def translate_acr
case type
when Constants::Auth::IDME
translate_idme_values
when Constants::Auth::LOGINGOV
translate_logingov_values
when Constants::Auth::DSLOGON
translate_dslogon_values
when Constants::Auth::MHV
translate_mhv_values
else
raise Errors::InvalidTypeError.new message: 'Invalid Type value'
end
end
def translate_acr_comparison
type == Constants::Auth::IDME && acr == 'min' && !uplevel ? Constants::Auth::IDME_COMPARISON_MINIMUM : nil
end
def translate_idme_values
case acr
when 'loa1'
Constants::Auth::IDME_LOA1
when 'loa3'
Constants::Auth::IDME_LOA3_FORCE
when 'ial2'
ial2_enabled? ? Constants::Auth::IDME_IAL2 : invalid_acr!
when 'min'
uplevel ? Constants::Auth::IDME_LOA3 : Constants::Auth::IDME_LOA1
else
invalid_acr!
end
end
def translate_dslogon_values
case acr
when 'loa1', 'loa3', 'min'
Constants::Auth::IDME_DSLOGON_LOA1
else
raise Errors::InvalidAcrError.new message: 'Invalid ACR for dslogon'
end
end
def translate_mhv_values
case acr
when 'loa1', 'loa3', 'min'
Constants::Auth::IDME_MHV_LOA1
else
raise Errors::InvalidAcrError.new message: 'Invalid ACR for mhv'
end
end
def translate_logingov_values
case acr
when 'ial1'
Constants::Auth::LOGIN_GOV_IAL1
when 'ial2'
Constants::Auth::LOGIN_GOV_IAL2
when 'min'
uplevel ? Constants::Auth::LOGIN_GOV_IAL2 : Constants::Auth::LOGIN_GOV_IAL0
else
raise Errors::InvalidAcrError.new message: 'Invalid ACR for logingov'
end
end
def ial2_enabled?
Flipper.enabled?(:identity_ial2_enforcement) && Settings.vsp_environment != 'production'
end
def invalid_acr!
raise Errors::InvalidAcrError.new message: 'Invalid ACR for idme'
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/state_payload_jwt_encoder.rb
|
# frozen_string_literal: true
module SignIn
class StatePayloadJwtEncoder
attr_reader :acr, :client_config, :type, :code_challenge, :code_challenge_method, :client_state, :scope
# rubocop:disable Metrics/ParameterLists
def initialize(code_challenge:, code_challenge_method:, acr:, client_config:, type:, scope: nil, client_state: nil)
@acr = acr
@client_config = client_config
@type = type
@code_challenge = code_challenge
@code_challenge_method = code_challenge_method
@client_state = client_state
@scope = scope
end
# rubocop:enable Metrics/ParameterLists
def perform
validate_pkce_params! if client_config.pkce?
validate_scope!
validate_state_payload!
save_state_code
jwt_encode_state_payload
end
private
def validate_pkce_params!
validate_code_challenge_method!
validate_code_challenge!
end
def validate_scope!
raise Errors::InvalidScope.new message: 'Scope is not valid for Client' if sso_not_enabled_for_device_sso_scope?
end
def validate_code_challenge_method!
if code_challenge_method != Constants::Auth::CODE_CHALLENGE_METHOD
raise Errors::CodeChallengeMethodMismatchError.new message: 'Code Challenge Method is not valid'
end
end
def validate_code_challenge!
raise Errors::CodeChallengeMalformedError.new message: 'Code Challenge is not valid' if code_challenge.blank?
end
def validate_state_payload!
state_payload
rescue ActiveModel::ValidationError
raise Errors::StatePayloadError.new message: 'Attributes are not valid'
end
def jwt_encode_state_payload
JWT.encode(jwt_payload, private_key, Constants::Auth::JWT_ENCODE_ALGORITHM)
end
def save_state_code
StateCode.new(code: state_code).save!
end
def jwt_payload
{
acr: state_payload.acr,
type: state_payload.type,
client_id: state_payload.client_id,
code_challenge: state_payload.code_challenge,
client_state: state_payload.client_state,
code: state_payload.code,
created_at: state_payload.created_at,
scope: state_payload.scope
}
end
def state_payload
@state_payload ||= StatePayload.new(acr:,
type:,
client_id: client_config.client_id,
code_challenge: remove_base64_padding(code_challenge),
code: state_code,
client_state:,
scope:)
end
def state_code
@state_code ||= SecureRandom.hex
end
def sso_not_enabled_for_device_sso_scope?
scope == Constants::Auth::DEVICE_SSO && !client_config.api_sso_enabled?
end
def remove_base64_padding(data)
return unless client_config.pkce? && data
Base64.urlsafe_encode64(Base64.urlsafe_decode64(data.to_s), padding: false)
rescue ArgumentError
raise Errors::CodeChallengeMalformedError.new message: 'Code Challenge is not valid'
end
def private_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_encode_key))
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/revoke_sessions_for_user.rb
|
# frozen_string_literal: true
module SignIn
class RevokeSessionsForUser
attr_reader :user_account, :sessions
def initialize(user_account:)
@user_account = user_account
end
def perform
delete_sessions!
end
private
def delete_sessions!
OAuthSession.where(user_account:).destroy_all
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/access_token_jwt_decoder.rb
|
# frozen_string_literal: true
module SignIn
class AccessTokenJwtDecoder
attr_reader :access_token_jwt
def initialize(access_token_jwt:)
@access_token_jwt = access_token_jwt
end
def perform(with_validation: true)
decoded_token = jwt_decode_access_token(with_validation)
AccessToken.new(
uuid: decoded_token.jti,
session_handle: decoded_token.session_handle,
client_id: decoded_token.client_id,
user_uuid: decoded_token.sub,
user_attributes: decoded_token.user_attributes,
audience: decoded_token.aud,
refresh_token_hash: decoded_token.refresh_token_hash,
device_secret_hash: decoded_token.device_secret_hash,
anti_csrf_token: decoded_token.anti_csrf_token,
last_regeneration_time: Time.zone.at(decoded_token.last_regeneration_time),
parent_refresh_token_hash: decoded_token.parent_refresh_token_hash,
version: decoded_token.version,
expiration_time: Time.zone.at(decoded_token.exp),
created_time: Time.zone.at(decoded_token.iat)
)
end
private
def jwt_decode_access_token(with_validation)
decoded_jwt = JWT.decode(
access_token_jwt,
decode_key_array,
with_validation,
{
verify_expiration: with_validation,
algorithm: Constants::AccessToken::JWT_ENCODE_ALGORITHM
}
)&.first
OpenStruct.new(decoded_jwt)
rescue JWT::VerificationError
raise Errors::AccessTokenSignatureMismatchError.new message: 'Access token body does not match signature'
rescue JWT::ExpiredSignature
raise Errors::AccessTokenExpiredError.new message: 'Access token has expired'
rescue JWT::DecodeError
raise Errors::AccessTokenMalformedJWTError.new message: 'Access token JWT is malformed'
end
def decode_key_array
[public_key, public_key_old].compact
end
def public_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_encode_key)).public_key
end
def public_key_old
return unless IdentitySettings.sign_in.jwt_old_encode_key
OpenSSL::PKey::RSA.new(File.read(IdentitySettings.sign_in.jwt_old_encode_key)).public_key
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/user_loader.rb
|
# frozen_string_literal: true
module SignIn
class UserLoader
CERNER_ELIGIBLE_COOKIE_NAME = 'CERNER_ELIGIBLE'
attr_reader :access_token, :request_ip, :cookies
def initialize(access_token:, request_ip:, cookies:)
@access_token = access_token
@request_ip = request_ip
@cookies = cookies
end
def perform
find_valid_user || reload_user
end
private
def find_valid_user
user = User.find(access_token.user_uuid)
return unless user&.identity && user&.session_handle == access_token.session_handle
user
end
def reload_user # rubocop:disable Metrics/MethodLength
validate_account_and_session
user_identity.uuid = access_token.user_uuid
current_user.uuid = access_token.user_uuid
current_user.last_signed_in = session.created_at
current_user.fingerprint = request_ip
current_user.session_handle = access_token.session_handle
current_user.user_verification_id = user_verification.id
current_user.save && user_identity.save
current_user.invalidate_mpi_cache
current_user.validate_mpi_profile
current_user.create_mhv_account_async
current_user.provision_cerner_async(source: :sis)
set_cerner_eligibility_cookie
context = {
user_uuid: current_user.uuid,
credential_uuid: user_verification.credential_identifier,
icn: user_account.icn,
sign_in:
}
SignIn::Logger.new(prefix: self.class).info('reload_user', context)
current_user
end
def validate_account_and_session
raise Errors::SessionNotFoundError.new message: 'Invalid Session Handle' unless session
end
def set_cerner_eligibility_cookie
cookies.permanent[CERNER_ELIGIBLE_COOKIE_NAME] = {
value: current_user.cerner_eligible?,
domain: IdentitySettings.sign_in.info_cookie_domain
}
end
def user_attributes
{
mhv_icn: user_account.icn,
idme_uuid: user_verification.idme_uuid || user_verification.backing_idme_uuid,
logingov_uuid: user_verification.logingov_uuid,
loa:,
email: session.credential_email,
authn_context:,
multifactor:,
sign_in:
}
end
def loa
current_loa = user_is_verified? ? Constants::Auth::LOA_THREE : Constants::Auth::LOA_ONE
{ current: current_loa, highest: current_loa }
end
def sign_in
{ service_name: user_verification.credential_type,
client_id: session.client_id,
auth_broker: Constants::Auth::BROKER_CODE }
end
def authn_context
case user_verification.credential_type
when Constants::Auth::IDME
user_is_verified? ? Constants::Auth::IDME_LOA3 : Constants::Auth::IDME_LOA1
when Constants::Auth::DSLOGON
user_is_verified? ? Constants::Auth::IDME_DSLOGON_LOA3 : Constants::Auth::IDME_DSLOGON_LOA1
when Constants::Auth::MHV
user_is_verified? ? Constants::Auth::IDME_MHV_LOA3 : Constants::Auth::IDME_MHV_LOA1
when Constants::Auth::LOGINGOV
user_is_verified? ? Constants::Auth::LOGIN_GOV_IAL2 : Constants::Auth::LOGIN_GOV_IAL1
end
end
def multifactor
user_is_verified? && idme_or_logingov_service
end
def idme_or_logingov_service
[Constants::Auth::IDME, Constants::Auth::LOGINGOV].include?(sign_in[:service_name])
end
def user_is_verified?
user_account.verified?
end
def session
@session ||= OAuthSession.find_by(handle: access_token.session_handle)
end
def user_account
@user_account ||= session.user_account
end
def user_verification
@user_verification ||= session.user_verification
end
def user_identity
@user_identity ||= UserIdentity.new(user_attributes)
end
def current_user
return @current_user if @current_user
user = User.new
user.instance_variable_set(:@identity, user_identity)
@current_user = user
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/sign_in/token_response_generator.rb
|
# frozen_string_literal: true
module SignIn
class TokenResponseGenerator
attr_reader :grant_type, :code, :code_verifier, :client_assertion, :client_assertion_type, :assertion,
:subject_token, :subject_token_type, :actor_token, :actor_token_type, :client_id, :cookies,
:request_attributes
def initialize(params:, cookies:, request_attributes:)
@grant_type = params[:grant_type]
@code = params[:code]
@code_verifier = params[:code_verifier]
@client_assertion = params[:client_assertion]
@client_assertion_type = params[:client_assertion_type]
@assertion = params[:assertion]
@subject_token = params[:subject_token]
@subject_token_type = params[:subject_token_type]
@actor_token = params[:actor_token]
@actor_token_type = params[:actor_token_type]
@client_id = params[:client_id]
@cookies = cookies
@request_attributes = request_attributes
end
def perform
case grant_type
when Constants::Auth::AUTH_CODE_GRANT
generate_client_tokens
when Constants::Auth::JWT_BEARER_GRANT
generate_service_account_token
when Constants::Auth::TOKEN_EXCHANGE_GRANT
generate_token_exchange_response
else
raise Errors::MalformedParamsError.new(message: 'Grant type is not valid')
end
end
private
def generate_client_tokens
validated_credential = CodeValidator.new(code:, code_verifier:, client_assertion:,
client_assertion_type:).perform
session_container = SessionCreator.new(validated_credential:).perform
UserAudit.logger.success(event: :sign_in, user_verification: validated_credential.user_verification)
sign_in_logger.info('session created', session_container.access_token.to_s)
TokenSerializer.new(session_container:, cookies:).perform
end
def generate_service_account_token
service_account_access_token = AssertionValidator.new(assertion:).perform
sign_in_logger.info('generated service account token', service_account_access_token.to_s)
encoded_access_token = ServiceAccountAccessTokenJwtEncoder.new(service_account_access_token:).perform
serialized_service_account_token(access_token: encoded_access_token)
end
def generate_token_exchange_response
exchanged_container = TokenExchanger.new(subject_token:, subject_token_type:, actor_token:,
actor_token_type:, client_id:).perform
sign_in_logger.info('token exchanged', exchanged_container.access_token.to_s)
TokenSerializer.new(session_container: exchanged_container, cookies:).perform
end
def sign_in_logger
@sign_in_logger ||= Logger.new(prefix: self.class)
end
def serialized_service_account_token(access_token:)
{
data: {
access_token:
}
}
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/auth_sso/session_validator.rb
|
# frozen_string_literal: true
module SignIn
module AuthSSO
class SessionValidator
def initialize(access_token:, client_id:)
@access_token = access_token
@client_id = client_id
end
def perform
validate_session!
validate_client_configs!
validate_credential_level_and_type!
auth_sso_user_attributes
end
private
attr_reader :access_token, :client_id
def auth_sso_user_attributes
{
idme_uuid: user_verification.idme_uuid || user_verification.backing_idme_uuid,
logingov_uuid: user_verification.logingov_uuid,
credential_email: session.credential_email,
edipi: user_verification.dslogon_uuid,
mhv_credential_uuid: user_verification.mhv_uuid,
first_name: session_user_attributes[:first_name],
last_name: session_user_attributes[:last_name],
acr: session_assurance_level,
type: user_verification.credential_type,
icn: user_verification.user_account.icn,
session_id: session.id
}
end
def validate_session!
unless access_token
raise Errors::AccessTokenUnauthenticatedError.new(message: 'Access token is not authenticated')
end
raise Errors::SessionNotAuthorizedError.new(message: 'Session not authorized') unless session
end
def validate_client_configs!
unless client_config.api_sso_enabled? && session_client_config.web_sso_enabled?
raise Errors::InvalidClientConfigError.new message: 'SSO requested for client without shared sessions'
end
end
def validate_credential_level_and_type!
unless client_config.valid_credential_service_provider?(user_verification.credential_type)
raise Errors::InvalidCredentialLevelError.new(message: 'Invalid credential service provider')
end
unless client_config.valid_service_level?(session_assurance_level)
raise Errors::InvalidCredentialLevelError.new(message: 'Invalid service level')
end
end
def client_config
@client_config ||= ClientConfig.find_by(client_id:)
end
def user_verification
@user_verification ||= session.user_verification
end
def session
@session ||= OAuthSession.find_by(handle: access_token.session_handle)
end
def session_client_config
@session_client_config ||= ClientConfig.find_by(client_id: session.client_id)
end
def session_user_attributes
@session_user_attributes ||= session.user_attributes_hash
end
def session_assurance_level
if user_verification.credential_type == Constants::Auth::LOGINGOV
user_verification.verified? ? Constants::Auth::IAL2 : Constants::Auth::IAL1
else
user_verification.verified? ? Constants::Auth::LOA3 : Constants::Auth::LOA1
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/error_code.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module ErrorCode
IDME_VERIFICATION_DENIED = '001'
GENERIC_EXTERNAL_ISSUE = '007'
LOGINGOV_VERIFICATION_DENIED = '009'
MULTIPLE_MHV_IEN = '101'
MULTIPLE_EDIPI = '102'
MULTIPLE_CORP_ID = '106'
MPI_LOCKED_ACCOUNT = '107'
MHV_UNVERIFIED_BLOCKED = '108'
INVALID_REQUEST = '400'
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/statsd.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module Statsd
STATSD_SIS_AUTHORIZE_SUCCESS = 'api.sis.auth.success'
STATSD_SIS_AUTHORIZE_FAILURE = 'api.sis.auth.failure'
STATSD_SIS_AUTHORIZE_SSO_SUCCESS = 'api.sis.auth_sso.success'
STATSD_SIS_AUTHORIZE_SSO_FAILURE = 'api.sis.auth_sso.failure'
STATSD_SIS_AUTHORIZE_SSO_REDIRECT = 'api.sis.auth_sso.redirect'
STATSD_SIS_CALLBACK_SUCCESS = 'api.sis.callback.success'
STATSD_SIS_CALLBACK_FAILURE = 'api.sis.callback.failure'
STATSD_SIS_TOKEN_SUCCESS = 'api.sis.token.success'
STATSD_SIS_TOKEN_FAILURE = 'api.sis.token.failure'
STATSD_SIS_REFRESH_SUCCESS = 'api.sis.refresh.success'
STATSD_SIS_REFRESH_FAILURE = 'api.sis.refresh.failure'
STATSD_SIS_REVOKE_SUCCESS = 'api.sis.revoke.success'
STATSD_SIS_REVOKE_FAILURE = 'api.sis.revoke.failure'
STATSD_SIS_LOGOUT_SUCCESS = 'api.sis.logout.success'
STATSD_SIS_LOGOUT_FAILURE = 'api.sis.logout.failure'
STATSD_SIS_REVOKE_ALL_SESSIONS_SUCCESS = 'api.sis.revoke_all_sessions.success'
STATSD_SIS_REVOKE_ALL_SESSIONS_FAILURE = 'api.sis.revoke_all_sessions.failure'
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/refresh_token.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module RefreshToken
ENCRYPTED_ARRAY = [
ENCRYPTED_POSITION = 0,
NONCE_POSITION = 1,
VERSION_POSITION = 2
].freeze
VERSION_LIST = [
CURRENT_VERSION = 'V0'
].freeze
VALIDITY_LENGTHS = [VALIDITY_LENGTH_SHORT_MINUTES = 30.minutes, VALIDITY_LENGTH_LONG_DAYS = 45.days].freeze
SESSION_MAX_VALIDITY_LENGTH_DAYS = 45.days
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/urn.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module Urn
ACCESS_TOKEN = 'urn:ietf:params:oauth:token-type:access_token'
DEVICE_SECRET = 'urn:x-oath:params:oauth:token-type:device-secret'
JWT_BEARER_CLIENT_AUTHENTICATION = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
JWT_BEARER_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
TOKEN_EXCHANGE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/service_account_access_token.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module ServiceAccountAccessToken
ISSUER = 'va.gov sign in'
JWT_ENCODE_ALGORITHM = 'RS256'
USER_ATTRIBUTES = %w[icn type credential_id participant_id].freeze
VALIDITY_LENGTHS = [VALIDITY_LENGTH_SHORT_MINUTES = 5.minutes, VALIDITY_LENGTH_LONG_MINUTES = 30.minutes].freeze
VERSION_LIST = [
CURRENT_VERSION = 'V0'
].freeze
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/auth.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module Auth
ACCESS_TOKEN_COOKIE_NAME = 'vagov_access_token'
ACCESS_DENIED = 'access_denied'
ACR_VALUES = [LOA1 = 'loa1', LOA3 = 'loa3', IAL1 = 'ial1', IAL2 = 'ial2',
MIN = 'min'].freeze
ACR_TRANSLATIONS = [IDME_LOA1 = 'http://idmanagement.gov/ns/assurance/loa/1/vets',
IDME_LOA3 = 'http://idmanagement.gov/ns/assurance/loa/3',
IDME_LOA3_FORCE = 'http://idmanagement.gov/ns/assurance/loa/3_force',
IDME_IAL2 = 'http://idmanagement.gov/ns/assurance/ial/2/aal/2',
IDME_CLASSIC_LOA3 = 'classic_loa3',
IDME_DSLOGON_LOA1 = 'dslogon',
IDME_DSLOGON_LOA3 = 'dslogon_loa3',
IDME_MHV_LOA1 = 'myhealthevet',
IDME_MHV_LOA3 = 'myhealthevet_loa3',
IDME_COMPARISON_MINIMUM = 'comparison:minimum',
MHV_PREMIUM_VERIFIED = %w[Premium].freeze,
DSLOGON_PREMIUM_VERIFIED = [DSLOGON_ASSURANCE_TWO = '2',
DSLOGON_ASSURANCE_THREE = '3'].freeze,
LOGIN_GOV_IAL0 = 'http://idmanagement.gov/ns/assurance/ial/0',
LOGIN_GOV_IAL1 = 'http://idmanagement.gov/ns/assurance/ial/1',
LOGIN_GOV_IAL2 = 'http://idmanagement.gov/ns/assurance/ial/2'].freeze
ANTI_CSRF_COOKIE_NAME = 'vagov_anti_csrf_token'
AUTHENTICATION_TYPES = [COOKIE = 'cookie', API = 'api', MOCK = 'mock'].freeze
BROKER_CODE = 'sis'
CLIENT_STATE_MINIMUM_LENGTH = 22
CODE_CHALLENGE_METHOD = 'S256'
CSP_TYPES = [IDME = 'idme', LOGINGOV = 'logingov', DSLOGON = 'dslogon', MHV = 'mhv'].freeze
OPERATION_TYPES = [SIGN_UP = 'sign_up',
AUTHORIZE = 'authorize',
INTERSTITIAL_VERIFY = 'interstitial_verify',
INTERSTITIAL_SIGNUP = 'interstitial_signup',
VERIFY_CTA_AUTHENTICATED = 'verify_cta_authenticated',
VERIFY_PAGE_AUTHENTICATED = 'verify_page_authenticated',
VERIFY_PAGE_UNAUTHENTICATED = 'verify_page_unauthenticated'].freeze
GRANT_TYPES = [AUTH_CODE_GRANT = 'authorization_code',
JWT_BEARER_GRANT = Urn::JWT_BEARER_GRANT_TYPE,
TOKEN_EXCHANGE_GRANT = Urn::TOKEN_EXCHANGE_GRANT_TYPE].freeze
ENFORCED_TERMS = [VA_TERMS = 'VA'].freeze
ASSERTION_ENCODE_ALGORITHM = 'RS256'
IAL = [IAL_ONE = 1, IAL_TWO = 2].freeze
INFO_COOKIE_NAME = 'vagov_info_token'
JWT_ENCODE_ALGORITHM = 'RS256'
LOA = [LOA_ONE = 1, LOA_THREE = 3].freeze
REFRESH_ROUTE_PATH = '/v0/sign_in/refresh'
REFRESH_TOKEN_COOKIE_NAME = 'vagov_refresh_token'
SERVICE_ACCOUNT_ACCESS_TOKEN_COOKIE_NAME = 'service_account_access_token'
SCOPES = [DEVICE_SSO = 'device_sso'].freeze
TOKEN_ROUTE_PATH = '/v0/sign_in/token'
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/constants/access_token.rb
|
# frozen_string_literal: true
module SignIn
module Constants
module AccessToken
VALIDITY_LENGTHS = [VALIDITY_LENGTH_SHORT_MINUTES = 5.minutes, VALIDITY_LENGTH_LONG_MINUTES = 30.minutes].freeze
JWT_ENCODE_ALGORITHM = 'RS256'
VERSION_LIST = [
CURRENT_VERSION = 'V0'
].freeze
ISSUER = 'va.gov sign in'
USER_ATTRIBUTES = %w[first_name last_name email all_emails].freeze
end
end
end
|
0
|
code_files/vets-api-private/app/services/sign_in
|
code_files/vets-api-private/app/services/sign_in/logingov/risc_event_handler.rb
|
# frozen_string_literal: true
require 'sign_in/logingov/risc_event'
module SignIn
module Logingov
class RiscEventHandler
STATSD_KEY = 'api.sign_in.logingov.risc_event'
attr_reader :payload
def initialize(payload:)
@payload = payload.deep_symbolize_keys
end
def perform
risc_event = SignIn::Logingov::RiscEvent.new(event: payload[:events])
risc_event.validate!
handle_event(risc_event)
rescue ActiveModel::ValidationError => e
Rails.logger.error('[SignIn][Logingov][RiscEventHandler] validation error',
error: e.message,
risc_event: risc_event.to_h_masked)
raise SignIn::Errors::LogingovRiscEventHandlerError.new message: "Invalid RISC event: #{e.message}"
end
private
def handle_event(risc_event)
log_event(risc_event)
increment_metric(risc_event)
end
def log_event(risc_event)
Rails.logger.info('[SignIn][Logingov][RiscEventHandler] risc_event received',
risc_event: risc_event.to_h_masked)
end
def increment_metric(risc_event)
StatsD.increment(STATSD_KEY, tags: ["event_type:#{risc_event.event_type}"])
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/claim_fast_tracking/flash_picker.rb
|
# frozen_string_literal: true
module ClaimFastTracking
class FlashPicker
DEFAULT_FUZZY_TOLERANCE = 0.2
MIN_FUZZY_MATCH_LENGTH = 6
MIN_LENGTH_RATIO = 0.9
ALS_DC = 8017
ALS_PARTIAL_MATCH_TERMS = [
'amyotrophic lateral sclerosis',
'(als)'
].freeze
ALS_MATCH_TERMS = (ALS_PARTIAL_MATCH_TERMS + [
'als',
'lou gehrig disease',
'lou gehrigs disease',
'lou gehrig\'s disease',
'lou gehrig',
'lou gehrigs',
'lou gehrig\'s'
]).freeze
def self.als?(claimed_disabilities)
return if claimed_disabilities.pluck('diagnosticCode').include?(ALS_DC)
claimed_disabilities.map { |disability| disability['name']&.downcase }.compact.any? do |name|
partial_matches?(name, ALS_PARTIAL_MATCH_TERMS) || matches?(name, ALS_MATCH_TERMS)
end
end
def self.partial_matches?(name, match_terms)
match_terms = [match_terms] unless match_terms.is_a?(Array)
match_terms.any? { |term| name.include?(term) }
end
def self.matches?(name,
match_terms,
tolerance = DEFAULT_FUZZY_TOLERANCE,
min_length_ratio = MIN_LENGTH_RATIO,
min_length_limit = MIN_FUZZY_MATCH_LENGTH)
match_terms = [match_terms] unless match_terms.is_a?(Array)
match_terms.any? do |term|
# Early exact match check (case insensitive)
return true if name.casecmp?(term)
# Prevent fuzzy matching for very short terms (e.g., less than min_length_limit)
next false if name.length < min_length_limit || term.length < min_length_limit
# Calculate the length ratio based on the shorter and longer lengths
shorter_length = [name.length, term.length].min
longer_length = [name.length, term.length].max
# Skip comparison if the length ratio is below minimum length ratio, indicating a significant length difference
next false if shorter_length.to_f / longer_length < min_length_ratio
# Calculate the Levenshtein threshold based on tolerance and maximum length
return true if fuzzy_match?(name, term, longer_length, tolerance)
end
end
def self.fuzzy_match?(name, term, longer_length, tolerance = DEFAULT_FUZZY_TOLERANCE)
threshold = (longer_length * tolerance).ceil
distance = StringHelpers.levenshtein_distance(name, term)
if distance - 1 == threshold
Rails.logger.info(
'FlashPicker close fuzzy match for condition',
{ name:, match_term: term, distance:, threshold: }
)
end
distance <= threshold
end
private_class_method :partial_matches?, :matches?, :fuzzy_match?
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/claim_fast_tracking/diagnostic_codes_for_metrics.rb
|
# frozen_string_literal: true
module ClaimFastTracking
module DiagnosticCodesForMetrics
include DiagnosticCodes
DC = [
LIMITED_MOTION_OF_WRIST,
LIMITATION_OF_MOTION_OF_INDEX_OR_LONG_FINGER,
LIMITATION_OF_EXTENSION_OF_THE_THIGH,
FLATFOOT_ACQUIRED,
HALLUX_VALGUS_UNILATERAL,
TINNITUS,
SCARS_GENERAL,
MIGRAINES
].freeze
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/claim_fast_tracking/max_rating_annotator.rb
|
# frozen_string_literal: true
require 'disability_max_ratings/client'
module ClaimFastTracking
class MaxRatingAnnotator
EXCLUDED_DIGESTIVE_CODES = [7318, 7319, 7327, 7336, 7346].freeze
def self.annotate_disabilities(rated_disabilities_response)
return if rated_disabilities_response.rated_disabilities.blank?
log_hyphenated_diagnostic_codes(rated_disabilities_response.rated_disabilities)
diagnostic_codes = rated_disabilities_response.rated_disabilities
.compact # filter out nil entries in rated_disabilities
.select { |rd| eligible_for_request?(rd) } # select only eligible
.map(&:diagnostic_code) # map to diagnostic_code field in rating
return rated_disabilities_response if diagnostic_codes.empty?
ratings = get_ratings(diagnostic_codes)
return rated_disabilities_response unless ratings
ratings_hash = ratings.to_h { |rating| [rating['diagnostic_code'], rating['max_rating']] }
rated_disabilities_response.rated_disabilities.each do |rated_disability|
max_rating = ratings_hash[rated_disability.diagnostic_code]
rated_disability.maximum_rating_percentage = max_rating if max_rating
end
rated_disabilities_response
end
def self.log_hyphenated_diagnostic_codes(rated_disabilities)
rated_disabilities.each do |dis|
StatsD.increment('api.max_cfi.rated_disability',
tags: [
"diagnostic_code:#{dis&.diagnostic_code}",
"diagnostic_code_type:#{diagnostic_code_type(dis)}",
"hyphenated_diagnostic_code:#{dis&.hyphenated_diagnostic_code}"
])
end
end
def self.diagnostic_code_type(rated_disability)
case rated_disability&.diagnostic_code
when nil
:missing_diagnostic_code
when 7200..7399
:digestive_system
when 6300..6399
:infectious_disease
else
if (rated_disability&.hyphenated_diagnostic_code || 0) % 100 == 99
:analogous_code
else
:primary_max_rating
end
end
end
def self.get_ratings(diagnostic_codes)
disability_max_ratings_client = DisabilityMaxRatings::Client.new
response = disability_max_ratings_client.post_for_max_ratings(diagnostic_codes)
response.body['ratings']
rescue Faraday::TimeoutError
Rails.logger.error 'Get Max Ratings Failed: Request timed out.'
nil
rescue Common::Client::Errors::ClientError => e
Rails.logger.error "Get Max Ratings Failed #{e.message}.", backtrace: e.backtrace
nil
end
def self.eligible_for_request?(rated_disability)
%i[infectious_disease missing_diagnostic_code].exclude?(diagnostic_code_type(rated_disability)) &&
EXCLUDED_DIGESTIVE_CODES.exclude?(rated_disability.diagnostic_code)
end
private_class_method :get_ratings
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/claim_fast_tracking/constants.rb
|
# frozen_string_literal: true
module ClaimFastTracking
class Constants
DISABILITIES = {
hypertension: {
code: 7101,
label: 'hypertension'
},
asthma: {
code: 6602,
label: 'asthma'
}
}.freeze
DISABILITIES_BY_CODE = DISABILITIES.to_h { |k, v| [v[:code], k] }
# @return [Array] mapping submitted disabilities to symbols used as keys for DISABILITIES;
# an element is nil when the disability is not supported by RRD
def self.extract_disability_symbol_list(form526_submission)
form_disabilities = form526_submission.form.dig('form526', 'form526', 'disabilities')
form_disabilities.map { |form_disability| DISABILITIES_BY_CODE[form_disability['diagnosticCode']] }
end
# @return [Hash] for the first RRD-supported disability in the form526_submission
def self.first_disability(form526_submission)
extracted_disability_symbols = extract_disability_symbol_list(form526_submission)
return if extracted_disability_symbols.empty?
disability_symbol = extracted_disability_symbols.first
DISABILITIES[disability_symbol]
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/claim_fast_tracking/max_cfi_metrics.rb
|
# frozen_string_literal: true
module ClaimFastTracking
class MaxCfiMetrics
attr_reader :form, :form_data, :metadata
MAX_CFI_STATSD_KEY_PREFIX = 'api.max_cfi'
# Triggers any relevant StatsD metrics calls whenever a 526EZ InProgressForm is updated with
# a new params hash. The params[:metadata] hash will be mutated to include any metadata
# needed by this CFI metrics logic.
def self.log_form_update(form, params)
new(form, params).log_form_update if form.form_id == '21-526EZ'
end
def initialize(form, params)
params[:metadata] ||= {}
@form = form
@form_data = params[:form_data] || params[:formData]
@form_data = JSON.parse(form_data) if form_data.is_a?(String)
@metadata = params[:metadata]
end
# Max CFI metrics progress is stored in InProgressForm#metadata, to prevent double-counting
# events over the IPF's lifecycle. This method will create-or-load the progress metadata
# from the IPF, and updates an older scheme where the progress was just a boolean.
def create_or_load_metadata
cfi_metadata = form.metadata['cfiMetric']
if cfi_metadata.blank?
{ 'initLogged' => false, 'cfiLogged' => false }
elsif cfi_metadata == true
{ 'initLogged' => true, 'cfiLogged' => true }
else
cfi_metadata
end
end
def log_form_update
cfi_metadata = create_or_load_metadata
unless cfi_metadata['initLogged']
log_init_metric
cfi_metadata['initLogged'] = true
end
if claiming_increase? && !cfi_metadata['cfiLogged']
log_cfi_metric
cfi_metadata['cfiLogged'] = true
end
metadata['cfiMetric'] = cfi_metadata
rescue => e
# Log the exception but but do not fail, otherwise in-progress form will not update
Rails.logger.error("In-progress form failed to log Max CFI metrics: #{e.message}")
end
def claiming_increase?
form_data&.dig('view:claim_type', 'view:claiming_increase') ||
form_data&.dig('view:claimType', 'view:claimingIncrease')
end
def rated_disabilities
form_data&.dig('rated_disabilities') || form_data&.dig('ratedDisabilities') || []
end
def max_rated_disabilities
rated_disabilities.filter do |dis|
maximum_rating_percentage = dis['maximum_rating_percentage'] || dis['maximumRatingPercentage']
rating_percentage = dis['rating_percentage'] || dis['ratingPercentage']
maximum_rating_percentage.present? && maximum_rating_percentage == rating_percentage
end
end
def max_rated_disabilities_diagnostic_codes
max_rated_disabilities.map { |dis| dis['diagnosticCode'] || dis['diagnostic_code'] }
end
private
def log_init_metric
StatsD.increment("#{MAX_CFI_STATSD_KEY_PREFIX}.on_526_started",
tags: ["has_max_rated:#{max_rated_disabilities.any?}"])
max_rated_disabilities_diagnostic_codes.each do |dc|
StatsD.increment("#{MAX_CFI_STATSD_KEY_PREFIX}.526_started", tags: ["diagnostic_code:#{dc}"])
end
end
def log_cfi_metric
StatsD.increment("#{MAX_CFI_STATSD_KEY_PREFIX}.on_rated_disabilities",
tags: ["has_max_rated:#{max_rated_disabilities.any?}"])
max_rated_disabilities_diagnostic_codes.each do |dc|
StatsD.increment("#{MAX_CFI_STATSD_KEY_PREFIX}.rated_disabilities", tags: ["diagnostic_code:#{dc}"])
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/claim_fast_tracking/diagnostic_codes.rb
|
# frozen_string_literal: true
module ClaimFastTracking
module DiagnosticCodes
LIMITED_MOTION_OF_WRIST = 5215
LIMITATION_OF_MOTION_OF_INDEX_OR_LONG_FINGER = 5229
LIMITATION_OF_EXTENSION_OF_THE_THIGH = 5251
FLATFOOT_ACQUIRED = 5276
HALLUX_VALGUS_UNILATERAL = 5280
TINNITUS = 6260
ASTHMA = 6602
HYPERTENSION = 7101
SCARS_GENERAL = 7805
MIGRAINES = 8100
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/form1010_ezr_attachments/file_type_validator.rb
|
# frozen_string_literal: true
require 'form1010_ezr/service'
module Form1010EzrAttachments
class FileTypeValidator
def initialize(file)
@file = file
end
# This method was created because there's an issue on the frontend where a user can manually 'change' a
# file's extension via its name in order to circumvent frontend validation. '.xlsx' files, in particular, were
# the cause of several form submission failures. With that said, we need to check the actual file type
# and ensure the Enrollment System accepts it.
def validate
file_path = @file.tempfile.path
# Using 'MIME::Types' doesn't work here because it will
# return, for example, 'application/zip' for .docx files
mime_subtype = IO.popen(
['file', '--mime-type', '--brief', file_path]
) { |io| io.read.chomp.to_s }.split('/').last
unless mime_subtype_allow_list.include?(mime_subtype)
StatsD.increment("#{Form1010Ezr::Service::STATSD_KEY_PREFIX}.attachments.invalid_file_type")
raise Common::Exceptions::UnprocessableEntity.new(
detail: 'File type not supported. Follow the instructions on your device ' \
'on how to convert the file type and try again to continue.'
)
end
rescue => e
StatsD.increment("#{Form1010Ezr::Service::STATSD_KEY_PREFIX}.attachments.failed")
Rails.logger.error(
"Form1010EzrAttachment validate file type failed #{e.message}.",
backtrace: e.backtrace
)
raise e
end
private
# These MIME types correspond to the extensions accepted by enrollment system: PDF,WORD,JPG,RTF
def mime_subtype_allow_list
%w[pdf msword vnd.openxmlformats-officedocument.wordprocessingml.document jpeg rtf png]
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/dependent_service.rb
|
# frozen_string_literal: true
require 'claims_evidence_api/uploader'
require 'dependents/monitor'
module BGS
class DependentService
attr_reader :first_name,
:middle_name,
:last_name,
:ssn,
:birth_date,
:common_name,
:email,
:icn,
:participant_id,
:uuid,
:file_number
STATS_KEY = 'bgs.dependent_service'
class PDFSubmissionError < StandardError; end
def initialize(user)
@first_name = user.first_name
@middle_name = user.middle_name
@last_name = user.last_name
@ssn = user.ssn
@uuid = user.uuid
@birth_date = user.birth_date
@common_name = user.common_name
@email = user.email
@icn = user.icn
@participant_id = user.participant_id
@va_profile_email = user.va_profile_email
end
def get_dependents
backup_response = { persons: [] }
return backup_response if participant_id.blank?
response = service.claimant.find_dependents_by_participant_id(participant_id, ssn)
if response.presence && response[:persons]
# When only one dependent exists, BGS returns a Hash instead of an Array
# Ensure persons is always an array for consistent processing
response[:persons] = [response[:persons]] if response[:persons].is_a?(Hash)
response
else
backup_response
end
end
def submit_686c_form(claim)
@monitor = init_monitor(claim&.id)
@monitor.track_event('info', 'BGS::DependentService running!', "#{STATS_KEY}.start")
InProgressForm.find_by(form_id: BGS::SubmitForm686cJob::FORM_ID, user_uuid: uuid)&.submission_processing!
encrypted_vet_info = KmsEncrypted::Box.new.encrypt(get_form_hash_686c.to_json)
submit_pdf_job(claim:)
if claim.submittable_686? || claim.submittable_674?
submit_form_job_id = submit_to_standard_service(claim:, encrypted_vet_info:)
@monitor.track_event('info', 'BGS::DependentService succeeded!', "#{STATS_KEY}.success")
end
{ submit_form_job_id: }
rescue PDFSubmissionError
submit_to_central_service(claim:)
rescue => e
@monitor.track_event('warn', 'BGS::DependentService#submit_686c_form method failed!',
"#{STATS_KEY}.failure", { error: e.message, user_uuid: uuid })
raise e
end
private
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
def folder_identifier
fid = 'VETERAN'
{ ssn:, participant_id:, icn: }.each do |k, v|
if v.present?
fid += ":#{k.to_s.upcase}:#{v}"
break
end
end
fid
end
def claims_evidence_uploader
@ce_uploader ||= ClaimsEvidenceApi::Uploader.new(folder_identifier)
end
def submit_pdf_job(claim:)
@monitor = init_monitor(claim&.id)
@monitor.track_event('info', 'BGS::DependentService#submit_pdf_job called to begin ClaimsEvidenceApi::Uploader',
"#{STATS_KEY}.submit_pdf.begin")
form_id = submit_claim_via_claims_evidence(claim)
submit_attachments_via_claims_evidence(form_id, claim)
@monitor.track_event('info', 'BGS::DependentService#submit_pdf_job completed',
"#{STATS_KEY}.submit_pdf.completed")
rescue => e
error = Flipper.enabled?(:dependents_log_vbms_errors) ? e.message : '[REDACTED]'
@monitor.track_event('warn',
'BGS::DependentService#submit_pdf_job failed, submitting to Lighthouse Benefits Intake',
"#{STATS_KEY}.submit_pdf.failure", error:)
raise PDFSubmissionError
end
def submit_claim_via_claims_evidence(claim)
form_id = claim.form_id
doctype = claim.document_type
if claim.submittable_686?
form_id = '686C-674'
file_path = claim.process_pdf(claim.to_pdf(form_id:), claim.created_at, form_id)
@monitor.track_event('info', "#{self.class} claims evidence upload of #{form_id} claim_id #{claim.id}",
"#{STATS_KEY}.claims_evidence.upload", tags: ["form_id:#{form_id}"])
claims_evidence_uploader.upload_evidence(claim.id, file_path:, form_id:, doctype:)
end
if claim.submittable_674?
form_id = '21-674'
doctype = 142
claim.process_pdf(claim.to_pdf(form_id:), claim.created_at, form_id)
@monitor.track_event('info', "#{self.class} claims evidence upload of #{form_id} claim_id #{claim.id}",
"#{STATS_KEY}.claims_evidence.upload", tags: ["form_id:#{form_id}"])
claims_evidence_uploader.upload_evidence(claim.id, file_path:, form_id:, doctype:)
end
form_id
end
def submit_attachments_via_claims_evidence(form_id, claim)
Rails.logger.info("BGS::DependentService claims evidence upload of #{form_id} claim_id #{claim.id} attachments")
stamp_set = [{ text: 'VA.GOV', x: 5, y: 5 }]
claim.persistent_attachments.each do |pa|
doctype = pa.document_type
file_path = PDFUtilities::PDFStamper.new(stamp_set).run(pa.to_pdf, timestamp: pa.created_at)
claims_evidence_uploader.upload_evidence(claim.id, pa.id, file_path:, form_id:, doctype:)
end
end
def submit_to_standard_service(claim:, encrypted_vet_info:)
if claim.submittable_686?
BGS::SubmitForm686cJob.perform_async(
uuid, claim.id, encrypted_vet_info
)
else
BGS::SubmitForm674Job.perform_async(
uuid, claim.id, encrypted_vet_info
)
end
end
def submit_to_central_service(claim:)
vet_info = JSON.parse(claim.form)['dependents_application']
vet_info.merge!(get_form_hash_686c) unless vet_info['veteran_information']
user = BGS::SubmitForm686cJob.generate_user_struct(vet_info)
Lighthouse::BenefitsIntake::SubmitCentralForm686cJob.perform_async(
claim.id,
KmsEncrypted::Box.new.encrypt(vet_info.to_json),
KmsEncrypted::Box.new.encrypt(user.to_h.to_json)
)
end
def external_key
@external_key ||= begin
key = common_name.presence || email
key.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
def get_form_hash_686c
# include ssn in call to BGS for mocks
bgs_person = service.people.find_person_by_ptcpnt_id(participant_id, ssn) || service.people.find_by_ssn(ssn) # rubocop:disable Rails/DynamicFindBy
@file_number = bgs_person[:file_nbr]
# BGS's file number is supposed to be an eight or nine-digit string, and
# our code is built upon the assumption that this is the case. However,
# we've seen cases where BGS returns a file number with dashes
# (e.g. XXX-XX-XXXX). In this case specifically, we can simply strip out
# the dashes and proceed with form submission.
@file_number = file_number.delete('-') if file_number =~ /\A\d{3}-\d{2}-\d{4}\z/
generate_hash_from_details
end
def generate_hash_from_details
{
'veteran_information' => {
'full_name' => {
'first' => first_name,
'middle' => middle_name,
'last' => last_name
},
'common_name' => common_name,
'va_profile_email' => @va_profile_email,
'email' => email,
'participant_id' => participant_id,
'ssn' => ssn,
'va_file_number' => file_number,
'birth_date' => birth_date,
'uuid' => uuid,
'icn' => icn
}
}
end
def init_monitor(saved_claim_id)
@monitor ||= ::Dependents::Monitor.new(saved_claim_id)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/dependent_v2_service.rb
|
# frozen_string_literal: true
require 'claims_evidence_api/uploader'
require 'dependents/monitor'
require 'vets/shared_logging'
module BGS
class DependentV2Service
include Vets::SharedLogging
attr_reader :first_name,
:middle_name,
:last_name,
:ssn,
:birth_date,
:common_name,
:email,
:icn,
:participant_id,
:uuid,
:file_number
attr_accessor :notification_email
STATS_KEY = 'bgs.dependent_service'
class PDFSubmissionError < StandardError; end
class BgsServicesError < StandardError; end
# Initialize service with a user-like object.
# Copies identifying fields onto the service instance for later use
# when interacting with BGS and building submission payloads.
def initialize(user)
@first_name = user.first_name
@middle_name = user.middle_name
@last_name = user.last_name
@ssn = user.ssn
@uuid = user.uuid
@birth_date = user.birth_date
@common_name = user.common_name
@email = user.email
@icn = user.icn
@participant_id = user.participant_id
@notification_email = get_user_email(user)
end
# Retrieve dependents for the veteran from BGS.
# Returns a Hash with :persons => [] (array) for consistent downstream processing.
# Falls back to an empty response when participant_id is blank or the BGS response
# does not include dependents.
def get_dependents
backup_response = { persons: [] }
return backup_response if participant_id.blank?
response = service.claimant.find_dependents_by_participant_id(participant_id, ssn)
if response.presence && response[:persons]
# When only one dependent exists, BGS returns a Hash instead of an Array
# Ensure persons is always an array for consistent processing
response[:persons] = [response[:persons]] if response[:persons].is_a?(Hash)
response
else
backup_response
end
end
# Top-level orchestration for submitting a 686c/674 dependents form.
# - Ensures notification email is set (prefers VA profile email, falls back to form email)
# - Builds and encrypts veteran info
# - Submits PDFs to ClaimsEvidenceApi (VBMS) and then attempts standard BGS submission
# - If PDF submission fails, falls back to central submission flow
# Returns a hash containing the enqueued job id for the BGS submit job when applicable.
def submit_686c_form(claim)
# Set email for BGS service and notification emails from form email if va_profile_email is not available
# Form email is required
if @notification_email.nil?
form = claim.parsed_form
@notification_email = form&.dig('dependents_application', 'veteran_contact_information', 'email_address')
end
@monitor = init_monitor(claim&.id)
@monitor.track_event('info', 'BGS::DependentService running!', "#{STATS_KEY}.start")
InProgressForm.find_by(form_id: BGS::SubmitForm686cV2Job::FORM_ID, user_uuid: uuid)&.submission_processing!
encrypted_vet_info = setup_vet_info(claim)
submit_pdf_job(claim:)
if claim.submittable_686? || claim.submittable_674?
submit_form_job_id = submit_to_standard_service(claim:, encrypted_vet_info:)
@monitor.track_event('info', 'BGS::DependentService succeeded!', "#{STATS_KEY}.success")
end
{ submit_form_job_id: }
rescue PDFSubmissionError
# If ClaimsEvidenceApi (PDF upload) fails, use central submission path.
submit_to_central_service(claim:, encrypted_vet_info:)
rescue => e
# Log and re-raise unexpected errors for caller to handle.
log_bgs_errors(e)
raise e
end
private
# Build, attach to claim, and encrypt veteran information to be sent with the form.
# Returns the encrypted JSON string.
def setup_vet_info(claim)
vet_info = get_form_hash_686c
claim.add_veteran_info(vet_info)
KmsEncrypted::Box.new.encrypt(vet_info.to_json)
end
# Construct the BGS service client for subsequent remote calls.
# Uses the veteran's ICN and external_key for identification.
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
# Centralized BGS error logging/tracking wrapper for visibility in monitoring.
# Emits a monitor event with sanitized error details and increments metrics when configured.
def log_bgs_errors(error)
increment_non_validation_error(error) if Flipper.enabled?(:va_dependents_bgs_extra_error_logging)
# Temporarily logging a few iterations of status code to see what BGS returns in the error
@monitor.track_event(
'warn', 'BGS::DependentService#submit_686c_form method failed!',
"#{STATS_KEY}.failure",
{
error: error.message,
status: error.try(:status) || 'no status',
status_code: error.try(:status_code) || 'no status code',
code: error.try(:code) || 'no code'
}
)
end
# Inspect nested error messages for common HTTP error types and increment StatsD counters.
# This isolates transient BGS HTTP status conditions for easier alerting.
def increment_non_validation_error(error)
error_messages = ['HTTP error (302)', 'HTTP error (500)', 'HTTP error (502)', 'HTTP error (504)']
error_type_map = {
'HTTP error (302)' => '302',
'HTTP error (500)' => '500',
'HTTP error (502)' => '502',
'HTTP error (504)' => '504'
}
nested_error_message = error.cause&.message
error_type = error_messages.find do |et|
nested_error_message&.include?(et)
end
if error_type.present?
error_status = error_type_map[error_type]
StatsD.increment("#{STATS_KEY}.non_validation_error.#{error_status}", tags: ["form_id:#{BGS::SubmitForm686cV2Job::FORM_ID}"])
end
end
# Build a folder identifier for Claims Evidence API uploads.
# Chooses the first available identifier from ssn, participant_id, or icn.
def folder_identifier
fid = 'VETERAN'
{ ssn:, participant_id:, icn: }.each do |k, v|
if v.present?
fid += ":#{k.to_s.upcase}:#{v}"
break
end
end
fid
end
# Lazily construct a ClaimsEvidenceApi uploader scoped to the folder identifier.
def claims_evidence_uploader
@ce_uploader ||= ClaimsEvidenceApi::Uploader.new(folder_identifier)
end
# Orchestrate PDF submission to Claims Evidence (VBMS).
# - Upload main claim PDF(s)
# - Upload attachment PDFs
# Tracks progress via monitor and raises PDFSubmissionError on failure so caller can handle fallback.
def submit_pdf_job(claim:)
@monitor = init_monitor(claim&.id)
@monitor.track_event('info', 'BGS::DependentV2Service#submit_pdf_job called to begin ClaimsEvidenceApi::Uploader',
"#{STATS_KEY}.submit_pdf.begin")
form_id = submit_claim_via_claims_evidence(claim)
submit_attachments_via_claims_evidence(form_id, claim)
@monitor.track_event('info', 'BGS::DependentV2Service#submit_pdf_job completed',
"#{STATS_KEY}.submit_pdf.completed")
rescue => e
error = Flipper.enabled?(:dependents_log_vbms_errors) ? e.message : '[REDACTED]'
@monitor.track_event('warn',
'BGS::DependentV2Service#submit_pdf_job failed, submitting to Lighthouse Benefits Intake',
"#{STATS_KEY}.submit_pdf.failure", error:)
raise PDFSubmissionError
end
# Upload the primary claim PDF(s) for 686C and 674 forms via ClaimsEvidenceApi.
# Returns the form_id used for subsequent attachments.
def submit_claim_via_claims_evidence(claim)
form_id = claim.form_id
doctype = claim.document_type
if claim.submittable_686?
form_id = '686C-674-V2'
file_path = claim.process_pdf(claim.to_pdf(form_id:), claim.created_at, form_id)
@monitor.track_event('info', "#{self.class} claims evidence upload of #{form_id} claim_id #{claim.id}",
"#{STATS_KEY}.claims_evidence.upload", tags: ["form_id:#{form_id}"])
claims_evidence_uploader.upload_evidence(claim.id, file_path:, form_id:, doctype:)
end
form_id = submit_674_via_claims_evidence(claim) if claim.submittable_674?
form_id
end
# Special handling for 674 PDFs: multiple student PDFs are uploaded and reference data is updated.
# Ensures ClaimsEvidenceApi submission contains all students' PDFs and file UUID metadata.
def submit_674_via_claims_evidence(claim)
form_id = '21-674-V2'
doctype = 142
@monitor.track_event('info', "#{self.class} claims evidence upload of #{form_id} claim_id #{claim.id}",
"#{STATS_KEY}.claims_evidence.upload", tags: ["form_id:#{form_id}"])
form_674_pdfs = []
claim.parsed_form['dependents_application']['student_information']&.each_with_index do |student, index|
file_path = claim.process_pdf(claim.to_pdf(form_id:, student:), claim.created_at, form_id, index)
file_uuid = claims_evidence_uploader.upload_evidence(claim.id, file_path:, form_id:, doctype:)
form_674_pdfs << [file_uuid, file_path]
end
# When multiple student PDFs exist (form 674), encode references into the submission record.
if form_674_pdfs.length > 1
file_uuid = form_674_pdfs.map { |fp| fp[0] }
submission = claims_evidence_uploader.submission
submission.update_reference_data(students: form_674_pdfs)
submission.file_uuid = file_uuid.to_s # set to stringified array
submission.save
end
form_id
end
# Upload each persistent attachment via ClaimsEvidenceApi, stamping PDFs and sending them.
def submit_attachments_via_claims_evidence(form_id, claim)
Rails.logger.info("BGS::DependentV2Service claims evidence upload of #{form_id} claim_id #{claim.id} attachments")
stamp_set = [{ text: 'VA.GOV', x: 5, y: 5 }]
claim.persistent_attachments.each do |pa|
doctype = pa.document_type
file_path = PDFUtilities::PDFStamper.new(stamp_set).run(pa.to_pdf, timestamp: pa.created_at)
claims_evidence_uploader.upload_evidence(claim.id, pa.id, file_path:, form_id:, doctype:)
end
end
# Enqueue the appropriate Sidekiq job to submit to the standard BGS service (686c or 674).
def submit_to_standard_service(claim:, encrypted_vet_info:)
if claim.submittable_686?
BGS::SubmitForm686cV2Job.perform_async(
uuid, claim.id, encrypted_vet_info
)
else
BGS::SubmitForm674V2Job.perform_async(
uuid, claim.id, encrypted_vet_info
)
end
end
# Fallback submission path that sends the encrypted vet info to the central intake job.
# Decrypts the previously encrypted vet_info and generates the user struct required by central job.
def submit_to_central_service(claim:, encrypted_vet_info:)
vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info))
user = BGS::SubmitForm686cV2Job.generate_user_struct(vet_info)
Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.perform_async(
claim.id,
encrypted_vet_info,
KmsEncrypted::Box.new.encrypt(user.to_h.to_json)
)
end
# Build an external key used for BGS client identification.
# Prefer the user's common_name, fall back to email, and truncate to max allowed length.
def external_key
@external_key ||= begin
key = common_name.presence || email
key.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
# Retrieve veteran identifiers from BGS and compose the hash used in 686C submissions.
# - Attempts lookup by participant_id then SSN
# - Extracts and normalizes va file number when present
# - Logs and continues on BGS failures
# Additional notes on this method can be found in app/services/bgs/dependents_veteran_identifiers.md
def get_form_hash_686c
begin
# SSN is required in test/dev environments but unnecessary in production
# This will be fixed in an upcoming refactor by @TaiWilkin
bgs_person = lookup_bgs_person
# Safely extract file number from BGS response as an instance variable for later use;
# For more details on why this matters, see dependents_veteran_identifiers.md
# The short version is that we need the file number to be present for RBPS, but we are retrieving by PID.
if bgs_person.respond_to?(:[]) && bgs_person[:file_nbr].present?
@file_number = bgs_person[:file_nbr]
else
@monitor.track_event('warn',
'BGS::DependentV2Service#get_form_hash_686c missing bgs_person file_nbr',
"#{STATS_KEY}.file_number.missing",
{ bgs_person_present: bgs_person.present? ? 'yes' : 'no' })
@file_number = nil
end
# Normalize file numbers that are returned in dashed SSN format (XXX-XX-XXXX).
# BGS's file number is supposed to be an eight or nine-digit string, and
# our code is built upon the assumption that this is the case. However,
# we've seen cases where BGS returns a file number with dashes
# (e.g. XXX-XX-XXXX). In this case specifically, we can simply strip out
# the dashes and proceed with form submission.
@file_number = file_number.delete('-') if file_number =~ /\A\d{3}-\d{2}-\d{4}\z/
# This rescue could be hit if BGS is down or unreachable when trying to run find_person_by_ptcpnt_id()
# It could also be hit if the file number is invalid or missing. We log and continue since we can
# fall back to using Lighthouse and want to still generate the PDF.
rescue
@monitor.track_event('warn',
'BGS::DependentV2Service#get_form_hash_686c failed',
"#{STATS_KEY}.get_form_hash.failure", { error: 'Could not retrieve file number from BGS' })
end
generate_hash_from_details
end
# Lookup BGS person record by participant_id (preferred) or SSN (fallback)
def lookup_bgs_person
bgs_person = service.people.find_person_by_ptcpnt_id(participant_id, ssn)
if bgs_person.present?
@monitor.track_event('info', 'BGS::DependentV2Service#get_form_hash_686c found bgs_person by PID',
"#{STATS_KEY}.find_by_participant_id")
else
bgs_person = service.people.find_by_ssn(ssn) # rubocop:disable Rails/DynamicFindBy
@monitor.track_event('info', 'BGS::DependentV2Service#get_form_hash_686c found bgs_person by ssn',
"#{STATS_KEY}.find_by_ssn")
end
bgs_person
end
# Compose the final payload hash used by submission jobs.
# Ensures minimal fields are present and that middle name is omitted only when nil
# to avoid schema validation issues.
def generate_hash_from_details
full_name = { 'first' => first_name, 'last' => last_name }
full_name['middle'] = middle_name unless middle_name.nil? # nil middle name breaks prod validation
# Sometimes BGS will return a 502 (Bad Gateway) when trying to find a person by participant id or ssn.
# Given this a rare occurrence and almost always file number is the same as ssn, we'll set file number
# to ssn as a backup.
{
'veteran_information' => {
'full_name' => full_name,
'common_name' => common_name,
'va_profile_email' => @notification_email,
'email' => email,
'participant_id' => participant_id,
'ssn' => ssn,
'va_file_number' => file_number || ssn,
'birth_date' => birth_date,
'uuid' => uuid,
'icn' => icn
}
}
end
# Attempt to retrieve the VA profile email for notifications. If profile lookup fails,
# log the event and return nil so callers can fall back to form-supplied email.
def get_user_email(user)
# Safeguard for when VAProfileRedis::V2::ContactInformation.for_user fails in app/models/user.rb
# Failure is expected occasionally due to 404 errors from the redis cache
# New users, users that have not logged on in over a month, users who created an account on web,
# and users who have not visited their profile page will need to obtain/refresh VAProfile_ID
# Originates here: lib/va_profile/contact_information/v2/service.rb
user.va_profile_email
rescue => e
# We don't have a claim id accessible yet
@monitor = init_monitor(nil)
@monitor.track_event('warn', 'BGS::DependentV2Service#get_user_email failed to get va_profile_email',
"#{STATS_KEY}.get_va_profile_email.failure", { error: e.message })
nil
end
# Initialize or return the monitor instance used for tracking events tied to a saved claim id.
def init_monitor(saved_claim_id)
@monitor ||= ::Dependents::Monitor.new(saved_claim_id)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/awards_service.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
module BGS
class AwardsService
include Vets::SharedLogging
attr_reader :participant_id, :ssn, :common_name, :email, :icn
def initialize(user)
@participant_id = user.participant_id
@ssn = user.ssn
@common_name = user.common_name
@email = user.email
@icn = user.icn
end
def get_awards
service.awards.find_award_by_participant_id(participant_id, ssn) || service.awards.find_award_by_ssn(ssn)
rescue => e
log_exception_to_sentry(e, { icn: }, { team: Constants::SENTRY_REPORTING_TEAM })
log_exception_to_rails(e)
false
end
private
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
def external_key
@external_key ||= begin
key = common_name.presence || email
key.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/dependents_veteran_identifiers.md
|
# Additional notes on get_form_hash_686c()
The purpose of this readme is to add some context and information to `app/services/bgs/dependent_v2_service.rb` and specifically to get_form_hash_686c() The main concern is around the identifiers used in `get_form_hash_686c()`. As noted in the comments in code, the SSN really shouldn't be included because the SOAP service doesn't use it.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:per="http://person.services.vetsnet.vba.va.gov/">
<soapenv:Header/>
<soapenv:Body>
<per:findPersonsByPtcpntIds>
<!--Zero or more repetitions:-->
<ptcpntId>?</ptcpntId>
</per:findPersonsByPtcpntIds>
</soapenv:Body>
</soapenv:Envelope>
```
def get_form_hash_686c
begin
# The inclusion of ssn as a parameter is necessary for test/development environments, but really isn't needed in production
# This will be fixed in an upcoming refactor by @TaiWilkin
bgs_person = lookup_bgs_person
```
After the check in `lookup_bgs_person` for `bgs_person.present?`, we currently have a second check for lookup by SSN. A couple versions (one liner vs if/else) of this lookup has been in place for a while, but it seems to serve no purpose. Even after logging was added to DataDog ([PR here](https://github.com/department-of-veterans-affairs/vets-api/commit/ec5602459650d16dcc509d65dc78c25a76e77662)), there were no instances of the else being hit in the [logs](https://vagov.ddog-gov.com/logs?query=%22BGS%3A%3ADependentV2Service%23get_form_hash_686c%20found%20bgs_person%20by%20ssn%22&agg_m=count&agg_m_source=base&agg_t=count&cols=host%2Cservice&messageDisplay=inline&refresh_mode=sliding&storage=hot&stream_sort=desc&viz=stream&from_ts=1763921404855&to_ts=1765217404855&live=true).
The next line piece of code is used to grab the file number from `bgs_person`
```
@file_number = bgs_person[:file_nbr]
# BGS's file number is supposed to be an eight or nine-digit string, and
# our code is built upon the assumption that this is the case. However,
# we've seen cases where BGS returns a file number with dashes
# (e.g. XXX-XX-XXXX). In this case specifically, we can simply strip out
# the dashes and proceed with form submission.
@file_number = file_number.delete('-') if file_number =~ /\A\d{3}-\d{2}-\d{4}\z/
```
This piece of code here seems to make assumptions that aren't backed up in conversations with the CorpDB team. From a conversation with Alex Mikuliak:
> "...only Veterans have a file number β persons can be anyone β spouses, children, etc. but remember; a spouse, child, etc. could be a Veteran alsoβ¦ hence why we abandoned file number as a key a long time ago in favor of PTCPNT_ID β file number is a TRAIT β and we should avoid using it (like avoiding using SSN) as much as possible."
In the case above where we try to extract `@file_number = bgs_person[:file_nbr]` but the file_number is not the same as the participant ID. This probably hasn't been a big issue because the primary users of the 686c form are veterans who have a file number. Back in app/controllers/v0/benefits_claims_controller.rb#31, we do a check to see if file number is present in `check_for_file_number()`, but it seems like we only log it and don't do anything else.
It might seem redundant. but this change seems to better capture the issue in our own code, rather than a shared file.
```ruby
# Safely extract file number from BGS response as an instance variable for later use;
# handle malformed bgs_person gracefully
begin
@file_number = bgs_person[:file_nbr]
rescue => e
@monitor.track_event('warn',
'BGS::DependentV2Service#get_form_hash_686c invalid bgs_person file_nbr',
"#{STATS_KEY}.file_number.parse_failure",
{ error: e.message })
@file_number = nil
end
```
Lastly, if there is an issue with BGS being down or with a missing file number, we log but allow for it to continue. This continuation might seem odd, but it is so that the PDF can still be created and then used in the back-up Lighthouse route.
```
# This rescue could be hit if BGS is down or unreachable when trying to run find_person_by_ptcpnt_id()
# It could also be hit if the file number is invalid or missing. We log and continue since we can
# fall back to using Lighthouse and want to still generate the PDF.
rescue
@monitor.track_event('warn',
'BGS::DependentV2Service#get_form_hash_686c failed',
"#{STATS_KEY}.get_form_hash.failure", { error: 'Could not retrieve file number from BGS' })
end
```
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/uploaded_document_service.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
module BGS
class UploadedDocumentService
include Vets::SharedLogging
attr_reader :participant_id, :ssn, :common_name, :email, :icn
def initialize(user)
@participant_id = user.participant_id
@common_name = user.common_name
@email = user.email
@icn = user.icn
end
def get_documents
service.uploaded_document.find_by_participant_id(participant_id) || [] # rubocop:disable Rails/DynamicFindBy
rescue => e
log_exception_to_sentry(e, { icn: }, { team: Constants::SENTRY_REPORTING_TEAM })
log_exception_to_rails(e)
[]
end
private
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
def external_key
@external_key ||= begin
key = common_name.presence || email
key.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/constants.rb
|
# frozen_string_literal: true
module BGS
module Constants
EXTERNAL_KEY_MAX_LENGTH = 39
SENTRY_REPORTING_TEAM = 'vfs-ebenefits'
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/payment_service.rb
|
# frozen_string_literal: true
require 'bgs/monitor'
module BGS
class PaymentService
attr_reader :common_name, :email, :icn
def initialize(user)
@common_name = user.common_name
@email = user.email
@icn = user.icn
end
def payment_history(person)
response = service.payment_information.retrieve_payment_summary_with_bdn(
person.participant_id,
person.file_number,
'00', # payee code
person.ssn_number
)
return empty_response if response[:payments].nil?
payments = Array.wrap(response[:payments][:payment])
exclude_third_party_payments(payments)
recategorize_hardship(payments)
response
rescue => e
monitor.error(e.message, 'payment_history_error')
empty_response if e.message.include?('No Data Found')
end
private
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
def external_key
@external_key ||= begin
key = common_name.presence || email
key.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
def empty_response
{ payments: { payment: [] } }
end
def exclude_third_party_payments(payments)
payments.select! do |pay|
pay[:payee_type] != 'Third Party/Vendor' && pay[:beneficiary_participant_id] == pay[:recipient_participant_id]
end
end
def recategorize_hardship(payments)
payments.each do |payment|
if payment[:payee_type] == 'Veteran' &&
payment[:program_type] == 'Chapter 33' &&
payment[:payment_type].match(/Hardship/)
payment[:payment_type] = "CH 33 #{payment[:payment_type]}"
end
end
end
def monitor
@monitor ||= BGS::Monitor.new
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/bgs/dependency_verification_service.rb
|
# frozen_string_literal: true
require 'bgs/monitor'
module BGS
class DependencyVerificationService
attr_reader :participant_id, :ssn, :common_name, :email, :icn, :user_uuid
def initialize(user)
@participant_id = user.participant_id
@ssn = user.ssn
@common_name = user.common_name
@email = user.email
@icn = user.icn
@user_uuid = user.uuid
end
def read_diaries
if participant_id.blank?
monitor.warn('read_diaries: participant_id is blank', 'read_diaries', user_uuid:)
return { dependency_decs: nil, diaries: [] }
end
diaries = service.diaries.read_diaries(
{
beneficiary_id: participant_id,
participant_id:,
ssn:,
award_type: 'CPL'
}
)
return empty_response(diaries) if diaries[:diaries].blank?
dependency_decisions = diaries[:dependency_decs][:dependency_dec]
diaries[:dependency_decs][:dependency_dec] = normalize_dependency_decisions(dependency_decisions)
standard_response(diaries)
rescue => e
monitor.error(e.message, 'read_diaries_error', user_uuid:)
end
private
def empty_response(diaries)
{
dependency_decs: diaries.dig(:dependency_decs, :dependency_dec),
diaries: []
}
end
def standard_response(diaries)
{
dependency_decs: diaries.dig(:dependency_decs, :dependency_dec),
diaries: diaries.dig(:diaries, :diary)
}
end
def normalize_dependency_decisions(dependency_decisions)
set1 = dependency_decisions.delete_if do |dependency_decision|
invalid_dependency_decision?(dependency_decision)
end
final = []
return final if set1.blank?
set2 = set1.group_by { |dependency_decision| dependency_decision[:person_id] }
set2.each_value do |array|
latest = array.max_by { |dd| dd[:award_effective_date] }
final << latest if latest[:dependency_status_type] != 'NAWDDEP'
end
final
end
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
def external_key
@external_key ||= begin
key = common_name.presence || email
key.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
def invalid_dependency_decision?(dependency_decision)
!dependency_decision.is_a?(Hash) ||
!dependency_decision.key?(:award_effective_date) ||
dependency_decision[:award_effective_date].future?
end
def monitor
@monitor ||= BGS::Monitor.new
end
end
end
|
0
|
code_files/vets-api-private/app/services/bgs
|
code_files/vets-api-private/app/services/bgs/people/response.rb
|
# frozen_string_literal: true
module BGS
module People
class Response
attr_reader :response, :status
def initialize(response, status: :ok)
@response = response
@status = status
end
def participant_id
return if response.blank?
response[:ptcpnt_id]
end
def file_number
return if response.blank?
response[:file_nbr]
end
def ssn_number
return if response.blank?
response[:ssn_nbr]
end
def cache?
status == :ok
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/bgs
|
code_files/vets-api-private/app/services/bgs/people/request.rb
|
# frozen_string_literal: true
module BGS
# The People module provides Redis-backed caching for BGS (Benefits Gateway Service)
# person lookups. It wraps remote calls to BGS and caches responses to minimize
# repeated network requests for the same participant identifiers.
#
# This module contains classes that handle both the request logic (via Request)
# and response handling (via Response) for BGS person data retrieval operations.
#
# @example Using the People::Request service
# request = BGS::People::Request.new
# response = request.find_person_by_participant_id(user: current_user)
# if response.ok?
# person_data = response.person
# end
module People
# Request is a Redis-backed wrapper around the BGS People lookup.
# It provides a cached entrypoint for `find_person_by_participant_id`
# to avoid repeated remote calls for the same participant id.
class Request < Common::RedisStore
include Common::CacheAside
# Redis key used for caching responses from BGS find_person_by_participant_id
REDIS_CONFIG_KEY = :bgs_find_person_by_participant_id_response
redis_config_key REDIS_CONFIG_KEY
# Public: Retrieve the BGS person response for the given user.
#
# user - a User-like object that responds to `participant_id`.
#
# Returns a BGS::People::Response instance (may represent :no_id).
def find_person_by_participant_id(user:)
find_person_by_participant_id_cached_response(user)
end
private
# Internal: Get the cached response or fetch from BGS if not present.
#
# Builds a cache key using the user's participant_id. If no participant_id
# is available, returns a Response indicating no id was provided.
#
# user - a User-like object that responds to `participant_id`.
#
# Returns a BGS::People::Response instance.
def find_person_by_participant_id_cached_response(user)
user_key = user.participant_id
# If the user has no participant id, short-circuit with a no_id response.
return BGS::People::Response.new(nil, status: :no_id) unless user_key
# do_cached_with will attempt to read from Redis and, on a miss,
# execute the provided block to fetch fresh data and cache it.
do_cached_with(key: user_key) do
# Delegate the actual BGS call to the service layer.
BGS::People::Service.new(user).find_person_by_participant_id
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/bgs
|
code_files/vets-api-private/app/services/bgs/people/service.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
module BGS
module People
class Service
class VAFileNumberNotFound < StandardError; end
include Vets::SharedLogging
attr_reader :ssn,
:participant_id,
:common_name,
:email,
:icn
def initialize(user)
@ssn = user.ssn
@participant_id = user.participant_id
@common_name = user.common_name
@email = user.email
@icn = user.icn
end
def find_person_by_participant_id
raw_response = service.people.find_person_by_ptcpnt_id(participant_id, ssn)
if raw_response.blank?
exception = VAFileNumberNotFound.new
log_exception_to_sentry(exception, { icn: }, { team: Constants::SENTRY_REPORTING_TEAM })
log_exception_to_rails(exception)
end
BGS::People::Response.new(raw_response, status: :ok)
rescue => e
log_exception_to_sentry(e, { icn: }, { team: Constants::SENTRY_REPORTING_TEAM })
log_exception_to_rails(e)
BGS::People::Response.new(nil, status: :error)
end
private
def service
@service ||= BGS::Services.new(external_uid: icn, external_key:)
end
def external_key
@external_key ||= begin
key = common_name.presence || email
key&.first(Constants::EXTERNAL_KEY_MAX_LENGTH)
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/mhv
|
code_files/vets-api-private/app/services/mhv/user_account/creator.rb
|
# frozen_string_literal: true
require 'mhv/account_creation/service'
module MHV
module UserAccount
class Creator
attr_reader :user_verification, :break_cache, :from_cache_only
def initialize(user_verification:, break_cache: false, from_cache_only: false)
@user_verification = user_verification
@break_cache = break_cache
@from_cache_only = from_cache_only
end
def perform
validate!
create_mhv_user_account!
rescue ActiveModel::ValidationError, Errors::ValidationError => e
log_error(e, :validation)
raise Errors::ValidationError, e.message
rescue Common::Client::Errors::Error => e
log_error(e, :client)
raise Errors::MHVClientError.new(e.message, e.body)
rescue => e
log_error(e, :creator)
raise Errors::CreatorError, e.message
end
private
def create_mhv_user_account!
return nil if mhv_account_creation_response.nil? && from_cache_only
account = MHVUserAccount.new(mhv_account_creation_response)
account.validate!
MPIData.find(icn)&.destroy unless from_cache_only
account
end
def mhv_account_creation_response
@mhv_account_creation_response ||= mhv_client.create_account(icn:, email:, tou_occurred_at:, break_cache:,
from_cache_only:)
end
def icn
@icn ||= user_account.icn
end
def email
@email ||= user_verification.user_credential_email&.credential_email
end
def current_tou_agreement
@current_tou_agreement ||= user_account.terms_of_use_agreements.current.last
end
def user_account
@user_account ||= user_verification.user_account
end
def tou_occurred_at
current_tou_agreement.created_at
end
def mhv_client
MHV::AccountCreation::Service.new
end
def validate!
errors = [
('ICN must be present' if icn.blank?),
('Current terms of use agreement must be present' if current_tou_agreement.blank?),
("Current terms of use agreement must be 'accepted'" unless current_tou_agreement&.accepted?)
].compact
raise Errors::ValidationError, errors.join(', ') if errors.present?
end
def log_error(error, type)
Rails.logger.error("[MHV][UserAccount][Creator] #{type} error", error_message: error.message, icn:)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/mhv
|
code_files/vets-api-private/app/services/mhv/user_account/errors.rb
|
# frozen_string_literal: true
module MHV
module UserAccount
module Errors
class UserAccountError < StandardError
def as_json
message.split(',').map { |m| { title: class_name, detail: m.strip } }
end
private
def class_name
self.class.name.demodulize.underscore.humanize
end
end
class CreatorError < UserAccountError; end
class ValidationError < UserAccountError; end
class MHVClientError < UserAccountError
attr_accessor :body
def initialize(message, body = nil)
super(message)
@body = body
end
def as_json
[{ title: message, detail: body['message'], code: body['errorCode'] }]
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/users/scaffold.rb
|
# frozen_string_literal: true
module Users
# Struct class serving as the pre-serialized object that is passed to the UserSerializer
# during the '/v0/user' endpoint call.
#
# Note that with Struct's, parameter order matters. Namely having `errors` first
# and `status` second.
#
# rubocop:disable Style/StructInheritance
class Scaffold < Struct.new(:errors, :status, :services, :user_account, :profile, :va_profile,
:veteran_status, :in_progress_forms, :prefills_available, :vet360_contact_information,
:session, :onboarding)
end
# rubocop:enable Style/StructInheritance
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/users/exception_handler.rb
|
# frozen_string_literal: true
require 'common/exceptions'
require 'common/client/concerns/service_status'
require 'mpi/errors/errors'
require 'va_profile/veteran_status/va_profile_error'
module Users
class ExceptionHandler
include Common::Client::Concerns::ServiceStatus
attr_reader :error, :service
# @param error [ErrorClass] An external service error
# @param service [String] The name of the external service (i.e. 'VAProfile' or 'MVI')
#
def initialize(error, service)
@error = validate!(error)
@service = service
end
# Serializes the initialized error into one of the predetermined error types.
# Uses error classes that can be triggered by MVI or VA Profile (formerly Vet360).
#
# The serialized error format is modelled after the Maintenance Windows schema,
# per the FE's request.
#
# @return [Hash] A serialized version of the initialized error. Follows maintenance
# window schema.
# @see https://department-of-veterans-affairs.github.io/va-digital-services-platform-docs/api-reference/#/site/getMaintenanceWindows
#
def serialize_error
case error
when Common::Exceptions::BaseError
base_error
when VAProfile::VeteranStatus::VAProfileError
if error.status == 404
title_error(:not_found)
else
standard_va_profile_error
end
when Common::Client::Errors::ClientError
client_error
when MPI::Errors::RecordNotFound, MPI::Errors::DuplicateRecords
mpi_error(404)
when MPI::Errors::FailedRequestError
mpi_error(503)
else
standard_error
end
end
private
def validate!(error)
raise Common::Exceptions::ParameterMissing.new('error'), 'error' if error.blank?
error
end
def base_error
exception = error.errors.first
error_template.merge(
description: "#{exception.code}, #{exception.status}, #{exception.title}, #{exception.detail}",
status: exception.status.to_i
)
end
def client_error
error_template.merge(
description: "#{error.class}, #{error.status}, #{error.message}, #{error.body}",
status: error.status.to_i
)
end
def title_error(_type)
error_template.merge(
description: "#{error.class}, 404 Veteran Status title not found",
status: 404
)
end
def standard_va_profile_error
error_template.merge(
description: "#{error.class}, #{error.message}, #{error} VA Profile failure",
status: standard_error_status(error)
)
end
def client_error_related_to_title38
error_template.merge(
description: "#{error.class}, Client error related to title38",
status: 404
)
end
def mpi_error(status)
error_template.merge(
description: "#{error.class}, #{error.message}",
status:
)
end
def standard_error
error_template.merge(
description: "#{error.class}, #{error.message}, #{error}",
status: standard_error_status(error)
)
end
def error_template
{
external_service: service,
start_time: Time.current.iso8601,
end_time: nil,
description: nil,
status: nil
}
end
def standard_error_status(error)
error.try(:status).presence ||
error.try(:status_code).presence ||
error.try(:code).presence ||
503
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/users/profile.rb
|
# frozen_string_literal: true
require 'common/exceptions'
require 'common/client/concerns/service_status'
require 'mhv/oh_facilities_helper/service'
module Users
class Profile
include Common::Client::Concerns::ServiceStatus
HTTP_OK = 200
HTTP_SOME_ERRORS = 296
attr_reader :user, :scaffold, :oh_facilities_helper
def initialize(user, session = nil)
@user = validate!(user)
@session = session || {}
@scaffold = Users::Scaffold.new([], HTTP_OK)
@oh_facilities_helper = MHV::OhFacilitiesHelper::Service.new(user)
end
# Fetches and serializes all of the initialized user's profile data that
# is returned in the '/v0/user' endpoint.
#
# If there are no external service errors, the status property is set to 200,
# and the `errors` property is set to nil.
#
# If there *are* errors from any associated external services, the status
# property is set to 296, and serialized versions of the errors are
# added to the `errors` array.
#
# @return [Struct] A Struct composed of the fetched, serialized profile data.
#
def pre_serialize
fetch_and_serialize_profile
update_status_and_errors
scaffold
end
private
def validate!(user)
raise Common::Exceptions::ParameterMissing.new('user'), 'user' unless user&.class == User
user
end
def fetch_and_serialize_profile
scaffold.user_account = user_account
scaffold.profile = profile
scaffold.vet360_contact_information = vet360_contact_information
scaffold.va_profile = mpi_profile
scaffold.veteran_status = veteran_status
scaffold.in_progress_forms = in_progress_forms
scaffold.prefills_available = prefills_available
scaffold.services = services
scaffold.session = session_data
scaffold.onboarding = onboarding
end
def user_account
{ id: user.user_account_uuid }
rescue => e
scaffold.errors << Users::ExceptionHandler.new(e, 'UserAccount').serialize_error
nil
end
# rubocop:disable Metrics/MethodLength
def profile
{
email: user.email,
first_name: user.first_name,
middle_name: user.middle_name,
last_name: user.last_name,
preferred_name: user.preferred_name,
birth_date: user.birth_date,
gender: user.gender,
zip: user.postal_code,
last_signed_in: user.last_signed_in,
loa: user.loa,
multifactor: user.multifactor,
verified: user.loa3?,
sign_in: user.identity.sign_in,
authn_context: user.authn_context,
claims:,
icn: user.icn,
npi_id: user.npi_id,
birls_id: user.birls_id,
edipi: user.edipi,
sec_id: user.sec_id,
logingov_uuid: user.logingov_uuid,
idme_uuid: user.idme_uuid,
id_theft_flag: user.id_theft_flag,
initial_sign_in: user.initial_sign_in
}
end
# rubocop:enable Metrics/MethodLength
def claims
if Flipper.enabled?(:profile_user_claims, user)
{
appeals: AppealsPolicy.new(user).access?,
coe: CoePolicy.new(user).access?,
communication_preferences: Vet360Policy.new(user).access? &&
CommunicationPreferencesPolicy.new(user).access?,
connected_apps: true,
medical_copays: MedicalCopaysPolicy.new(user).access?,
military_history: Vet360Policy.new(user).military_access?,
payment_history: BGSPolicy.new(user).access?(log_stats: false),
personal_information: MPIPolicy.new(user).queryable?,
rating_info: LighthousePolicy.new(user).rating_info_access?,
**form_526_required_identifiers
}
end
end
def form_526_required_identifiers
return {} unless Flipper.enabled?(:form_526_required_identifiers_in_user_object, user)
{ form526_required_identifier_presence: Users::Form526UserIdentifiersStatusService.call(user) }
end
def vet360_contact_information
person = user.vet360_contact_info
return {} if person.blank?
email_object = person.email
{
vet360_id: user.vet360_id,
va_profile_id: user.vet360_id,
email: email_object,
residential_address: person.residential_address,
mailing_address: person.mailing_address,
mobile_phone: person.mobile_phone,
home_phone: person.home_phone,
work_phone: person.work_phone,
temporary_phone: person.temporary_phone,
fax_number: person.fax_number,
contact_email_verified: email_object&.contact_email_verified?
}
rescue => e
handle_service_error(e, 'VAProfile', 'vet360_contact_information')
nil
end
# rubocop:disable Metrics/MethodLength
def mpi_profile
unless user.loa3?
error_hash = {
external_service: 'MVI',
description: 'User is not LOA3, MPI access denied',
user_uuid: user.uuid,
loa: user.loa,
method: 'mpi_profile'
}
log_external_service_error(error_hash)
return { status: RESPONSE_STATUS[:ok] }
end
status = user.mpi_status
if status == :ok
{
status: RESPONSE_STATUS[:ok],
birth_date: user.birth_date_mpi,
family_name: user.last_name_mpi,
gender: user.gender_mpi,
given_names: user.given_names,
is_cerner_patient: !user.cerner_id.nil?,
cerner_id: user.cerner_id,
cerner_facility_ids: user.cerner_facility_ids,
facilities: user.va_treatment_facility_ids.map { |id| facility(id) },
user_at_pretransitioned_oh_facility: oh_facilities_helper.user_at_pretransitioned_oh_facility?,
user_facility_ready_for_info_alert: oh_facilities_helper.user_facility_ready_for_info_alert?,
user_facility_migrating_to_oh: oh_facilities_helper.user_facility_migrating_to_oh?,
va_patient: user.va_patient?,
mhv_account_state: user.mhv_account_state,
active_mhv_ids: user.active_mhv_ids,
scheduling_preferences_pilot_eligible:
}
else
handle_service_error(user.mpi_error, 'MVI', 'mpi_profile')
nil
end
end
# rubocop:enable Metrics/MethodLength
def veteran_status
if user.edipi.blank?
log_for_missing_edipi
return build_veteran_status_object(nil, nil)
end
build_veteran_status_object(user.veteran?, user.served_in_military?)
rescue => e
handle_service_error(e, 'VAProfile', 'veteran_status')
nil
end
def in_progress_forms
InProgressForm.submission_pending.for_user(user).map do |form|
{
form: form.form_id,
metadata: form.metadata,
lastUpdated: form.updated_at.to_i
}
end
end
def prefills_available
return [] if user.identity.blank?
FormProfile.prefill_enabled_forms
end
def services
Users::Services.new(user).authorizations
end
def update_status_and_errors
if scaffold.errors.present?
scaffold.status = HTTP_SOME_ERRORS
elsif user.edipi.blank? || !user.loa3?
scaffold.errors = []
else
scaffold.errors = nil
end
end
def facility(facility_id)
cerner_facility_ids = user.cerner_facility_ids || []
{
facility_id:,
is_cerner: cerner_facility_ids.include?(facility_id)
}
end
def session_data
{
auth_broker: @user.identity.sign_in[:auth_broker],
ssoe: @session[:ssoe_transactionid] ? true : false,
transactionid: @session[:ssoe_transactionid]
}
end
def onboarding
{
show: user.show_onboarding_flow_on_login
}
end
def log_external_service_error(error_hash)
Rails.logger.warn(
'Users::Profile external service error',
{
error: error_hash,
user_uuid: user.uuid,
loa: user.loa
}.to_json
)
end
def log_for_missing_edipi
Rails.logger.info(
'Skipping VAProfile veteran status call, No EDIPI present',
user_uuid: user.uuid,
loa: user.loa
)
end
def build_veteran_status_object(is_veteran, served_in_military)
{
status: RESPONSE_STATUS[:ok],
is_veteran:,
served_in_military:
}
end
def handle_service_error(error, service, method_name)
error_hash = Users::ExceptionHandler.new(error, service).serialize_error
error_hash[:method] = method_name
scaffold.errors << error_hash
log_external_service_error(error_hash)
end
def scheduling_preferences_pilot_eligible
return false unless Flipper.enabled?(:profile_scheduling_preferences, user)
UserVisnService.new(user).in_pilot_visn?
rescue => e
Rails.logger.error("Error checking scheduling preferences pilot eligibility: #{e.message}")
false
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/users/form_526_user_identifiers_status_service.rb
|
# frozen_string_literal: true
# For a given user, checks for the presence of certain identifiers required by Form526
# Returns a mapping of the identifier name to a boolean indicating whether we have that information for a user or not
module Users
class Form526UserIdentifiersStatusService
FORM526_REQUIRED_IDENTIFIERS = %w[participant_id birls_id ssn birth_date edipi].freeze
def self.call(*)
new(*).call
end
def initialize(user)
@user = user
end
def call
identifer_mapping
end
private
def identifer_mapping
FORM526_REQUIRED_IDENTIFIERS.index_with { |identifier| @user[identifier].present? }
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/users/services.rb
|
# frozen_string_literal: true
require 'backend_services'
module Users
class Services
attr_reader :user
def initialize(user)
@user = user
@list = auth_free_services
end
# Checks if the initialized user has authorization to access any of the
# below services. Returns an array of services they have access to.
#
# @return [Array<String>] Array of names of services they have access to
#
def authorizations
@list << BackendServices::RX if user.authorize :mhv_prescriptions, :access?
@list << BackendServices::MESSAGING if user.authorize :mhv_messaging, :access?
@list << BackendServices::MEDICAL_RECORDS if user.authorize :mhv_medical_records, :access?
@list << BackendServices::HEALTH_RECORDS if user.authorize :mhv_health_records, :access?
@list << BackendServices::EVSS_CLAIMS if user.authorize :evss, :access?
@list << BackendServices::LIGHTHOUSE if user.authorize :lighthouse, :access?
@list << BackendServices::FORM526 if user.authorize :evss, :access_form526?
@list << BackendServices::ADD_PERSON_PROXY if user.authorize :mpi, :access_add_person_proxy?
@list << BackendServices::USER_PROFILE if user.can_access_user_profile?
@list << BackendServices::APPEALS_STATUS if user.authorize :appeals, :access?
@list << BackendServices::ID_CARD if user.can_access_id_card?
@list << BackendServices::IDENTITY_PROOFED if user.loa3?
@list << BackendServices::VET360 if user.can_access_vet360?
@list << BackendServices::DGI if user.authorize :dgi, :access?
@list
end
private
def auth_free_services
[
BackendServices::FACILITIES,
BackendServices::HCA,
BackendServices::EDUCATION_BENEFITS,
BackendServices::SAVE_IN_PROGRESS,
BackendServices::FORM_PREFILL
]
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/form1010cg/auditor.rb
|
# frozen_string_literal: true
module Form1010cg
class Auditor
attr_reader :logger
STATSD_KEY_PREFIX = 'api.form1010cg'
LOGGER_PREFIX = 'Form 10-10CG'
LOGGER_FILTER_KEYS = [:veteran_name].freeze
METRICS = lambda do
submission_prefix = "#{STATSD_KEY_PREFIX}.submission"
process_prefix = "#{STATSD_KEY_PREFIX}.process"
process_job_prefix = "#{STATSD_KEY_PREFIX}.process_job"
OpenStruct.new(
submission: OpenStruct.new(
attempt: "#{submission_prefix}.attempt",
caregivers: OpenStruct.new(
primary_no_secondary: "#{submission_prefix}.caregivers.primary_no_secondary",
primary_one_secondary: "#{submission_prefix}.caregivers.primary_one_secondary",
primary_two_secondary: "#{submission_prefix}.caregivers.primary_two_secondary",
no_primary_one_secondary: "#{submission_prefix}.caregivers.no_primary_one_secondary",
no_primary_two_secondary: "#{submission_prefix}.caregivers.no_primary_two_secondary"
),
failure: OpenStruct.new(
client: OpenStruct.new(
data: "#{submission_prefix}.failure.client.data",
qualification: "#{submission_prefix}.failure.client.qualification"
),
attachments: "#{submission_prefix}.failure.attachments"
)
),
pdf_download: "#{STATSD_KEY_PREFIX}.pdf_download",
process: OpenStruct.new(
success: "#{process_prefix}.success",
failure: "#{process_prefix}.failure"
),
process_job: OpenStruct.new(
success: "#{process_job_prefix}.success",
failure: "#{process_job_prefix}.failure"
)
)
end.call
def self.metrics
METRICS
end
def initialize(logger = Rails.logger)
@logger = logger
end
def record(event, **context)
message = "record_#{event}"
context.any? ? send(message, **context) : send(message)
end
def record_submission_attempt
increment self.class.metrics.submission.attempt
end
def record_caregivers(claim)
secondaries_count = 0
%w[one two].each do |attr|
secondaries_count += 1 if claim.public_send("secondary_caregiver_#{attr}_data").present?
end
if claim.primary_caregiver_data.present?
increment_primary_caregiver_data(secondaries_count)
else
increment_no_primary_caregiver_data(secondaries_count)
end
end
def record_submission_failure_client_data(errors:, claim_guid: nil)
increment self.class.metrics.submission.failure.client.data
log 'Submission Failed: invalid data provided by client', claim_guid:, errors:
end
def record_submission_failure_client_qualification(claim_guid:)
increment self.class.metrics.submission.failure.client.qualification
log 'Submission Failed: qualifications not met', claim_guid:
end
def record_pdf_download
increment self.class.metrics.pdf_download
end
def record_attachments_delivered(claim_guid:, carma_case_id:, attachments:)
log(
'Attachments Delivered',
claim_guid:,
carma_case_id:,
attachments:
)
end
def log_mpi_search_result(claim_guid:, form_subject:, result:)
labels = { found: 'found', not_found: 'NOT FOUND', skipped: 'search was skipped' }
result_label = labels[result]
log("MPI Profile #{result_label} for #{form_subject.titleize}", { claim_guid: })
end
def log_caregiver_request_duration(context:, event:, start_time:)
measure_duration(self.class.metrics[context][event], start_time)
end
private
def increment_primary_caregiver_data(secondaries_count)
caregivers = self.class.metrics.submission.caregivers
case secondaries_count
when 0
increment(caregivers.primary_no_secondary)
when 1
increment(caregivers.primary_one_secondary)
when 2
increment(caregivers.primary_two_secondary)
end
end
def increment_no_primary_caregiver_data(secondaries_count)
caregivers = self.class.metrics.submission.caregivers
case secondaries_count
when 1
increment(caregivers.no_primary_one_secondary)
when 2
increment(caregivers.no_primary_two_secondary)
end
end
def increment(stat)
StatsD.increment stat
end
def measure_duration(stat, start_time)
current_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
StatsD.measure "#{stat}.duration", (current_time - start_time).round(4)
end
def log(message, context_hash = {})
logger.send(:info, "[#{LOGGER_PREFIX}] #{message}", **deep_apply_filter(context_hash))
end
def deep_apply_filter(value)
case value
when Array
value.map { |v| deep_apply_filter(v) }
when Hash
value.each_with_object({}) do |(key, v), result|
result[key] = if LOGGER_FILTER_KEYS.include?(key.to_s) || LOGGER_FILTER_KEYS.include?(key.to_sym)
ActiveSupport::ParameterFilter::FILTERED
else
deep_apply_filter(v)
end
end
else
value
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/form1010cg/service.rb
|
# frozen_string_literal: true
# This service manages the interactions between CaregiversAssistanceClaim, CARMA, and Form1010cg::Submission.
require 'carma/client/mule_soft_client'
require 'carma/models/submission'
require 'carma/models/attachments'
require 'mpi/service'
module Form1010cg
class Service
extend Forwardable
class InvalidVeteranStatus < StandardError
end
attr_accessor :claim, # SavedClaim::CaregiversAssistanceClaim
:submission # Form1010cg::Submission
NOT_FOUND = 'NOT_FOUND'
AUDITOR = Form1010cg::Auditor.new
def self.collect_attachments(claim)
poa_attachment_id = claim.parsed_form['poaAttachmentId']
claim_pdf_path = claim.to_pdf(sign: true)
poa_attachment_path = nil
if poa_attachment_id
attachment = Form1010cg::Attachment.find_by(guid: claim.parsed_form['poaAttachmentId'])
poa_attachment_path = attachment.to_local_file if attachment
end
[claim_pdf_path, poa_attachment_path]
end
def initialize(claim, submission = nil)
# This service makes assumptions on what data is present on the claim
# Make sure the claim is valid, so we can be assured the required data is present.
claim.valid? || raise(Common::Exceptions::ValidationErrors, claim)
# The CaregiversAssistanceClaim we are processing with this service
@claim = claim
# The Form1010cg::Submission
@submission = submission
# Store for the search results we will run on MPI
@cache = {
# [form_subject]: String - The person's ICN
# [form_subject]: NOT_FOUND - This person could not be found in MPI
# [form_subject]: nil - An MPI search has not been conducted for this person
icns: {}
}
end
def process_claim_v2!
start_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
payload = CARMA::Models::Submission.from_claim(claim, build_metadata).to_request_payload
claim_pdf_path, poa_attachment_path = self.class.collect_attachments(claim)
payload[:records] = generate_records(claim_pdf_path, poa_attachment_path)
[claim_pdf_path, poa_attachment_path].each { |p| File.delete(p) if p.present? }
result = CARMA::Client::MuleSoftClient.new.create_submission_v2(payload)
self.class::AUDITOR.log_caregiver_request_duration(context: :process, event: :success, start_time:)
log_submission_complete(claim.guid, claim_pdf_path, poa_attachment_path, result)
result
rescue => e
self.class::AUDITOR.log_caregiver_request_duration(context: :process, event: :failure, start_time:)
Rails.logger.error(
'[10-10CG] - Error processing Caregiver submission',
{ form: '10-10CG', exception: e, claim_guid: claim.guid }
)
raise e
end
# Will raise an error unless the veteran specified on the claim's data can be found in MVI
#
# @return [nil]
def assert_veteran_status
if icn_for('veteran') == NOT_FOUND
error = InvalidVeteranStatus.new
Rails.logger.error('[10-10CG] - Error fetching Veteran ICN', { error: })
raise error
end
end
# Returns a metadata hash:
#
# {
# veteran: {
# is_veteran: true | false | nil,
# icn: String | nil
# },
# primaryCaregiver?: { icn: String | nil },
# secondaryCaregiverOne?: { icn: String | nil },
# secondaryCaregiverTwo?: { icn: String | nil }
# }
def build_metadata
# Set the ICN's for each form_subject on the metadata hash
metadata = claim.form_subjects.each_with_object({}) do |form_subject, obj|
icn = icn_for(form_subject)
obj[form_subject.snakecase.to_sym] = {
icn: icn == NOT_FOUND ? nil : icn
}
end
# Disabling the veteran status search since there is an issue with searching
# for a veteran status using an ICN. Only edipi works. Consider adding this back in
# once ICN searches work or we refactor our veteran status search to use the edipi.
metadata[:veteran][:is_veteran] = false
metadata
end
# Will search MVI for the provided form subject and return (1) the matching profile's ICN or (2) `NOT_FOUND`.
# The result will be cached and subsequent calls will return the cached value, preventing additional api requests.
#
# @param form_subject [String] The key in the claim's data that contains this person's info (ex: "veteran")
# @return [String | NOT_FOUND] Returns the icn of the form subject if found, and NOT_FOUND otherwise.
def icn_for(form_subject)
cached_icn = @cache[:icns][form_subject]
return cached_icn unless cached_icn.nil?
form_subject_data = claim.parsed_form[form_subject]
if form_subject_data['ssnOrTin'].nil?
log_mpi_search_result form_subject, :skipped
return @cache[:icns][form_subject] = NOT_FOUND
end
response = mpi_service_find_profile_by_attributes(form_subject_data)
if response.ok?
log_mpi_search_result form_subject, :found
return @cache[:icns][form_subject] = response.profile.icn
end
if response.not_found?
log_mpi_search_result form_subject, :not_found
return @cache[:icns][form_subject] = NOT_FOUND
end
raise response.error if response.error
@cache[:icns][form_subject] = NOT_FOUND
end
private
def log_submission_complete(guid, claim_pdf_path, poa_attachment_path, response_data)
attachment_data = (response_data.dig('record', 'results') || []).map do |attachment|
{
reference_id: attachment['referenceId'] || '',
id: attachment['id'] || ''
}
end
Rails.logger.info(
'[10-10CG] - CARMA submission complete',
{
form: '10-10CG',
claim_guid: guid,
claim_pdf_path_length: claim_pdf_path&.length,
poa_attachment_path_length: poa_attachment_path&.length,
carma_case: {
created_at: response_data.dig('data', 'carmacase', 'createdAt') || '',
id: response_data.dig('data', 'carmacase', 'id') || '',
attachments: attachment_data
}
}
)
end
def generate_records(claim_pdf_path, poa_attachment_path)
[
{
file_path: claim_pdf_path, document_type: CARMA::Models::Attachment::DOCUMENT_TYPES['10-10CG']
},
{
file_path: poa_attachment_path, document_type: CARMA::Models::Attachment::DOCUMENT_TYPES['POA']
}
].map do |doc_data|
next if doc_data[:file_path].blank?
CARMA::Models::Attachment.new(
doc_data.merge(
carma_case_id: nil,
veteran_name: {
first: claim.parsed_form.dig('veteran', 'fullName', 'first'),
last: claim.parsed_form.dig('veteran', 'fullName', 'last')
},
document_date: claim.created_at, id: nil
)
).to_request_payload.compact
end.compact
end
def mpi_service_find_profile_by_attributes(form_subject_data)
mpi_service.find_profile_by_attributes(first_name: form_subject_data['fullName']['first'],
last_name: form_subject_data['fullName']['last'],
birth_date: form_subject_data['dateOfBirth'],
ssn: form_subject_data['ssnOrTin'])
end
def mpi_service
@mpi_service ||= MPI::Service.new
end
def log_mpi_search_result(form_subject, result)
self.class::AUDITOR.log_mpi_search_result(
claim_guid: claim.guid,
form_subject:,
result:
)
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/terms_of_use/errors.rb
|
# frozen_string_literal: true
module TermsOfUse
module Errors
class AcceptorError < StandardError; end
class DeclinerError < StandardError; end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/terms_of_use/logger.rb
|
# frozen_string_literal: true
module TermsOfUse
class Logger
STATSD_PREFIX = 'api.terms_of_use_agreements'
def initialize(terms_of_use_agreement:)
@terms_of_use_agreement = terms_of_use_agreement
end
def perform
log_terms_of_use_agreement
increment_terms_of_use_agreement_statsd
end
private
attr_reader :terms_of_use_agreement
def log_terms_of_use_agreement
Rails.logger.info("[TermsOfUseAgreement] [#{prefix.capitalize}]", context)
end
def increment_terms_of_use_agreement_statsd
StatsD.increment("#{STATSD_PREFIX}.#{prefix}",
tags: ["version:#{terms_of_use_agreement.agreement_version}"])
end
def prefix
@prefix ||= terms_of_use_agreement.response
end
def context
@context ||= {
terms_of_use_agreement_id: terms_of_use_agreement.id,
user_account_uuid: user_account.id,
icn: user_account.icn,
agreement_version: terms_of_use_agreement.agreement_version,
response: terms_of_use_agreement.response
}
end
def user_account
@user_account ||= terms_of_use_agreement.user_account
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/terms_of_use/decliner.rb
|
# frozen_string_literal: true
require 'terms_of_use/exceptions'
require 'sidekiq/attr_package'
module TermsOfUse
class Decliner
include ActiveModel::Validations
attr_reader :user_account, :icn, :version
validates :user_account, :icn, :version, presence: true
def initialize(user_account:, version:)
@user_account = user_account
@icn = user_account&.icn
@version = version
validate!
rescue ActiveModel::ValidationError => e
log_and_raise_decliner_error(e)
end
def perform!
terms_of_use_agreement.declined!
update_sign_up_service
Logger.new(terms_of_use_agreement:).perform
terms_of_use_agreement
rescue ActiveRecord::RecordInvalid => e
log_and_raise_decliner_error(e)
end
private
def terms_of_use_agreement
@terms_of_use_agreement ||= user_account.terms_of_use_agreements.new(agreement_version: version)
end
def update_sign_up_service
Rails.logger.info('[TermsOfUse] [Decliner] update_sign_up_service', { icn: })
SignUpServiceUpdaterJob.perform_async(user_account.id, version)
end
def log_and_raise_decliner_error(error)
Rails.logger.error("[TermsOfUse] [Decliner] Error: #{error.message}", { user_account_id: user_account&.id })
raise Errors::DeclinerError, error.message
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/terms_of_use/acceptor.rb
|
# frozen_string_literal: true
require 'terms_of_use/exceptions'
require 'sidekiq/attr_package'
module TermsOfUse
class Acceptor
include ActiveModel::Validations
attr_reader :user_account, :icn, :version, :sync
validates :user_account, :icn, :version, presence: true
def initialize(user_account:, version:, sync: false)
@user_account = user_account
@version = version
@sync = sync
@icn = user_account&.icn
validate!
rescue ActiveModel::ValidationError => e
log_and_raise_acceptor_error(e)
end
def perform!
terms_of_use_agreement.accepted!
update_sign_up_service
Logger.new(terms_of_use_agreement:).perform
terms_of_use_agreement
rescue ActiveRecord::RecordInvalid, StandardError => e
log_and_raise_acceptor_error(e)
end
private
def terms_of_use_agreement
@terms_of_use_agreement ||= user_account.terms_of_use_agreements.new(agreement_version: version)
end
def update_sign_up_service
Rails.logger.info('[TermsOfUse] [Acceptor] update_sign_up_service', { icn: })
SignUpServiceUpdaterJob.set(sync:).perform_async(user_account.id, version)
end
def log_and_raise_acceptor_error(error)
Rails.logger.error("[TermsOfUse] [Acceptor] Error: #{error.message}", { user_account_id: user_account&.id })
raise Errors::AcceptorError, error.message
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/login/errors.rb
|
# frozen_string_literal: true
module Login
module Errors
class UserVerificationNotCreatedError < StandardError; end
class UnknownLoginTypeError < StandardError; end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/login/user_acceptable_verified_credential_updater_logger.rb
|
# frozen_string_literal: true
module Login
class UserAcceptableVerifiedCredentialUpdaterLogger
STATSD_KEY_PREFIX = 'api.user_avc_updater'
LOG_MESSAGE = '[UserAcceptableVerifiedCredentialUpdater] - User AVC Updated'
FROM_TYPES = [MHV_TYPE = 'mhv', DSLOGON_TYPE = 'dslogon', IDME_TYPE = 'idme', LOGINGOV_TYPE = 'logingov'].freeze
ADDED_TYPES = [AVC_TYPE = 'avc', IVC_TYPE = 'ivc'].freeze
def initialize(user_acceptable_verified_credential:)
@user_avc = user_acceptable_verified_credential
end
def perform
return if user_avc.nil?
increment_statsd
log_info
end
private
attr_reader :user_avc
def increment_statsd
statsd_keys.each do |key|
StatsD.increment(key, 1)
end
end
def log_info
Rails.logger.info(LOG_MESSAGE, log_payload)
end
def statsd_keys
@statsd_keys ||= build_statsd_keys
end
def log_payload
@log_payload ||= build_log_payload
end
def added_type
@added_type ||= if avc_added?
AVC_TYPE
elsif ivc_added?
IVC_TYPE
end
end
def added_from_type
@added_from_type ||= if from_mhv?
MHV_TYPE
elsif from_dslogon?
DSLOGON_TYPE
elsif from_logingov?
LOGINGOV_TYPE
elsif from_idme?
IDME_TYPE
end
end
def build_statsd_keys
keys = []
return keys unless added_type.present? && added_from_type.present?
keys << "#{STATSD_KEY_PREFIX}.#{added_from_type}.#{added_type}.added"
if [MHV_TYPE, DSLOGON_TYPE].include?(added_from_type)
keys << "#{STATSD_KEY_PREFIX}.#{MHV_TYPE}_#{DSLOGON_TYPE}.#{added_type}.added"
end
keys
end
def build_log_payload
payload = {}
payload[:added_type] = added_type
payload[:added_from] = added_from_type if added_from_type.present?
payload[:user_account_id] = user_account.id
payload[:mhv_uuid] = mhv_credential.mhv_uuid if added_from_type == MHV_TYPE
payload[:dslogon_uuid] = dslogon_credential.dslogon_uuid if added_from_type == DSLOGON_TYPE
payload[:backing_idme_uuid] = backing_idme_uuid if backing_idme_uuid.present?
payload[:idme_uuid] = idme_credential&.idme_uuid
payload[:logingov_uuid] = logingov_credential&.logingov_uuid
payload
end
def user_account
@user_account ||= user_avc.user_account
end
def idme_credential
@idme_credential ||= user_verifications.idme.first
end
def logingov_credential
@logingov_credential ||= user_verifications.logingov.first
end
def mhv_credential
@mhv_credential ||= user_verifications.mhv.first
end
def dslogon_credential
@dslogon_credential ||= user_verifications.dslogon.first
end
def backing_idme_uuid
@backing_idme_uuid ||= if from_mhv?
mhv_credential.backing_idme_uuid
elsif from_dslogon?
dslogon_credential.backing_idme_uuid
end
end
def user_verifications
@user_verifications ||= user_account.user_verifications
end
def avc_added?
user_avc.saved_change_to_acceptable_verified_credential_at?
end
def ivc_added?
user_avc.saved_change_to_idme_verified_credential_at?
end
# When the newly added verified_credential_at is the only one that exists and
# the user has a mhv credential it is from mhv e.g. user_avc_updater.mhv.{added_type}.added
def from_mhv?
mhv_credential.present? && (added_ivc_only? || added_avc_only?)
end
# When the newly added verified_credential_at is the only one that exists and
# the user has a dslogon credential it is from dslogon e.g. user_avc_updater.dslogon.{added_type}.added
def from_dslogon?
dslogon_credential.present? && (added_ivc_only? || added_avc_only?)
end
def from_idme?
# When an avc is added on a uavc already having an ivc it is from idme.
# e.g. user_avc_updater.idme.avc.added
return user_avc.idme_verified_credential_at.present? if avc_added?
# When ivc is the only verified_credential_at that exists and it's not from mhv or dslogon,
# it's from idme e.g. user_avc_updater.idme.ivc.added
added_ivc_only? && !from_mhv? && !from_dslogon?
end
def from_logingov?
# When an ivc is added on a uavc already having an avc it is from logingov.
# e.g. user_avc_updater.logingov.ivc.added
return user_avc.acceptable_verified_credential_at.present? if ivc_added?
# When avc is the only verified_credential_at that exists and it's not from mhv or dslogon,
# it's from logingov e.g. user_avc_updater.logingov.avc.added
added_avc_only? && !from_mhv? && !from_dslogon?
end
##
# Checks if the newly added ivc is the only verified_credential_at that exists.
def added_ivc_only?
ivc_added? && user_avc.acceptable_verified_credential_at.nil?
end
##
# Checks if the newly added avc is the only verified_credential_at that exists.
def added_avc_only?
avc_added? && user_avc.idme_verified_credential_at.nil?
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/login/after_login_actions.rb
|
# frozen_string_literal: true
require 'login/errors'
module Login
class AfterLoginActions
attr_reader :current_user, :skip_mhv_account_creation
def initialize(user, skip_mhv_account_creation)
@current_user = user
@skip_mhv_account_creation = skip_mhv_account_creation
end
def perform
return unless current_user
Login::UserCredentialEmailUpdater.new(credential_email: current_user.email,
user_verification: current_user.user_verification).perform
Login::UserAcceptableVerifiedCredentialUpdater.new(user_account: @current_user.user_account).perform
id_mismatch_validations
create_mhv_account
current_user.provision_cerner_async(source: :ssoe)
if Settings.test_user_dashboard.env == 'staging'
TestUserDashboard::UpdateUser.new(current_user).call(Time.current)
TestUserDashboard::AccountMetrics.new(current_user).checkout
end
end
private
def create_mhv_account
return if skip_mhv_account_creation
current_user.create_mhv_account_async
end
def login_type
@login_type ||= current_user.identity.sign_in[:service_name]
end
def id_mismatch_validations
return unless current_user.loa3?
check_id_mismatch(current_user.identity.ssn, current_user.ssn_mpi, 'User Identity & MPI SSN values conflict')
check_id_mismatch(current_user.identity.icn, current_user.mpi_icn, 'User Identity & MPI ICN values conflict')
check_id_mismatch(current_user.identity.edipi, current_user.edipi_mpi,
'User Identity & MPI EDIPI values conflict')
end
def check_id_mismatch(identity_value, mpi_value, error_message)
return if mpi_value.blank?
if identity_value != mpi_value
error_data = { icn: current_user.icn }
error_data.merge!(identity_value:, mpi_value:) unless error_message.include?('SSN')
Rails.logger.warn("[SessionsController version:v1] #{error_message}", error_data)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/login/user_credential_email_updater.rb
|
# frozen_string_literal: true
module Login
class UserCredentialEmailUpdater
def initialize(credential_email:, user_verification:)
@credential_email = credential_email
@user_verification = user_verification
end
def perform
return unless user_verification && credential_email
update_user_credential_email
end
private
attr_reader :credential_email, :user_verification
def update_user_credential_email
user_credential_email = UserCredentialEmail.find_or_initialize_by(user_verification:)
user_credential_email.credential_email = credential_email
user_credential_email.save!
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/login/user_verifier.rb
|
# frozen_string_literal: true
module Login
class UserVerifier
def initialize(login_type:, # rubocop:disable Metrics/ParameterLists
auth_broker:,
mhv_uuid:,
idme_uuid:,
dslogon_uuid:,
logingov_uuid:,
icn:,
credential_attributes_digest: nil)
@login_type = login_type
@auth_broker = auth_broker
@mhv_uuid = mhv_uuid
@idme_uuid = idme_uuid
@dslogon_uuid = dslogon_uuid
@logingov_uuid = logingov_uuid
@icn = icn.presence
@credential_attributes_digest = credential_attributes_digest
@deprecated_log = nil
@user_account_mismatch_log = nil
end
def perform
find_or_create_user_verification
end
private
attr_reader :login_type,
:auth_broker,
:mhv_uuid,
:idme_uuid,
:dslogon_uuid,
:logingov_uuid,
:icn,
:deprecated_log,
:user_account_mismatch_log,
:new_user_log,
:credential_attributes_digest
MHV_TYPE = :mhv_uuid
IDME_TYPE = :idme_uuid
DSLOGON_TYPE = :dslogon_uuid
LOGINGOV_TYPE = :logingov_uuid
# Queries for a UserVerification on the user, based off the credential identifier
# If a UserVerification doesn't exist, create one and a UserAccount record associated
# with that UserVerification
def find_or_create_user_verification
if identifier.nil?
Rails.logger.info("[Login::UserVerifier] Nil identifier for type=#{type}")
attempt_secondary_idme_identifier
end
ActiveRecord::Base.transaction do
if user_verification
update_existing_user_verification if user_verification_needs_to_be_updated?
update_backing_idme_uuid if backing_idme_uuid_has_changed?
update_credential_attributes_digest if credential_attributes_digest_changed?
else
create_user_verification
end
end
post_transaction_message_logs
user_verification
end
def update_existing_user_verification
if existing_user_account
if user_verification.verified?
@user_account_mismatch_log = '[Login::UserVerifier] User Account Mismatch for ' \
"UserVerification id=#{user_verification.id}, " \
"UserAccount id=#{user_verification.user_account.id}, " \
"icn=#{user_verification.user_account.icn}, conflicts with " \
"UserAccount id=#{existing_user_account.id} " \
"icn=#{existing_user_account.icn} " \
"Setting UserVerification id=#{user_verification.id} " \
"association to UserAccount id=#{existing_user_account.id}"
user_verification.update(user_account: existing_user_account)
else
deprecate_unverified_user_account
end
else
update_newly_verified_user
end
end
def update_backing_idme_uuid
user_verification.update(backing_idme_uuid:)
end
def update_credential_attributes_digest
return unless user_verification.verified?
user_verification.update(credential_attributes_digest:)
end
def deprecate_unverified_user_account
deprecated_user_account = user_verification.user_account
DeprecatedUserAccount.create!(user_account: deprecated_user_account,
user_verification:)
user_verification.update(user_account: existing_user_account, verified_at: Time.zone.now)
set_deprecated_log(deprecated_user_account.id, user_verification.id, existing_user_account.id)
end
def update_newly_verified_user
user_verification_account = user_verification.user_account
user_verification.update(verified_at: Time.zone.now)
user_verification_account.update(icn:)
end
def create_user_verification
set_new_user_log
verified_at = icn ? Time.zone.now : nil
credential_attributes_digest = nil unless icn
UserVerification.create!(type => identifier,
user_account: existing_user_account || UserAccount.new(icn:),
backing_idme_uuid:,
verified_at:,
locked:,
credential_attributes_digest:)
end
def user_verification_needs_to_be_updated?
icn.present? && user_verification.user_account != existing_user_account
end
def backing_idme_uuid_has_changed?
backing_idme_uuid != user_verification.backing_idme_uuid
end
def credential_attributes_digest_changed?
credential_attributes_digest != user_verification.credential_attributes_digest
end
def set_new_user_log
@new_user_log = '[Login::UserVerifier] New VA.gov user, ' \
"type=#{login_type}, broker=#{auth_broker}, identifier=#{identifier}, locked=#{locked}"
end
def post_transaction_message_logs
Rails.logger.info(deprecated_log) if deprecated_log
Rails.logger.info(user_account_mismatch_log) if user_account_mismatch_log
Rails.logger.info(new_user_log, { icn: }) if new_user_log
end
def set_deprecated_log(deprecated_user_account_id, user_verification_id, user_account_id)
@deprecated_log = "[Login::UserVerifier] Deprecating UserAccount id=#{deprecated_user_account_id}, " \
"Updating UserVerification id=#{user_verification_id} with UserAccount id=#{user_account_id}"
end
# ID.me uuid has historically been a primary identifier, even for non-ID.me credentials.
# For now it is still worth attempting to use it as a backup identifier
def attempt_secondary_idme_identifier
@type = :idme_uuid
@identifier = idme_uuid
raise Errors::UserVerificationNotCreatedError if identifier.nil?
Rails.logger.info("[Login::UserVerifier] Attempting alternate type=#{type} identifier=#{identifier}")
end
def locked
return false unless existing_user_account
@locked ||= existing_user_account.user_verifications.send(login_type).where(locked: true).present?
end
def existing_user_account
@existing_user_account ||= icn ? UserAccount.find_by(icn:) : nil
end
def user_verification
@user_verification ||= identifier ? UserVerification.find_by(type => identifier) : nil
end
def backing_idme_uuid
@backing_idme_uuid ||= type_with_backing_idme_uuid ? idme_uuid : nil
end
def type_with_backing_idme_uuid
[MHV_TYPE, DSLOGON_TYPE].include?(type)
end
def type
@type ||= case login_type
when SAML::User::MHV_ORIGINAL_CSID
MHV_TYPE
when SAML::User::IDME_CSID
IDME_TYPE
when SAML::User::DSLOGON_CSID
DSLOGON_TYPE
when SAML::User::LOGINGOV_CSID
LOGINGOV_TYPE
end
end
def identifier
@identifier ||= case type
when MHV_TYPE
mhv_uuid
when IDME_TYPE
idme_uuid
when DSLOGON_TYPE
dslogon_uuid
when LOGINGOV_TYPE
logingov_uuid
end
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/login/user_acceptable_verified_credential_updater.rb
|
# frozen_string_literal: true
module Login
class UserAcceptableVerifiedCredentialUpdater
def initialize(user_account:)
@user_account = user_account
end
def perform
return unless user_account&.verified?
update_user_acceptable_verified_credential
end
private
attr_reader :user_account
def update_user_acceptable_verified_credential
user_avc = UserAcceptableVerifiedCredential.find_or_initialize_by(user_account:)
user_avc.idme_verified_credential_at ||= Time.zone.now if idme_credential.present?
user_avc.acceptable_verified_credential_at ||= Time.zone.now if logingov_credential.present?
if user_avc.changed?
user_avc.save!
Login::UserAcceptableVerifiedCredentialUpdaterLogger.new(user_acceptable_verified_credential: user_avc).perform
end
end
def idme_credential
@idme_credential ||= user_verifications_array.where.not(idme_uuid: nil).first
end
def logingov_credential
@logingov_credential ||= user_verifications_array.where.not(logingov_uuid: nil).first
end
def user_verifications_array
@user_verifications_array ||= user_account.user_verifications
end
end
end
|
0
|
code_files/vets-api-private/app/services
|
code_files/vets-api-private/app/services/user_audit/logger.rb
|
# frozen_string_literal: true
module UserAudit
class Logger < SemanticLogger::Logger
def initialize
super('UserAudit', 'info', /UserAudit/)
end
UserAction.statuses.each_key do |status|
define_method(status) do |*args, **kwargs|
kwargs[:status] = status
info(*args, **kwargs)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/user_audit
|
code_files/vets-api-private/app/services/user_audit/appenders/base.rb
|
# frozen_string_literal: true
module UserAudit
module Appenders
class Base < SemanticLogger::Subscriber
REQUIRED_PAYLOAD_KEYS = %i[status event user_verification].freeze
def initialize(filter: /UserAudit/, level: :info, **args, &)
super(filter:, level:, **args, &)
end
def log(log)
@payload = log.payload
@tags = log.named_tags
@log_time = log.time || Time.zone.now
append_log
true
rescue => e
log_error('Error appending log', e, log)
false
end
def should_log?(log)
super(log) && valid_log?(log)
rescue => e
log_error('Error validating log', e, log)
false
end
private
attr_reader :payload, :tags, :log_time
def append_log
raise NotImplementedError, 'Subclasses must implement #append_log'
end
def valid_log?(log)
missing_keys = REQUIRED_PAYLOAD_KEYS - log.payload.compact_blank.keys
return true if missing_keys.empty?
log_error("Missing required log payload keys: #{missing_keys.join(', ')}", nil, log)
false
end
def user_action_event
@user_action_event = UserActionEvent.find_by!(identifier: payload[:event])
end
def acting_user_verification
@acting_user_verification = payload[:acting_user_verification] || subject_user_verification
end
def subject_user_verification
@subject_user_verification = payload[:user_verification]
end
def status
@status = payload[:status]
end
def acting_ip_address
@acting_ip_address = tags[:remote_ip]
end
def acting_user_agent
@acting_user_agent = tags[:user_agent]
end
def log_success(message, **log_payload)
Rails.logger.info("[UserAudit][Logger] success: #{message}", log_payload)
end
def log_error(message, exception, log)
Rails.logger.info(
"[UserAudit][Logger] error: #{message}",
audit_log: { log_payload: mask_payload(log.payload), log_tags: log.named_tags },
error_message: exception&.message,
appender: self.class.name
)
end
def mask_payload(payload)
payload.each_with_object({}) do |(key, value), hash|
if value.respond_to?(:id)
id_key = :"#{key}_id"
hash[id_key] = value.id
else
hash[key] = value
end
end
end
def default_formatter
SemanticLogger::Formatters::Json.new
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/user_audit
|
code_files/vets-api-private/app/services/user_audit/appenders/user_action_appender.rb
|
# frozen_string_literal: true
module UserAudit
module Appenders
class UserActionAppender < Base
private
def append_log
user_action = UserAction.create!(
user_action_event:,
acting_user_verification:,
subject_user_verification:,
status:,
acting_ip_address:,
acting_user_agent:
)
log_success('UserAction created', event_id: user_action_event.id,
event_description: user_action_event.details,
status:,
user_action: user_action.id)
end
end
end
end
|
0
|
code_files/vets-api-private/app/services/user_audit
|
code_files/vets-api-private/app/services/user_audit/appenders/audit_log_appender.rb
|
# frozen_string_literal: true
module UserAudit
module Appenders
class AuditLogAppender < Base
private
def append_log
audit_log = Audit::Log.create!(
subject_user_identifier:,
subject_user_identifier_type:,
acting_user_identifier:,
acting_user_identifier_type:,
event_id: user_action_event.identifier,
event_description: user_action_event.details,
event_status: status,
event_occurred_at: log_time,
message:
)
log_success('AuditLog created', event_id: user_action_event.id,
event_description: user_action_event.details,
status:,
audit_log: audit_log.id)
end
def subject_user_identifier
@subject_user_identifier = identifier_for(subject_user_account, subject_user_verification)
end
def acting_user_identifier
@acting_user_identifier = if acting_user_verification == subject_user_verification
subject_user_identifier
else
identifier_for(acting_user_account, acting_user_verification)
end
end
def subject_user_identifier_type
@subject_user_identifier_type = identifier_type_for(subject_user_account, subject_user_verification)
end
def acting_user_identifier_type
@acting_user_identifier_type = if acting_user_verification == subject_user_verification
subject_user_identifier_type
else
identifier_type_for(acting_user_account, acting_user_verification)
end
end
def message
mask_payload(payload).merge({ acting_ip_address:, acting_user_agent: })
end
def acting_user_account
@acting_user_account = acting_user_verification.user_account
end
def subject_user_account
@subject_user_account = subject_user_verification.user_account
end
def identifier_type_for(user_account, user_verification)
return 'icn' if user_account.icn.present?
case user_verification.credential_type
when SAML::User::IDME_CSID then 'idme_uuid'
when SAML::User::LOGINGOV_CSID then 'logingov_uuid'
when SAML::User::MHV_ORIGINAL_CSID then 'mhv_id'
when SAML::User::DSLOGON_CSID then 'dslogon_id'
end
end
def identifier_for(user_account, user_verification)
user_account.icn || user_verification.credential_identifier
end
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/concerns/retriable_concern.rb
|
# frozen_string_literal: true
require 'retriable'
module RetriableConcern
extend ActiveSupport::Concern
def with_retries(block_name, tries: 3, base_interval: 1, &block)
attempts = 0
result = Retriable.retriable(tries:, base_interval:) do |attempt|
attempts = attempt
Rails.logger.warn("Retrying #{block_name} (Attempt #{attempts}/#{tries})") if attempts > 1
block.call
end
Rails.logger.info("#{block_name} succeeded on attempt #{attempts}/#{tries}") if attempts > 1
result
rescue => e
Rails.logger.error("#{block_name} failed after max retries", error: e.message, backtrace: e.backtrace)
raise
end
end
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/prod
|
#!/usr/bin/env bash
# bin/prod - Run Vets API in production mode locally
# Usage: bin/prod [command]
#
# If no command is provided, defaults to 'rails server -e production'
# Examples:
# bin/prod # Starts the rails server in production mode
# bin/prod console # Starts the rails console in production mode
# bin/prod -h # Shows this help message
set -e
# Display help if requested
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
echo "Usage: bin/prod [command]"
echo ""
echo "Runs the Vets API in RAILS_ENV=production mode locally with all necessary"
echo "environment variables pre-configured."
echo ""
echo "If no command is provided, defaults to 'rails server'"
echo ""
echo "Examples:"
echo " bin/prod # Starts the rails server in production mode"
echo " bin/prod console # Starts the rails console in production mode"
echo " bin/prod runner 'puts Rails.env' # Run a Rails runner command in production mode"
echo " bin/prod -h # Shows this help message"
exit 0
fi
# Check for existing secret key or generate a new one
SECRET_FILE="tmp/local_secret.txt"
if [[ -f "$SECRET_FILE" ]]; then
SECRET_KEY=$(cat "$SECRET_FILE")
else
# Generate and save a new secret key
SECRET_KEY=$(rails secret)
mkdir -p tmp
echo "$SECRET_KEY" > "$SECRET_FILE"
echo "Generated new secret key in $SECRET_FILE"
fi
# Determine the command to run
if [[ $# -eq 0 ]]; then
# No arguments provided, default to server
COMMAND="server"
else
# Use the provided arguments
COMMAND="$*"
fi
# ID.me credentials from config files:
# - client_id from config/identity_settings/settings.yml
# - client_secret from config/identity_settings/environments/development.yml
# Run the Rails command with all the necessary environment variables
APPLICATION_ENV=production \
RAILS_ENV=production \
RAILS_LOCAL_STORAGE=true \
identity_settings__sign_in__jwt_encode_key="spec/fixtures/sign_in/privatekey.pem" \
identity_settings__sign_in__jwt_old_encode_key="spec/fixtures/sign_in/privatekey_old.pem" \
identity_settings__sign_in__sts_client__key_path="spec/fixtures/sign_in/sts_client.pem" \
identity_settings__idme__client_id="ef7f1237ed3c396e4b4a2b04b608a7b1" \
identity_settings__idme__client_secret="ae657fd2b253d17be7b48ecdb39d7b34" \
identity_settings__idme__client_cert_path="spec/fixtures/sign_in/oauth.crt" \
identity_settings__idme__client_key_path="spec/fixtures/sign_in/oauth.key" \
identity_settings__idme__redirect_uri="http://localhost:3000/v0/sign_in/callback" \
identity_settings__idme__oauth_url="https://api.idmelabs.com" \
identity_settings__mvi__client_cert_path="spec/support/certificates/ruby-saml.crt" \
identity_settings__mvi__client_key_path="spec/support/certificates/ruby-saml.key" \
identity_settings__mvi__mock=true \
identity_settings__mvi__processing_code="T" \
identity_settings__mvi__url="http://mvi.example.com/psim_webservice/IdMWebService" \
hostname="localhost:3000" \
vsp_environment="localhost" \
vet360__contact_information__mock=true \
vet360__military_personnel__mock=true \
vet360__profile_information__use_mocks=true \
vet360__veteran_status__mock=true \
CONSIDER_ALL_REQUESTS_LOCAL=true \
DEBUG_EXCEPTIONS=true \
LOG_LEVEL=debug \
BACKTRACE=1 \
RAILS_LOG_TO_STDOUT=true \
breakers_disabled=true \
evss__aws__region="us-gov-west-1" \
evss__s3__bucket="evss_s3_bucket" \
mhv__account_creation__host="https://mhv-api.example.com" \
mhv__rx__host="https://mhv-api.example.com" \
mhv__sm__host="https://mhv-api.example.com" \
mhv__bb__mock=true \
mpi__mock=true \
central_mail__upload__enabled=false \
va_mobile__mock=true \
va_mobile__url="https://veteran.apps-staging.va.gov" \
va_mobile__key_path="spec/support/certificates/ruby-saml.key" \
va_mobile__timeout=55 \
caseflow__host="https://caseflow.example.com" \
caseflow__mock=true \
preneeds__host="https://preneeds.example.com" \
decision_review__url="https://decision-review.example.com" \
decision_review__mock=true \
dmc__url="https://dmc.example.com" \
dmc__mock_debts=true \
dmc__mock_fsr=true \
gibft__mock=true \
gi__version="v0" \
gi__url="https://gi.example.com" \
hca__mock=true \
hca__endpoint="https://vaww.esrprod.aac.va.gov/voa/voaSvc" \
hca__timeout=30 \
rx__mock=true \
sm__mock=true \
search__mock_search=true \
search__url="https://search.example.com" \
search_gsa__mock_search=true \
search_gsa__url="https://search-gsa.example.com" \
search_typeahead__url="https://search-typeahead.example.com" \
search_click_tracking__url="https://search-click-tracking.example.com" \
mdot__url="https://mdot.va.gov/api" \
mdot__mock=true \
mdot__timeout=30 \
iam_ssoe__oauth_url="https://dev.sqa.eauth.va.gov/oauthv2" \
iam_ssoe__client_cert_path="spec/support/certificates/ruby-saml.crt" \
iam_ssoe__client_key_path="spec/support/certificates/ruby-saml.key" \
iam_ssoe__timeout=15 \
vetext_push__base_url="https://vetext.example.com" \
vetext_push__user="user" \
vetext_push__pass="pass" \
vetext_push__va_mobile_app_sid="sid1234" \
vetext_push__va_mobile_app_debug_sid="debugsid1234" \
maintenance__pagerduty_api_url="https://api.pagerduty.com" \
bgs__url="https://bgs.example.com" \
bgs__ssl_verify_mode="none" \
bgs__mock_responses=true \
claims_api__bgs__mock_responses=true \
betamocks__enabled=true \
betamocks__cache_dir="../vets-api-mockdata" \
secret_key_base="$SECRET_KEY" \
maintenance__service_query_prefix=foo \
lockbox__master_key=0d78eaf0e90d4e7b8910c9112e16e66d8b00ec4054a89aa426e32712a13371e9 \
SETTINGS__DATABASE_URL="postgis://localhost/vets-api" \
SETTINGS__TEST_DATABASE_URL="postgis://postgres@localhost:5432/vets_api_test" \
web_origin="localhost" \
sign_in__web_origins=localhost \
old_secret_key_base=abc123 \
bin/rails $COMMAND -e production
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/lint
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'lib/vets-api/commands/lint'
require 'rake'
VALID_OPTIONS = ['--dry', '--only-rubocop', '--only-brakeman'].freeze
def help_message
puts <<~HELP
Usage:
bin/lint [options] [files|folders]
Options:
--help, -h Display help message for 'setup'
--dry Run the cops without autocorrect
--only-rubocop Only runs Rubocop
--only-brakeman Only runs Brakeman
Examples:
bin/lint
bin/lint --dry --only-rubocop
bin/lint lib/forms/client.rb
Notes:
bin/lint runs both Rubocop and Brakeman. Rubocop safe autocorrect is ON by default
HELP
end
# rubocop:disable Rails/NegateInclude
invalid_options = ARGV.select { |o| o.start_with?('--', '-') && !VALID_OPTIONS.include?(o) }
# rubocop:enable Rails/NegateInclude
if ARGV.include?('--help') || ARGV.include?('-h')
help_message
elsif invalid_options.empty?
VetsApi::Commands::Lint.run(ARGV)
else
puts "Invalid option(s) found: #{invalid_options.join(', ')}."
help_message
end
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/docker
|
#!/usr/bin/env sh
# Function to display the help message
display_help() {
echo "Usage: bin/docker [COMMAND]"
echo
echo "Commands:"
echo " clean Prunes unused Docker objects and rebuilds the images"
echo " rebuild Stops running containers and builds the images without cache"
echo " build Stops running containers and builds the images with cache"
echo " stop Stops all running Docker containers"
echo " startd Start Docker containers in the background"
echo " console Starts the Rails console"
echo " bundle Bundles ruby gems"
echo " db Prepares the database for development and test environments"
echo " ci Prepare docker environment to run bin/test --ci"
echo " help Display this help message"
echo
echo "Examples:"
echo " bin/docker clean Prune and rebuild Docker images"
echo " bin/docker build Stop and build Docker images without cache"
echo " bin/docker stop Stop all running Docker containers"
echo " bin/docker startd Start Docker containers in the background"
echo " bin/docker console Start the Rails console"
echo " bin/docker bundle Bundles ruby gems"
echo " bin/docker db Prepares the database for development and test environments"
echo " bin/docker ci Prepare docker environment to run bin/test --ci"
echo " bin/docker help Display this help message"
exit 0
}
clean() {
echo "Pruning unused Docker objects..."
docker system prune -f -a
echo "Rebuilding Docker images..."
docker compose build --no-cache
echo "Clean and rebuild completed."
}
rebuild() {
stop
echo "Building Docker images without cache..."
docker compose build --no-cache
echo "Build completed."
}
build() {
stop
echo "Building Docker images with cache..."
docker compose build
echo "Build completed."
}
stop() {
echo "Stopping all running Docker containers..."
docker compose down
echo "All Docker containers stopped."
}
startd() {
echo "Starting Docker containers..."
docker compose up -d
echo "Docker containers started."
}
console() {
echo "Starting Rails console..."
docker compose run --rm --service-ports web bash -c "bundle exec rails console"
}
bundle() {
echo "Bundling ruby gems..."
docker compose run --rm --service-ports web bash -c "bundle install"
}
db() {
echo "Running 'rails db:prepare'..."
docker compose run --rm --service-ports web bash -c "bundle exec rails db:prepare"
db_prepare_parallel
}
db_prepare_parallel() {
echo "Running 'parallel_test rails db:prepare'..."
docker compose run --rm --service-ports web bash -c "RAILS_ENV=test DISABLE_BOOTSNAP=true bundle exec parallel_test -e 'bundle exec rails db:prepare'"
}
ci() {
echo "Setting up for bin/test --ci compatibility..."
stop
build
bundle
db_prepare_parallel
}
case "$1" in
clean | rebuild | build | stop | startd | console | bundle | db | ci)
"$1"
;;
*)
display_help
;;
esac
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/test
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'lib/vets-api/commands/test'
require 'rake'
VALID_OPTIONS = ['--parallel', '--coverage', '--log'].freeze
# rubocop:disable Metrics/MethodLength
def help_message
puts <<~HELP
Usage:
bin/test [options] [files|folders]
Options:
--help, -h Display help message for 'setup'
--ci Run the tests exactly like the CI (requires docker to be setup)
--parallel Run the tests in parallel
--coverage Include test coverage report
--log Output pending/failures to log/rspec.log instead of STDOUT
Examples:
bin/test spec modules
bin/test --parallel spec/models/account_spec.rb
bin/test spec/models/account_spec.rb
bin/test --parallel --log spec/models/account_spec.rb
bin/test --ci
Defaults:
- Only run tests in './spec' folder
- No parallel
- No coverage or log
Notes:
If you are running the full suite, it's recommended to run with `--log`
to more easily see the pending and failing examples
HELP
end
# rubocop:enable Metrics/MethodLength
def ci_test_command
docker = 'docker compose run web bash -c'
runtime_variables = 'CI=true RAILS_ENV=test DISABLE_BOOTSNAP=true'
spec = "bundle exec parallel_rspec spec/ modules/ -n 8 -o '--color --tty'"
"#{docker} \"#{runtime_variables} #{spec}\""
end
# rubocop:disable Rails/NegateInclude
invalid_options = ARGV.select { |o| o.start_with?('--', '-') && !VALID_OPTIONS.include?(o) }
# rubocop:enable Rails/NegateInclude
if ARGV.include?('--help') || ARGV.include?('-h')
help_message
elsif ARGV.include?('--ci')
puts 'WARNING: --ci ignores all other options and inputs'
puts "running: #{ci_test_command}"
system(ci_test_command)
elsif invalid_options.empty?
VetsApi::Commands::Test.run(ARGV)
else
puts "Invalid option(s) found: #{invalid_options.join(', ')}"
help_message
end
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/merge_imagemagick_policy
|
require 'nokogiri'
original_policy_path = '/etc/ImageMagick-6/policy.xml'
new_policy_path = '/app/config/imagemagick/policies/new-policy.xml'
policy1 = Nokogiri::XML(File.read(original_policy_path)) { |config| config.default_xml.noblanks }
policy2 = Nokogiri::XML(File.read(new_policy_path)) { |config| config.default_xml.noblanks }
policy2.xpath('//policy').each do |policy|
policy1.root.add_child(policy)
end
File.write(original_policy_path, policy1.to_xml(indent: 2))
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/git_blame
|
#!/bin/bash
echo "| Filename | Author 1 | Author 2 | Author 3 | Timestamp 1 | Timestamp 2 | Timestamp 3 |" > git_blame_report.md
echo "|----------|----------|----------|----------|-------------|-------------|-------------|" >> git_blame_report.md
for filename in $(git ls-files)
do
# Extract the three most recent authors and timestamps
authors=($(git log -3 --pretty=format:'%an' -- "$filename"))
timestamps=($(git log -3 --pretty=format:'%cd' -- "$filename"))
# Assign the authors and timestamps to variables
author1=${authors[0]:-''}
author2=${authors[1]:-''}
author3=${authors[2]:-''}
timestamp1=${timestamps[0]:-''}
timestamp2=${timestamps[1]:-''}
timestamp3=${timestamps[2]:-''}
# Append the information to the markdown file
echo "| $filename | $author1 | $author2 | $author3 | $timestamp1 | $timestamp2 | $timestamp3 |" >> git_blame_report.md
done
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/rake
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative '../config/boot'
require 'rake'
Rake.application.run
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/setup
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'lib/vets-api/commands/setup'
require 'rake'
def help_message
puts <<~HELP
** A setup (.e.g., native) is required and must be the first argument **
Usage:
bin/setup [setup]
Options:
--help, -h Display help message for 'setup'
Setups:
native Setup native developer environment
docker Setup Docker developer environment
hybrid Setup hybrid developer environment
base Setup local settings and Sidekiq Enterprise
Examples:
bin/setup --help Show help message
bin/setup docker Setup Docker developer environment
bin/setup base This is useful for those running Linux or Windows
HELP
end
option = ARGV.first
if ARGV.include?('--help') || ARGV.include?('-h')
help_message
elsif %w[native docker hybrid base].include?(option)
VetsApi::Commands::Setup.run(ARGV)
else
puts "Invalid setup option \"#{option || 'NULL'}\""
help_message
end
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/local-openresty
|
#!/usr/bin/env bash
# bin/local-openresty - Boot an OpenResty container as a reverse proxy for Vets API
#
# Usage:
# bin/local-openresty [options]
#
# Options:
# --port PORT Host port to bind OpenResty (default: 80)
# --traefik-port PORT Port where Traefik is running (default: 8081)
# --version VER OpenResty version to use (default: 1.25.3.1-0-jammy)
# -h, --help Display this help message
#
# This script creates a local reverse proxy using OpenResty that forwards
# traffic to Vets API running on localhost:3000, either directly or through
# Traefik if detected.
set -e
# Default values
PORT=80
TRAEFIK_PORT=8081
VERSION="1.25.3.1-0-jammy"
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--port)
PORT="$2"
shift 2
;;
--traefik-port)
TRAEFIK_PORT="$2"
shift 2
;;
--version)
VERSION="$2"
shift 2
;;
-h|--help)
sed -n '/^#/!q;s/^#//;s/^ //;p' < "$0"
exit 0
;;
*)
echo "Error: Unknown option $1"
echo "Use -h or --help for usage information"
exit 1
;;
esac
done
# Configuration file path
OPENRESTY_CONF="tmp/openresty-local.conf"
# Verify directories exist
mkdir -p tmp
# Check if API is available
echo "Checking if Vets API is running on localhost:3000..."
if ! curl -s -o /dev/null http://localhost:3000; then
echo "Error: Vets API doesn't appear to be running on localhost:3000"
echo "Please start Vets API before running this script."
exit 1
fi
# Check if Traefik is running on the specified port
echo "Checking if Traefik is running on port $TRAEFIK_PORT..."
if curl -s -o /dev/null http://localhost:$TRAEFIK_PORT 2>/dev/null; then
USE_TRAEFIK=true
echo "Detected a service running on port $TRAEFIK_PORT, assuming Traefik"
else
USE_TRAEFIK=false
echo "No service detected on port $TRAEFIK_PORT, using direct mode"
fi
# Generate OpenResty config if it doesn't exist
if [ ! -f "$OPENRESTY_CONF" ]; then
echo "Generating OpenResty configuration at $OPENRESTY_CONF..."
# Determine target based on Traefik availability
if [ "$USE_TRAEFIK" = false ]; then
TARGET="127.0.0.1:3000"
echo "Using direct mode: proxying to Vets API directly"
else
TARGET="host.docker.internal:$TRAEFIK_PORT"
echo "Using Traefik mode: proxying to Vets API via Traefik on port $TRAEFIK_PORT"
fi
cat > "$OPENRESTY_CONF" << EOF
worker_processes auto;
error_log /dev/stderr info;
pid /tmp/nginx.pid;
events {
worker_connections 1024;
}
http {
access_log /dev/stdout combined;
upstream vets_api {
server $TARGET;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://vets_api;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
}
}
EOF
else
echo "Using existing OpenResty configuration at $OPENRESTY_CONF"
fi
# Print banner
echo "========================================================="
echo "π Starting OpenResty $VERSION as a reverse proxy"
echo "π Listening on port $PORT"
if [ "$USE_TRAEFIK" = false ]; then
echo "π Proxying directly to Vets API on port 3000"
else
echo "π Proxying to Vets API via Traefik on port $TRAEFIK_PORT"
fi
echo "π§ Using config from $OPENRESTY_CONF"
echo "========================================================="
# Run OpenResty container
docker run --rm \
-p "$PORT:80" \
-v "$(pwd)/$OPENRESTY_CONF:/usr/local/openresty/nginx/conf/nginx.conf:ro" \
--add-host=host.docker.internal:host-gateway \
--name vets-api-openresty \
openresty/openresty:$VERSION
|
0
|
code_files/vets-api-private
|
code_files/vets-api-private/bin/info
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative '../config/boot'
require_relative 'lib/vets-api/commands/info'
require 'rails'
if ARGV.include?('--help') || ARGV.include?('-h')
puts <<~HELP
Usage:
bin/info [option]
Options:
--help, -h Display help message for 'info'
Examples:
bin/info Show version information
HELP
else
VetsApi::Commands::Info.run
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.