index
int64
0
0
repo_id
stringclasses
829 values
file_path
stringlengths
34
254
content
stringlengths
6
5.38M
0
code_files
code_files/vets-api-private/.yardopts
--title "Vets API" --protected --private --verbose --no-cache --no-save --output-dir .yardoc/output --exclude /spec/ --exclude /swagger/ --exclude /db\/migrate/ --readme README.md --files CONTRIBUTING.md,LICENSE.md,SECURITY.md
0
code_files
code_files/vets-api-private/LICENSE.md
As a work of the United States Government, this project is in the public domain within the United States. Additionally, we waive copyright and related rights in the work worldwide through the CC0 1.0 Universal public domain dedication. ## CC0 1.0 Universal Summary This is a human-readable summary of the [Legal Code (read the full text)](https://creativecommons.org/publicdomain/zero/1.0/legalcode). ### No Copyright The person who associated a work with this deed has dedicated the work to the public domain by waiving all of his or her rights to the work worldwide under copyright law, including all related and neighboring rights, to the extent allowed by law. You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission. ### Other Information In no way are the patent or trademark rights of any person affected by CC0, nor are the rights that other persons may have in the work or in how the work is used, such as publicity or privacy rights. Unless expressly stated otherwise, the person who associated a work with this deed makes no warranties about the work, and disclaims liability for all uses of the work, to the fullest extent permitted by applicable law. When using or citing the work, you should not imply endorsement by the author or the affirmer.
0
code_files
code_files/vets-api-private/.rubocop_todo.yml
# This configuration was generated by # `rubocop --auto-gen-config --exclude-limit 100` # on 2024-09-12 18:15:53 UTC using RuboCop version 1.66.1. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. # Offense count: 70 # Configuration parameters: AllowedMethods. # AllowedMethods: enums Lint/ConstantDefinitionInBlock: Exclude: - 'app/policies/mhv_health_records_policy.rb' - 'app/policies/mhv_medical_records_policy.rb' - 'app/policies/mhv_prescriptions_policy.rb' - 'config/initializers/flipper.rb' - 'config/initializers/zcta.rb' - 'modules/va_forms/lib/tasks/va_forms.rake' - 'modules/vba_documents/lib/tasks/vba_documents_tasks.rake' - 'modules/vba_documents/spec/factories/upload_submissions.rb' - 'modules/vba_documents/spec/lib/multipart_parser_spec.rb' - 'modules/vba_documents/spec/mailers/unsuccessful_report_mailer_spec.rb' - 'rakelib/claims.rake' - 'rakelib/evss.rake' - 'rakelib/pension_burial.rake' - 'rakelib/vet360.rake' - 'spec/controllers/application_controller_spec.rb' - 'spec/lib/carma/models/base_spec.rb' - 'spec/lib/common/client/base_spec.rb' - 'spec/lib/common/client/concerns/monitoring_spec.rb' - 'spec/lib/common/client/configuration/base_spec.rb' - 'spec/lib/common/client/middleware/request/remove_cookies_spec.rb' - 'spec/lib/common/client/session_spec.rb' - 'spec/lib/common/exceptions/validation_errors_spec.rb' - 'spec/lib/evss/service_spec.rb' - 'spec/lib/generators/module_helper_spec.rb' - 'spec/lib/hca/enrollment_system_spec.rb' - 'spec/lib/sidekiq/error_tag_spec.rb' - 'spec/lib/sidekiq/retry_monitoring_spec.rb' - 'spec/lib/sidekiq_stats_instrumentation/client_middleware_spec.rb' - 'spec/lib/sidekiq_stats_instrumentation/server_middleware_spec.rb' - 'spec/lib/tasks/support/schema_camelizer_spec.rb' - 'spec/lib/vbs/requests/base_spec.rb' - 'spec/lib/webhooks/utilities_spec.rb' - 'spec/models/webhooks/utilities_spec.rb' - 'spec/requests/authentication/standard_authentication_spec.rb' - 'spec/sidekiq/process_file_job_spec.rb' - 'spec/uploaders/log_metrics_spec.rb' - 'spec/uploaders/uploader_virus_scan_spec.rb' - 'spec/uploaders/validate_pdf_spec.rb' # Offense count: 87 # Configuration parameters: AllowedParentClasses. Lint/MissingSuper: Exclude: - 'app/models/bgs_dependents/adult_child_attending_school.rb' - 'app/models/bgs_dependents/child.rb' - 'app/models/bgs_dependents/child_marriage.rb' - 'app/models/bgs_dependents/child_school.rb' - 'app/models/bgs_dependents/child_stopped_attending_school.rb' - 'app/models/bgs_dependents/child_student.rb' - 'app/models/bgs_dependents/death.rb' - 'app/models/bgs_dependents/divorce.rb' - 'app/models/bgs_dependents/marriage_history.rb' - 'app/models/bgs_dependents/relationship.rb' - 'app/models/bgs_dependents/spouse.rb' - 'app/models/bgs_dependents/step_child.rb' - 'app/models/bgs_dependents/veteran.rb' - 'app/sidekiq/evss/disability_compensation_form/form8940_document.rb' - 'lib/apps/client.rb' - 'lib/apps/responses/response.rb' - 'lib/bid/service.rb' - 'lib/carma/models/attachment.rb' - 'lib/carma/models/attachments.rb' - 'lib/carma/models/caregiver.rb' - 'lib/carma/models/metadata.rb' - 'lib/carma/models/submission.rb' - 'lib/carma/models/veteran.rb' - 'lib/caseflow/responses/caseflow.rb' - 'lib/common/exceptions/ambiguous_request.rb' - 'lib/common/exceptions/backend_service_exception.rb' - 'lib/common/exceptions/detailed_schema_errors.rb' - 'lib/common/exceptions/filter_not_allowed.rb' - 'lib/common/exceptions/forbidden.rb' - 'lib/common/exceptions/internal_server_error.rb' - 'lib/common/exceptions/invalid_field.rb' - 'lib/common/exceptions/invalid_field_value.rb' - 'lib/common/exceptions/invalid_filters_syntax.rb' - 'lib/common/exceptions/invalid_pagination_params.rb' - 'lib/common/exceptions/invalid_resource.rb' - 'lib/common/exceptions/invalid_sort_criteria.rb' - 'lib/common/exceptions/message_authenticity_error.rb' - 'lib/common/exceptions/open_id_service_error.rb' - 'lib/common/exceptions/parameter_missing.rb' - 'lib/common/exceptions/parameters_missing.rb' - 'lib/common/exceptions/record_not_found.rb' - 'lib/common/exceptions/routing_error.rb' - 'lib/common/exceptions/schema_validation_errors.rb' - 'lib/common/exceptions/service_error.rb' - 'lib/common/exceptions/service_outage.rb' - 'lib/common/exceptions/token_validation_error.rb' - 'lib/common/exceptions/unauthorized.rb' - 'lib/common/exceptions/validation_errors.rb' - 'lib/debt_management_center/base_service.rb' - 'lib/evss/disability_compensation_form/service.rb' - 'lib/evss/service.rb' - 'lib/facilities/drivetime_bands/response.rb' - 'lib/forms/client.rb' - 'lib/forms/responses/response.rb' - 'lib/hca/service.rb' - 'lib/json_schema/json_api_missing_attribute.rb' - 'lib/json_schema/missing_schema.rb' - 'lib/lgy/service.rb' - 'lib/lighthouse/veterans_health/client.rb' - 'lib/mail_automation/client.rb' - 'lib/mdot/client.rb' - 'lib/mdot/response.rb' - 'lib/mpi/responses/add_parser.rb' - 'lib/mpi/responses/profile_parser.rb' - 'lib/saml/post_url_service.rb' - 'lib/search/service.rb' - 'lib/search_click_tracking/service.rb' - 'lib/search_gsa/service.rb' - 'lib/search_typeahead/service.rb' - 'lib/token_validation/v2/client.rb' - 'lib/va_profile/address_validation/v3/service.rb' - 'lib/va_profile/service.rb' - 'lib/vbs/requests/list_statements.rb' - 'lib/vic/id_card_attribute_error.rb' - 'modules/appeals_api/lib/appeals_api/form_schemas.rb' - 'modules/appeals_api/lib/appeals_api/token_validation_client.rb' - 'modules/claims_api/config/initializers/okcomputer.rb' - 'modules/meb_api/lib/dgi/service.rb' - 'modules/mobile/app/services/mobile/v0/lighthouse_health/service.rb' - 'modules/va_notify/lib/va_notify/service.rb' - 'modules/vaos/app/services/vaos/session_service.rb' - 'modules/veteran/app/models/veteran/user.rb' - 'lib/vye/dgib/service.rb' # Offense count: 1074 # Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. Metrics/AbcSize: Max: 90 # Offense count: 60 # Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns, inherit_mode. # AllowedMethods: refine Metrics/BlockLength: Max: 83 # Offense count: 244 # Configuration parameters: AllowedMethods, AllowedPatterns. Metrics/CyclomaticComplexity: Max: 29 # Offense count: 181 # Configuration parameters: AllowedMethods, AllowedPatterns. Metrics/PerceivedComplexity: Max: 29 # Offense count: 286 Naming/AccessorMethodName: Enabled: false # Offense count: 250 # Configuration parameters: EnforcedStyle, CheckMethodNames, CheckSymbols, AllowedIdentifiers, AllowedPatterns. # SupportedStyles: snake_case, normalcase, non_integer # AllowedIdentifiers: capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339, x86_64 Naming/VariableNumber: Exclude: - 'app/controllers/v1/supplemental_claims_controller.rb' - 'app/models/form526_submission.rb' - 'app/models/form_profiles/va_526ez.rb' - 'app/sidekiq/education_form/create_daily_spool_files.rb' - 'app/sidekiq/evss/disability_compensation_form/form8940_document.rb' - 'app/sidekiq/evss/disability_compensation_form/submit_form0781.rb' - 'app/swagger/swagger/schemas/gibct/institutions.rb' - 'app/swagger/swagger/v1/schemas/facilities.rb' - 'lib/bgs/form674.rb' - 'lib/evss/base_service.rb' - 'lib/evss/configuration.rb' - 'lib/hca/enrollment_system.rb' - 'lib/mpi/messages/add_person_implicit_search_message.rb' - 'lib/mpi/messages/add_person_proxy_add_message.rb' - 'lib/mpi/messages/update_profile_message.rb' - 'modules/appeals_api/app/models/appeals_api/appellant.rb' - 'modules/appeals_api/app/models/appeals_api/higher_level_review.rb' - 'modules/appeals_api/app/models/appeals_api/notice_of_disagreement.rb' - 'modules/appeals_api/app/services/appeals_api/pdf_construction/higher_level_review/v2/form_fields.rb' - 'modules/appeals_api/app/swagger/appeals_api/v1/nod_json_schema_swagger_helper.rb' - 'modules/appeals_api/spec/lib/decision_review_report_spec.rb' - 'modules/appeals_api/spec/services/appeals_api/central_mail_updater_spec.rb' - 'modules/claims_api/app/controllers/claims_api/v1/forms/disability_compensation_controller.rb' - 'modules/claims_api/app/controllers/claims_api/v1/forms/intent_to_file_controller.rb' - 'modules/claims_api/app/controllers/claims_api/v1/forms/power_of_attorney_controller.rb' - 'modules/claims_api/app/controllers/claims_api/v2/blueprints/claim_blueprint.rb' - 'modules/claims_api/app/controllers/claims_api/v2/veterans/claims_controller.rb' - 'modules/dhp_connected_devices/spec/lib/fitbit_client_spec.rb' - 'modules/meb_api/spec/dgi/submission/service_spec.rb' - 'modules/test_user_dashboard/app/models/test_user_dashboard/tud_account.rb' - 'modules/va_notify/spec/services/find_in_progress_forms_spec.rb' - 'modules/va_notify/spec/services/in_progress_form_reminder_spec.rb' - 'modules/va_notify/spec/sidekiq/in_progress_form_reminder_spec.rb' - 'modules/va_notify/spec/sidekiq/in_progress_forms_spec.rb' - 'modules/vaos/spec/services/middleware/vaos_errors_spec.rb' - 'modules/vba_documents/spec/factories/upload_submissions.rb' - 'modules/vba_documents/spec/models/upload_file_spec.rb' - 'modules/vba_documents/spec/sidekiq/upload_processor_spec.rb' - 'rakelib/login.rake' - 'spec/factories/dod_facilities.rb' - 'spec/factories/drivetime_band.rb' - 'spec/factories/education_benefits.rb' - 'spec/factories/education_benefits_claims.rb' - 'spec/factories/lighthouse/facilities/lighthouse_facility.rb' - 'spec/factories/nca_facilities.rb' - 'spec/factories/vba_facilities.rb' - 'spec/factories/vha_facilities.rb' - 'spec/lib/carma/models/attachments_spec.rb' - 'spec/lib/common/exceptions/validation_errors_spec.rb' - 'spec/lib/decision_review/schemas_spec.rb' - 'spec/lib/facilities/drivetime_bands/client_spec.rb' - 'spec/lib/facilities/gis/client_spec.rb' - 'spec/mailers/ch31_submissions_report_mailer_spec.rb' - 'spec/mailers/stem_applicant_denial_mailer_spec.rb' - 'spec/models/drivetime_band_spec.rb' - 'spec/models/facilities/vba_facility_spec.rb' - 'spec/models/facilities/vha_facility_spec.rb' - 'spec/models/form1010cg/submission_spec.rb' - 'spec/models/form1095_b_spec.rb' - 'spec/models/saved_claim/caregivers_assistance_claim_spec.rb' - 'spec/serializers/education_stem_claim_status_serializer_spec.rb' - 'spec/services/form1010cg/service_spec.rb' - 'spec/services/sign_in/revoke_sessions_for_user_spec.rb' - 'spec/sidekiq/education_form/create10203_applicant_decision_letters_spec.rb' - 'spec/sidekiq/education_form/create10203_spool_submissions_report_spec.rb' - 'spec/sidekiq/education_form/create_daily_spool_files_spec.rb' - 'spec/sidekiq/education_form/create_spool_submissions_report_spec.rb' - 'spec/sidekiq/education_form/delete_old_applications_spec.rb' - 'spec/sidekiq/education_form/forms/va1990_spec.rb' - 'spec/sidekiq/education_form/process10203_submissions_spec.rb' - 'spec/sidekiq/facilities/state_cemetery_reload_job_spec.rb' - 'spec/sidekiq/form1010cg/delete_old_uploads_job_spec.rb' # Offense count: 57 # Configuration parameters: AllowedPatterns. # AllowedPatterns: ^expect_, ^assert_ RSpec/NoExpectationExample: Exclude: - 'modules/appeals_api/spec/docs/decision_reviews/legacy_appeals_spec.rb' - 'modules/appeals_api/spec/docs/decision_reviews/notice_of_disagreements_spec.rb' - 'modules/appeals_api/spec/docs/decision_reviews/supplemental_claims_spec.rb' - 'modules/appeals_api/spec/support/doc_helpers.rb' - 'modules/claims_api/spec/sidekiq/poa_vbms_updater_spec.rb' - 'modules/va_forms/spec/requests/metadata_spec.rb' - 'spec/config/initializers/staccato_spec.rb' - 'spec/controllers/application_controller_spec.rb' - 'spec/controllers/v1/sessions_controller_spec.rb' - 'spec/lib/central_mail/service_spec.rb' - 'spec/lib/common/convert_to_pdf_spec.rb' - 'spec/lib/evss/vso_search/service_spec.rb' - 'spec/lib/hca/soap_parser_spec.rb' - 'spec/lib/pdf_fill/extras_generator_spec.rb' - 'spec/lib/pdf_fill/hash_converter_spec.rb' - 'spec/models/base_facility_spec.rb' - 'spec/models/education_benefits_claim_spec.rb' - 'spec/models/facilities_query_spec.rb' - 'spec/models/saved_claim/caregivers_assistance_claim_spec.rb' - 'spec/models/saved_claim/dependency_verification_claim_spec.rb' - 'spec/models/user_session_form_spec.rb' - 'spec/requests/swagger_spec.rb' - 'spec/requests/v1/apidoc/apidoc_spec.rb' - 'spec/sidekiq/education_form/process10203_submissions_spec.rb' - 'spec/sidekiq/education_form/send_school_certifying_officials_email_spec.rb' - 'spec/sidekiq/form1010cg/delete_old_uploads_job_spec.rb' - 'spec/sidekiq/pager_duty/poll_maintenance_windows_spec.rb' - 'spec/sidekiq/vre/create_ch31_submissions_report_job_spec.rb' # Offense count: 715 RSpec/StubbedMock: Enabled: false # Offense count: 26 RSpec/SubjectDeclaration: Exclude: - 'modules/va_notify/spec/models/veteran_spec.rb' - 'modules/vaos/spec/services/user_service_spec.rb' - 'modules/vba_documents/spec/sidekiq/run_unsuccessful_submissions_spec.rb' - 'spec/lib/carma/models/attachments_spec.rb' - 'spec/lib/okta/directory_service_spec.rb' - 'spec/lib/pagerduty/external_services/service_spec.rb' - 'spec/lib/pagerduty/maintenance_client_spec.rb' - 'spec/lib/preneeds/service_spec.rb' - 'spec/lib/slack/service_spec.rb' - 'spec/lib/vbs/requests/base_spec.rb' - 'spec/models/form1010cg/attachment_spec.rb' - 'spec/services/form1010cg/auditor_spec.rb' - 'spec/services/form1010cg/service_spec.rb' - 'spec/sidekiq/pager_duty/cache_global_downtime_spec.rb' - 'spec/uploaders/form1010cg/poa_uploader_spec.rb' # Offense count: 470 # This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: Inferences. RSpecRails/InferredSpecType: Enabled: false # Offense count: 14 Rails/I18nLocaleTexts: Exclude: - 'app/mailers/veteran_readiness_employment_mailer.rb' - 'app/models/async_transaction/base.rb' - 'app/models/message.rb' - 'lib/va_profile/models/communication_permission.rb' - 'lib/va_profile/models/preferred_name.rb' - 'modules/claims_api/app/mailers/claims_api/unsuccessful_report_mailer.rb' # Offense count: 2 # Configuration parameters: ForbiddenMethods, AllowedMethods. # ForbiddenMethods: decrement!, decrement_counter, increment!, increment_counter, insert, insert!, insert_all, insert_all!, toggle!, touch, touch_all, update_all, update_attribute, update_column, update_columns, update_counters, upsert, upsert_all Rails/SkipsModelValidations: Exclude: - 'spec/models/form526_job_status_spec.rb' - 'spec/sidekiq/evss/disability_compensation_form/submit_form526_all_claim_spec.rb' # Offense count: 3 # Configuration parameters: Include. # Include: app/models/**/*.rb Rails/UniqueValidationWithoutIndex: Exclude: - 'app/models/gibs_not_found_user.rb' - 'app/models/invalid_letter_address_edipi.rb' - 'modules/va_forms/app/models/va_forms/form.rb' # Offense count: 476 Style/OpenStructUse: Enabled: false # Offense count: 8 # Configuration parameters: AllowedMethods. # AllowedMethods: respond_to_missing? Style/OptionalBooleanParameter: Exclude: - 'app/controllers/v1/sessions_controller.rb' - 'app/sidekiq/education_form/forms/base.rb' - 'lib/common/models/redis_store.rb' - 'lib/evss/base_service.rb' - 'lib/pdf_fill/hash_converter.rb' - 'spec/support/authenticated_session_helper.rb' # Offense count: 60 ThreadSafety/ClassInstanceVariable: Exclude: - 'app/models/base_facility.rb' - 'app/models/concerns/redis_caching.rb' - 'app/models/form_profile.rb' - 'lib/common/client/base.rb' - 'lib/common/client/concerns/mhv_locked_session_client.rb' - 'lib/common/models/base.rb' - 'lib/common/models/collection.rb' - 'lib/common/models/redis_store.rb' - 'lib/shrine/plugins/storage_from_config.rb' - 'lib/va_profile/contact_information/person_response.rb' - 'lib/va_profile/contact_information/transaction_response.rb' - 'lib/vic/url_helper.rb' - 'modules/mobile/app/models/mobile/v0/concerns/redis_caching.rb'
0
code_files
code_files/vets-api-private/Guardfile
# frozen_string_literal: true guard :rspec, cmd: 'DISABLE_SPRING=y NOCOVERAGE=y bin/rspec' do require 'guard/rspec/dsl' dsl = Guard::RSpec::Dsl.new(self) watch(dsl.rspec.spec_helper) { dsl.rspec.spec_dir } watch(dsl.rspec.spec_support) { dsl.rspec.spec_dir } watch(dsl.rspec.spec_files) dsl.watch_spec_files_for(dsl.ruby.lib_files) dsl.watch_spec_files_for(dsl.rails.app_files) watch(dsl.rails.controllers) do |m| [dsl.rspec.spec.call("routing/#{m[1]}_routing"), dsl.rspec.spec.call("controllers/#{m[1]}_controller")] end watch(dsl.rails.spec_helper) { rspec.spec_dir } watch(dsl.rails.routes) { "#{rspec.spec_dir}/routing" } watch(dsl.rails.app_controller) { "#{rspec.spec_dir}/controllers" } end guard :rubocop, all_on_start: false, cli: %w[--auto-correct --format fuubar] do watch(/.+\.rb$/) watch(%r{(?:.+/)?\.rubocop\.yml$}) { |m| File.dirname(m[0]) } end
0
code_files
code_files/vets-api-private/.rubocop_explicit_enables.yml
Capybara/NegationMatcher: # new in 2.14 Enabled: true Capybara/SpecificActions: # new in 2.14 Enabled: true Capybara/SpecificFinders: # new in 2.13 Enabled: true Capybara/SpecificMatcher: # new in 2.12 Enabled: true Gemspec/DeprecatedAttributeAssignment: # new in 1.30 Enabled: true Gemspec/RequireMFA: # new in 1.23 Enabled: true Layout/LineContinuationSpacing: # new in 1.31 Enabled: true Layout/SpaceBeforeBrackets: # new in 1.7 Enabled: true Lint/AmbiguousAssignment: # new in 1.7 Enabled: true Lint/AmbiguousOperatorPrecedence: # new in 1.21 Enabled: true Lint/AmbiguousRange: # new in 1.19 Enabled: true Lint/ConstantOverwrittenInRescue: # new in 1.31 Enabled: true Lint/DeprecatedConstants: # new in 1.8 Enabled: true Lint/DuplicateBranch: # new in 1.3 Enabled: true Lint/DuplicateMagicComment: # new in 1.37 Enabled: true Lint/DuplicateRegexpCharacterClassElement: # new in 1.1 Enabled: true Lint/EmptyClass: # new in 1.3 Enabled: true Lint/EmptyInPattern: # new in 1.16 Enabled: true Lint/IncompatibleIoSelectWithFiberScheduler: # new in 1.21 Enabled: true Lint/LambdaWithoutLiteralBlock: # new in 1.8 Enabled: true Lint/NoReturnInBeginEndBlocks: # new in 1.2 Enabled: true Lint/NonAtomicFileOperation: # new in 1.31 Enabled: true Lint/NumberedParameterAssignment: # new in 1.9 Enabled: true Lint/OrAssignmentToConstant: # new in 1.9 Enabled: true Lint/RedundantDirGlobSort: # new in 1.8 Enabled: true Lint/RefinementImportMethods: # new in 1.27 Enabled: true Lint/RequireRangeParentheses: # new in 1.32 Enabled: true Lint/RequireRelativeSelfPath: # new in 1.22 Enabled: true Lint/SymbolConversion: # new in 1.9 Enabled: true Lint/ToEnumArguments: # new in 1.1 Enabled: true Lint/TripleQuotes: # new in 1.9 Enabled: true Lint/UnexpectedBlockArity: # new in 1.5 Enabled: true Lint/UnmodifiedReduceAccumulator: # new in 1.1 Enabled: true Lint/UselessRescue: # new in 1.43 Enabled: true Lint/UselessRuby2Keywords: # new in 1.23 Enabled: true Naming/BlockForwarding: # new in 1.24 Enabled: true Security/CompoundHash: # new in 1.28 Enabled: true Security/IoMethods: # new in 1.22 Enabled: true Style/ArgumentsForwarding: # new in 1.1 Enabled: true Style/ArrayIntersect: # new in 1.40 Enabled: true Style/CollectionCompact: # new in 1.2 Enabled: true Style/ConcatArrayLiterals: # new in 1.41 Enabled: true Style/DocumentDynamicEvalDefinition: # new in 1.1 Enabled: true Style/EmptyHeredoc: # new in 1.32 Enabled: true Style/EndlessMethod: # new in 1.8 Enabled: true Style/EnvHome: # new in 1.29 Enabled: true Style/FetchEnvVar: # new in 1.28 Enabled: true Style/FileRead: # new in 1.24 Enabled: true Style/FileWrite: # new in 1.24 Enabled: true Style/HashConversion: # new in 1.10 Enabled: true Style/HashExcept: # new in 1.7 Enabled: true Style/IfWithBooleanLiteralBranches: # new in 1.9 Enabled: true Style/InPatternThen: # new in 1.16 Enabled: true Style/MagicCommentFormat: # new in 1.35 Enabled: true Style/MapCompactWithConditionalBlock: # new in 1.30 Enabled: true Style/MapToHash: # new in 1.24 Enabled: true Style/MapToSet: # new in 1.42 Enabled: true Style/MinMaxComparison: # new in 1.42 Enabled: true Style/MultilineInPatternThen: # new in 1.16 Enabled: true Style/NegatedIfElseCondition: # new in 1.2 Enabled: true Style/NestedFileDirname: # new in 1.26 Enabled: true Style/NilLambda: # new in 1.3 Enabled: true Style/NumberedParameters: # new in 1.22 Enabled: true Style/NumberedParametersLimit: # new in 1.22 Enabled: true Style/ObjectThen: # new in 1.28 Enabled: true Style/OpenStructUse: # new in 1.23 Enabled: true Style/OperatorMethodCall: # new in 1.37 Enabled: true Style/QuotedSymbols: # new in 1.16 Enabled: true Style/RedundantArgument: # new in 1.4 Enabled: true Style/RedundantConstantBase: # new in 1.40 Enabled: true Style/RedundantDoubleSplatHashBraces: # new in 1.41 Enabled: true Style/RedundantEach: # new in 1.38 Enabled: true Style/RedundantInitialize: # new in 1.27 Enabled: true Style/RedundantSelfAssignmentBranch: # new in 1.19 Enabled: true Style/RedundantStringEscape: # new in 1.37 Enabled: true Style/SelectByRegexp: # new in 1.22 Enabled: true Style/StringChars: # new in 1.12 Enabled: true Style/SwapValues: # new in 1.1 Enabled: true Rails/ActionControllerFlashBeforeRender: # new in 2.16 Enabled: true Rails/ActionControllerTestCase: # new in 2.14 Enabled: true Rails/ActionOrder: # new in 2.17 Enabled: true Rails/ActiveRecordCallbacksOrder: # new in 2.7 Enabled: true Rails/ActiveSupportOnLoad: # new in 2.16 Enabled: true Rails/AddColumnIndex: # new in 2.11 Enabled: true Rails/AfterCommitOverride: # new in 2.8 Enabled: true Rails/AttributeDefaultBlockValue: # new in 2.9 Enabled: true Rails/CompactBlank: # new in 2.13 Enabled: true Rails/DeprecatedActiveModelErrorsMethods: # new in 2.14 Enabled: true Rails/DotSeparatedKeys: # new in 2.15 Enabled: true Rails/DuplicateAssociation: # new in 2.14 Enabled: true Rails/DuplicateScope: # new in 2.14 Enabled: true Rails/DurationArithmetic: # new in 2.13 Enabled: true Rails/EagerEvaluationLogMessage: # new in 2.11 Enabled: true Rails/ExpandedDateRange: # new in 2.11 Enabled: true Rails/FindById: # new in 2.7 Enabled: true Rails/FreezeTime: # new in 2.16 Enabled: true Rails/I18nLazyLookup: # new in 2.14 Enabled: true Rails/I18nLocaleAssignment: # new in 2.11 Enabled: true Rails/I18nLocaleTexts: # new in 2.14 Enabled: true Rails/IgnoredColumnsAssignment: # new in 2.17 Enabled: true Rails/Inquiry: # new in 2.7 Enabled: true Rails/MailerName: # new in 2.7 Enabled: true Rails/MatchRoute: # new in 2.7 Enabled: true Rails/MigrationClassName: # new in 2.14 Enabled: true Rails/NegateInclude: # new in 2.7 Enabled: true Rails/Pluck: # new in 2.7 Enabled: true Rails/PluckInWhere: # new in 2.7 Enabled: true Rails/RedundantPresenceValidationOnBelongsTo: # new in 2.13 Enabled: true Rails/RedundantTravelBack: # new in 2.12 Enabled: true Rails/RenderInline: # new in 2.7 Enabled: true Rails/RenderPlainText: # new in 2.7 Enabled: true Rails/RootJoinChain: # new in 2.13 Enabled: true Rails/RootPathnameMethods: # new in 2.16 Enabled: true Rails/RootPublicPath: # new in 2.15 Enabled: true Rails/ShortI18n: # new in 2.7 Enabled: true Rails/SquishedSQLHeredocs: # new in 2.8 Enabled: true Rails/StripHeredoc: # new in 2.15 Enabled: true Rails/TimeZoneAssignment: # new in 2.10 Enabled: true Rails/ToFormattedS: # new in 2.15 Enabled: true Rails/ToSWithArgument: # new in 2.16 Enabled: true Rails/TopLevelHashWithIndifferentAccess: # new in 2.16 Enabled: true Rails/TransactionExitStatement: # new in 2.14 Enabled: true Rails/UnusedIgnoredColumns: # new in 2.11 Enabled: true Rails/WhereEquals: # new in 2.9 Enabled: true Rails/WhereExists: # new in 2.7 Enabled: true Rails/WhereMissing: # new in 2.16 Enabled: true Rails/WhereNot: # new in 2.8 Enabled: true Rails/WhereNotWithMultipleConditions: # new in 2.17 Enabled: true RSpec/BeEq: # new in 2.9.0 Enabled: true RSpec/BeNil: # new in 2.9.0 Enabled: true RSpec/ChangeByZero: # new in 2.11 Enabled: true RSpec/ClassCheck: # new in 2.13 Enabled: true RSpec/DuplicatedMetadata: # new in 2.16 Enabled: true RSpec/ExcessiveDocstringSpacing: # new in 2.5 Enabled: true RSpec/IdenticalEqualityAssertion: # new in 2.4 Enabled: true RSpec/NoExpectationExample: # new in 2.13 Enabled: true RSpec/PendingWithoutReason: # new in 2.16 Enabled: true RSpec/SortMetadata: # new in 2.14 Enabled: true RSpec/SubjectDeclaration: # new in 2.5 Enabled: true RSpec/VerifiedDoubleReference: # new in 2.10.0 Enabled: true FactoryBot/ConsistentParenthesesStyle: # new in 2.14 Enabled: true FactoryBot/FactoryNameStyle: # new in 2.16 Enabled: true FactoryBot/SyntaxMethods: # new in 2.7 Enabled: true RSpecRails/AvoidSetupHook: # new in 2.4 Enabled: true RSpecRails/HaveHttpStatus: # new in 2.12 Enabled: true RSpecRails/InferredSpecType: # new in 2.14 Enabled: true Layout/EmptyLinesAroundAttributeAccessor: Enabled: true Layout/LineEndStringConcatenationIndentation: Enabled: true Layout/SpaceAroundMethodCallOperator: Enabled: true Lint/DeprecatedOpenSSLConstant: Enabled: true Lint/RaiseException: Enabled: true Lint/StructNewOverride: Enabled: true Style/ExponentialNotation: Enabled: true Style/HashEachMethods: Enabled: true Style/HashTransformKeys: Enabled: true Style/HashTransformValues: Enabled: true Style/SlicingWithRange: Enabled: true
0
code_files
code_files/vets-api-private/.rspec
--color --require spec_helper --format progress <% if ENV['CI'] %> --format RspecJunitFormatter --out log/rspec.xml <% end %>
0
code_files
code_files/vets-api-private/docker-compose-deps.yml
services: redis: image: redis:6.2-alpine ports: - "63790:6379" postgres: command: postgres -c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all -c max_connections=200 image: postgis/postgis:14-3.3-alpine environment: POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-password}" POSTGRES_USER: "${POSTGRES_USER:-postgres}" volumes: - ./data:/var/lib/postgresql/data:cached ports: - "54320:5432" clamav: volumes: - shared-vol:/vets-api image: clamav/clamav ports: - 33100:3310 platform: linux/amd64 volumes: shared-vol:
0
code_files
code_files/vets-api-private/.ruby-version
3.3.6
0
code_files
code_files/vets-api-private/mkdocs.yaml
site_name: "Vets API" site_description: "Documentation for Vets API deployment, setup, and history." repo_url: https://github.com/department-of-veterans-affairs/vets-api edit_uri: edit/master/docs/ nav: - Deployment: - Information: "deployment/information.md" - Setup: - Betamocks: "setup/betamocks.md" - Debugging with Docker RubyMine Windows: "setup/debugging_with_docker_rubymine_windows.md" - Developer Setup: - Hybrid Developer Setup: "setup/hybrid.md" - Native Developer Setup: "setup/native.md" - Docker: "setup/docker.md" - Education Benefits Year to Date Report: "setup/edu_benefits.md" - EVSS S3 Uploads: "setup/evss.md" - Facilities Locator Setup: "setup/facilities_locator.md" - Local Network Access: "setup/local_network_access.md" - Mailers Info: "setup/mailer.md" - MHV Prescriptions and MHV Secure Messaging Setup: "setup/mhv.md" - MPI Service: "setup/mpi.md" - Rswag setup for Rails engine: "setup/rswag_setup.md" - Running the App: - Running the app with Docker: "setup/running_docker.md" - Running the app Natively: "setup/running_natively.md" - Virtual Machine Access: "setup/virtual_machine_access.md" - History: "HISTORY.md" - APIs: "*include ./modules/*/mkdocs.yml" plugins: - techdocs-core - monorepo markdown_extensions: - pymdownx.snippets: check_paths: true
0
code_files
code_files/vets-api-private/Dockerfile
FROM public.ecr.aws/docker/library/ruby:3.3.6-slim-bookworm AS rubyimg FROM rubyimg AS modules WORKDIR /tmp # Copy each module's Gemfile, gemspec, and version.rb files COPY modules/ modules/ RUN find modules -type f ! \( -name Gemfile -o -name "*.gemspec" -o -path "*/lib/*/version.rb" \) -delete && \ find modules -type d -empty -delete FROM rubyimg # Allow for setting ENV vars via --build-arg ARG BUNDLE_ENTERPRISE__CONTRIBSYS__COM \ RAILS_ENV=development \ USER_ID=1000 ENV RAILS_ENV=$RAILS_ENV \ BUNDLE_ENTERPRISE__CONTRIBSYS__COM=$BUNDLE_ENTERPRISE__CONTRIBSYS__COM \ BUNDLER_VERSION=2.5.23 RUN groupadd --gid $USER_ID nonroot \ && useradd --uid $USER_ID --gid nonroot --shell /bin/bash --create-home nonroot --home-dir /app WORKDIR /app RUN apt-get update --fix-missing RUN apt-get install -y poppler-utils build-essential libpq-dev libffi-dev libyaml-dev git curl wget unzip ca-certificates ca-certificates-java openssl file \ imagemagick pdftk tesseract-ocr \ && apt-get clean \ && rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/* /tmp/* /var/tmp/* # Relax ImageMagick PDF security. See https://stackoverflow.com/a/59193253. RUN sed -i '/rights="none" pattern="PDF"/d' /etc/ImageMagick-6/policy.xml # Install fwdproxy.crt into trust store COPY config/ca-trust/*.crt /usr/local/share/ca-certificates/ # Update CA certificates before downloading VA certs RUN update-ca-certificates # Download VA Certs COPY ./import-va-certs.sh . RUN ./import-va-certs.sh COPY config/clamd.conf /etc/clamav/clamd.conf RUN mkdir -p /clamav_tmp && \ chown -R nonroot:nonroot /clamav_tmp && \ chmod 777 /clamav_tmp ENV LANG=C.UTF-8 \ BUNDLE_JOBS=4 \ BUNDLE_PATH=/usr/local/bundle/cache \ BUNDLE_RETRY=3 RUN gem install bundler:${BUNDLER_VERSION} --no-document COPY --from=modules /tmp/modules modules/ COPY Gemfile Gemfile.lock ./ RUN bundle install \ && rm -rf /usr/local/bundle/cache/*.gem \ && find /usr/local/bundle/gems/ -name "*.c" -delete \ && find /usr/local/bundle/gems/ -name "*.o" -delete \ && find /usr/local/bundle/gems/ -name ".git" -type d -prune -execdir rm -rf {} + \ # 🔧 fix bad permissions from Nokogiri 1.18.7 (only if installed) && for d in /usr/local/bundle/gems/nokogiri-*; do \ if [ -d "$d" ]; then \ find "$d" -type f -exec chmod a+r {} \; && \ find "$d" -type d -exec chmod a+rx {} \; ; \ fi \ done COPY --chown=nonroot:nonroot . . # Make the ImageMagick script executable RUN chmod +x bin/merge_imagemagick_policy # Execute the merge policy script for ImageMagick RUN ruby -rbundler/setup bin/merge_imagemagick_policy EXPOSE 3000 USER nonroot CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
0
code_files
code_files/vets-api-private/Makefile
$stdout.sync = true export VETS_API_USER_ID := $(shell id -u) ifdef env ENV_ARG := $(env) else ENV_ARG := dev endif ifdef clam FOREMAN_ARG := all=1 else FOREMAN_ARG := all=1,clamd=0,freshclam=0 endif COMPOSE_DEV := docker-compose COMPOSE_TEST := docker-compose -f docker-compose.test.yml BASH := run --rm --service-ports web bash BASH_DEV := $(COMPOSE_DEV) $(BASH) -c BASH_TEST := $(COMPOSE_TEST) $(BASH) --login -c SPEC_PATH := spec/ modules/ DB := "bin/rails db:setup db:migrate" LINT := "bin/rails lint['$(files)']" DOWN := down SECURITY := "bin/rails security" .DEFAULT_GOAL := ci # cribbed from https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html and https://news.ycombinator.com/item?id=11195539 help: ## Prints out documentation for available commands @awk -F ':|##' \ '/^[^\t].+?:.*?##/ {\ printf "\033[36m%-30s\033[0m %s\n", $$1, $$NF \ }' $(MAKEFILE_LIST) .PHONY: ci ci: ## Sets up databases and runs tests for ci @$(BASH_TEST) "bin/rails db:setup db:migrate ci" .PHONY: bash bash: ## Starts a bash shell inside the docker container @$(COMPOSE_DEV) $(BASH) .PHONY: build build: ## Builds the api ifeq ($(ENV_ARG), dev) $(COMPOSE_DEV) build else $(COMPOSE_TEST) build endif .PHONY: db db: ## Sets up database and runs migrations ifeq ($(ENV_ARG), dev) @$(BASH_DEV) $(DB) else @$(BASH_TEST) $(DB) endif .PHONY: lint lint: ## runs the linter ifeq ($(ENV_ARG), dev) @$(BASH_DEV) $(LINT) else @$(BASH_TEST) $(LINT) endif .PHONY: console console: ## Starts a rails console @$(BASH_DEV) "bundle exec rails c" .PHONY: danger danger: ## Runs the danger static analysis @$(BASH_TEST) "bundle exec danger --verbose" .PHONY: docker-clean docker-clean: ## Removes all docker images and volumes associated with vets-api @$(COMPOSE_DEV) down --rmi all --volumes .PHONY: down down: ## Stops all docker services ifeq ($(ENV_ARG), dev) @$(COMPOSE_DEV) $(DOWN) else @$(COMPOSE_TEST) $(DOWN) endif .PHONY: guard guard: ## Runs guard @$(BASH_DEV) "bundle exec guard" .PHONY: migrate migrate: ## Runs the database migrations @$(BASH_DEV) "bin/rails db:migrate" .PHONY: rebuild rebuild: down ## Stops the docker services and builds the api @$(COMPOSE_DEV) build .PHONY: security security: ## Runs security scans ifeq ($(ENV_ARG), dev) @$(BASH_DEV) $(SECURITY) else @$(BASH_TEST) $(SECURITY) endif .PHONY: server server: ## Starts the server (natively) @$(BASH_DEV) "rm -f tmp/pids/server.pid && bundle exec rails server" .PHONY: spec spec: ## Runs spec tests @$(BASH_DEV) "RAILS_ENV=test bin/rspec ${SPEC_PATH}" .PHONY: spec_parallel_setup spec_parallel_setup: ## Setup the parallel test dbs. This resets the current test db, as well as the parallel test dbs ifeq ($(ENV_ARG), dev) @$(BASH_DEV) "RAILS_ENV=test DISABLE_BOOTSNAP=true bundle exec parallel_test -e 'bundle exec rake db:reset db:migrate'" else @$(COMPOSE_TEST) $(BASH) -c "RAILS_ENV=test DISABLE_BOOTSNAP=true parallel_test -e 'bundle exec rake db:reset db:migrate'" endif .PHONY: spec_parallel spec_parallel: ## Runs spec tests in parallel ifeq ($(ENV_ARG), dev) @$(BASH_DEV) "RAILS_ENV=test DISABLE_BOOTSNAP=true NOCOVERAGE=true bundle exec parallel_rspec ${SPEC_PATH}" else @$(COMPOSE_TEST) $(BASH) -c "DISABLE_BOOTSNAP=true bundle exec parallel_rspec ${SPEC_PATH}" endif .PHONY: up up: db ## Starts the server and associated services with docker-compose @$(BASH_DEV) "rm -f tmp/pids/server.pid && bundle exec foreman start -m all=1" # NATIVE COMMANDS .PHONY: native-up native-up: bundle install foreman start -m all=1 .PHONY: native-lint native-lint: bundle exec rake lint .PHONY: native-spec native-spec: bundle exec rake spec .PHONY: native-spec-parallel native-spec-parallel: RAILS_ENV=test NOCOVERAGE=true bundle exec rake parallel:spec .PHONY: native-spec-parallel-setup native-spec-parallel-setup: RAILS_ENV=test bundle exec rake parallel:setup
0
code_files
code_files/vets-api-private/.irbrc
# Disable autocomplete in deployed environments # to help prevent running unintended commands if ENV['RAILS_ENV'] == 'production' IRB.conf[:USE_AUTOCOMPLETE] = false end
0
code_files
code_files/vets-api-private/config.ru
# frozen_string_literal: true # This file is used by Rack-based servers to start the application. require_relative 'config/environment' require 'datadog/profiling/preload' run Rails.application Rails.application.load_server
0
code_files
code_files/vets-api-private/docker-compose-clamav.yml
version: '3.4' services: clamav: volumes: - shared-vol:/vets-api image: clamav/clamav ports: - 33100:3310 volumes: shared-vol:
0
code_files
code_files/vets-api-private/README.md
# Vets API This project provides common APIs for applications that live on VA.gov (formerly vets.gov APIs). [![Yard Docs](http://img.shields.io/badge/yard-docs-blue.svg)](https://www.rubydoc.info/github/department-of-veterans-affairs/vets-api) [![License: CC0-1.0](https://img.shields.io/badge/License-CC0%201.0-lightgrey.svg)](LICENSE.md) [Build Status](http://jenkins.vfs.va.gov/job/builds/job/vets-api/) [VA.gov Platform Documentation](https://depo-platform-documentation.scrollhelp.site/index.html) [API Docs](https://department-of-veterans-affairs.github.io/va-digital-services-platform-docs/api-reference/#/) For frontend, see [vets-website](https://github.com/department-of-veterans-affairs/vets-website). ## Base setup 1. Clone the `vets-api` repo: ```bash git clone https://github.com/department-of-veterans-affairs/vets-api.git ``` 1. Set up key & cert for localhost authentication to ID.me: - Create a folder in your vets-api directory: ```bash mkdir config/certs touch config/certs/vetsgov-localhost.crt touch config/certs/vetsgov-localhost.key ``` - Copy example configuration file: ```bash cp config/settings.local.yml.example config/settings.local.yml ``` - Edit `config/settings.local.yml` to disable signed authentication requests: ```yaml # settings.local.yml saml: authn_requests_signed: false ``` 1. If you are developing. features that need Sidekiq Enterprise, you must have access to the va.gov-team-sensitive repo and [install the sidekiq enterprise license](https://github.com/department-of-veterans-affairs/va.gov-team-sensitive/blob/master/platform/engineering/sidekiq-enterprise-setup.md) Sidekiq Enterprise is used for worker rate limiting and additional reliability in production and requires a license be configured on your development machine. If you do not have a license configured, the open source version of Sidekiq will be installed instead. This is not an issue unless you are specifically developing features that need Sidekiq Enterprise. **DO NOT commit local Gemfile.lock modifications that remove the `sidekiq-ent` and `sidekiq-pro` gems.** 1. Developers who work with vets-api daily tend to prefer the native setup because they don't have to deal with the abstraction of docker-compose while those who would to spend less time on getting started prefer the docker setup. Docker is also useful when it's necessary to have a setup as close to production as possible. Finally, it's possible to use a hybrid setup where you run vets-api natively, but run the Postgres and Redis dependencies in docker. - [Native setup](docs/setup/native.md) (OSX/Ubuntu) - [Docker setup](docs/setup/docker.md) - [Hybrid setup](docs/setup/hybrid.md) - [Codespaces setup](docs/setup/codespaces.md) ## Running the app - [Running natively](docs/setup/running_natively.md) - [Running with Docker](docs/setup/running_docker.md) ## Configuration Vets API is configured with [Config](https://github.com/railsconfig/config). The default configuration is contained in [settings.yml](config/settings.yml). To customize your setup, you can create a `config/settings.local.yml` file with configuration specific to your needs. For example, to configure Redis and PostgreSQL (PostGIS is required), place something like this in that file: ```yaml database_url: postgis://pg_host:9999/custom_db redis: host: redis_host port: 9999 ``` This is also where you will place any other customizations, such as API tokens or certificate paths. Config settings that vary in value depending on the deployment environment will need to be set appropriately for each environment following [these instructions](https://depo-platform-documentation.scrollhelp.site/developer-docs/settings-and-parameter-store). Secrets like keys, certs, and .pem files are stored in a different way. See [these instructions](https://depo-platform-documentation.scrollhelp.site/developer-docs/how-to-add-secret-files-to-vets-api). ### Optional application configuration The following features require additional configuration, click for details. - [Education Benefits](/docs/setup/edu_benefits.md) - [EVSS](/docs/setup/evss.md) - [Facilities Locator](/docs/setup/facilities_locator.md) - [Local Network Access](/docs/setup/local_network_access.md) - [Mailers](/docs/setup/mailer.md) - [Master Person Index (MPI)](/docs/setup/mpi.md) - [My HealtheVet (MHV)](/docs/setup/mhv.md) - [Virtual Machine Access](/docs/setup/virtual_machine_access.md) - [Test User Dashboard](https://github.com/department-of-veterans-affairs/vsp-test-user-dashboard/blob/main/README.md#back-end) To mock one or more of the above services see [Betamocks](/docs/setup/betamocks.md) Vets API will still run in a limited capacity without configuring any of these features, and will run the unit tests successfully. ## Deployment - Vets-api deployment is explained [in this document](https://depo-platform-documentation.scrollhelp.site/developer-docs/vets-api-on-eks) - The [deploy status dashboard](https://www.va.gov/atlas/apps/vets-api/deploy_status) shows which environments a merged commit has been deployed to - The latest deploys can also be seen at the links below: - dev: https://dev-api.va.gov/v0/status - staging: https://staging-api.va.gov/v0/status - sandbox: https://sandbox-api.va.gov/v0/status - prod: https://api.va.gov/v0/status ## API request key formatting When sending HTTP requests use the `X-Key-Inflection` request header to specify which case your client wants to use. Valid cases are `camel`, `dash`, and `snake`. For example if you set `X-Key-Inflection: camel` then you can use camelCase keys in your JSON request body and you will get back data with camelCase keys in the response body. If the header is not provided then the server will expect snake_case keys in the request body and output snake_case in the response. ## Versions The version of Ruby and gem dependencies (including Rails) used are defined in the included [Gemfile](https://github.com/department-of-veterans-affairs/vets-api/blob/master/Gemfile). The currently used versions of gems are maintained with Bundler and stored in the [Gemfile.lock](https://github.com/department-of-veterans-affairs/vets-api/blob/master/Gemfile.lock). #### Version Policy The goal is to have vets-api use supported versions of gems and Ruby, which is often the latest. However, for security reasons, we have a cool-down period so we don't update the gems immediately. If you need a newer version of a gem, please submit a pull-request. ## Not a member of the repository and want to be added? - If you're on a VA.gov Platform team, contact your Program Manager. - If you're on a VFS team, you must complete [Platform Orientation](https://depo-platform-documentation.scrollhelp.site/getting-started/platform-orientation) to be added to this repository. This includes completing your Platform Orientation ticket(s) in GitHub.
0
code_files
code_files/vets-api-private/.reek.yml
--- ### https://github.com/troessner/reek directories: "app/controllers": IrresponsibleModule: enabled: false NestedIterators: max_allowed_nesting: 2 UnusedPrivateMethod: enabled: false InstanceVariableAssumption: enabled: false "modules/*/app/controllers": IrresponsibleModule: enabled: false NestedIterators: max_allowed_nesting: 2 UnusedPrivateMethod: enabled: false InstanceVariableAssumption: enabled: false "app/helpers": IrresponsibleModule: enabled: false UtilityFunction: enabled: false "modules/*/app/helpers": IrresponsibleModule: enabled: false UtilityFunction: enabled: false "app/mailers": InstanceVariableAssumption: enabled: false "modules/*/app/mailers": InstanceVariableAssumption: enabled: false "app/models": InstanceVariableAssumption: enabled: false "modules/*/app/models": InstanceVariableAssumption: enabled: false detectors: IrresponsibleModule: enabled: false UnusedParameters: enabled: false # rubocop takes care of this UtilityFunction: public_methods_only: true UncommunicativeMethodName: accept: - "/[0-9]+$/" UncommunicativeModuleName: accept: - "/[0-9]+$/" UncommunicativeParameterName: accept: - "/[0-9]+$/" UncommunicativeVariableName: accept: - e - k - v - i - "/[0-9]+$/"
0
code_files
code_files/vets-api-private/Rakefile
# frozen_string_literal: true # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require 'rake' require 'datadog' require_relative 'config/application' Datadog.configure do |c| c.tracing.instrument :rake end # Load rake support files Rails.root.glob('lib/tasks/support/**/*.rb').each { |f| require f } Rake.add_rakelib 'rakelib/prod' Rails.application.load_tasks unless Rails.env.production? require 'rspec/core/rake_task' task(spec: :environment).clear RSpec::Core::RakeTask.new(:spec) do |t| t.pattern = Dir.glob(['spec/**/*_spec.rb', 'modules/*/spec/**/*_spec.rb']) t.verbose = false end end
0
code_files
code_files/vets-api-private/.dockerignore
.bundle .git .github .gitignore .rspec coverage data docs log tmp script/vcr_inspector
0
code_files
code_files/vets-api-private/Procfile.dev
web: bundle exec puma -p 3000 -C ./config/puma.rb job: bundle exec sidekiq -q critical,4 -q tasker,3 -q default,2 -q low,1 clam: docker compose up clamav deps: docker compose up clamav postgres redis
0
code_files
code_files/vets-api-private/CONTRIBUTING.md
# Contributing to Vets-api Projects https://depo-platform-documentation.scrollhelp.site/developer-docs/backend-developer-documentation ## How to Contribute There are many ways to contribute to this project: ### Bugs If you spot a bug in the source code or a mistake in the documentation, let us know! File a GitHub Issue for this project. When filing an issue, add the following: - Title: Sentence that summarizes the bug concisely - Comment: - The environment you experienced the bug (browser, browser version, kind of account any extensions enabled) - The exact steps you took that triggered the bug. Steps 1, 2, 3, etc. - The expected outcome - The actual outcome, including screen shot - (Bonus Points:) Animated GIF or video of the bug occurring - Label: Apply the label `bug` ### Code Submissions Due to team sprint prioritization, we are not always able to review community pull requests in a timely fashion. We ask that you file an issue so that we can work the fix into the work that our team is already doing. The best way to make sure that you don't waste your time is to file an Issue before beginning work on the code to verify if the team will have bandwidth to review and that it fits into a product prioritization (these are typically every 1 or 2 weeks). ### What isn't open? We track tasks separately from the publicly visible GitHub Issues in this repository to ensure that sensitive PHI/PII doesn't wind up in the wrong place. We strive to work in the open as much as possible, but the team has decided that doing this keeps folks safer and allows us to keep the code itself open to all. With this said, please still file Issues for public contributions and reporting bugs. We still look here. :smile:
0
code_files
code_files/vets-api-private/docker-compose.review.yml
version: '3.4' x-app: &common build: args: BUNDLE_ENTERPRISE__CONTRIBSYS__COM: "${BUNDLE_ENTERPRISE__CONTRIBSYS__COM}" USER_ID: ${VETS_API_USER_ID} context: . environment: RAILS_ENV: development BUNDLE_ENTERPRISE__CONTRIBSYS__COM: "${BUNDLE_ENTERPRISE__CONTRIBSYS__COM}" SETTINGS__DATABASE_URL: "postgis://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DATABASE:-vets_api_development}?pool=4" SETTINGS__TEST_DATABASE_URL: "postgis://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DATABASE:-vets_api_test}" SETTINGS__REDIS__APP_DATA__URL: "redis://redis:6379" SETTINGS__REDIS__SIDEKIQ__URL: "redis://redis:6379" SETTINGS__REDIS__RAILS_CACHE__URL: "redis://redis:6379" SETTINGS__SAML_SSOE__IDP_METADATA_FILE: "config/ssoe_idp_sqa_metadata_isam.xml" IDENTITY_SETTINGS__SAML_SSOE__IDP_METADATA_FILE: "config/ssoe_idp_sqa_metadata_isam.xml" SETTINGS__BETAMOCKS__CACHE_DIR: "config/vets-api-mockdata" image: vets-api:${DOCKER_IMAGE:-latest} restart: unless-stopped volumes: - "../vets-api-mockdata:/cache" - ../.secret:/srv/vets-api/secret:cached - ../.pki:/srv/vets-api/pki:cached - clamav-files:/app/clamav_tmp working_dir: /app depends_on: - clamav - postgres - redis links: - clamav - postgres - redis services: clamav: image: clamav/clamav restart: unless-stopped ports: - 3310:3310 volumes: - clamav-files:/vets-api redis: image: redis:6.2-alpine restart: unless-stopped ports: - 6379:6379 postgres: command: postgres -c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all -c max_connections=200 environment: POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-password}" POSTGRES_USER: "${POSTGRES_USER:-postgres}" PGDATA: /tmp image: postgis/postgis:14-3.3-alpine ports: - 5432:5432 volumes: - ./data:/var/lib/postgresql/data:cached web: <<: *common command: bash -c "bundle exec rake db:migrate || bundle exec rake db:reset db:migrate && bundle exec rails s -b 0.0.0.0" ports: - 3000:3000 worker: <<: *common command: bundle exec sidekiq -q critical,4 -q tasker,3 -q default,2 -q low,1 volumes: clamav-files:
0
code_files
code_files/vets-api-private/import-va-certs.sh
#!/usr/bin/env bash set -euo pipefail ( cd /usr/local/share/ca-certificates/ curl -LO https://cacerts.digicert.com/DigiCertTLSRSASHA2562020CA1-1.crt.pem curl -LO https://digicert.tbs-certificats.com/DigiCertGlobalG2TLSRSASHA2562020CA1.crt # DoD ECA with multiple fallback mechanisms ( echo "Downloading DoD ECA certificates..." # Primary: HTTPS with timeout and retries if curl --show-error --connect-timeout 10 --max-time 60 --retry 3 --retry-delay 5 -o unclass-certificates_pkcs7_ECA.zip https://dl.dod.cyber.mil/wp-content/uploads/pki-pke/zip/unclass-certificates_pkcs7_ECA.zip; then echo "✓ DoD ECA downloaded via HTTPS" # Fallback 1: HTTP with timeout and retries ## Uncomment in case the https call fails again ## Last time we got this error: Failed to connect to dl.dod.cyber.mil port 443 elif curl --connect-timeout 10 --max-time 60 --retry 3 --retry-delay 5 -LO http://dl.dod.cyber.mil/wp-content/uploads/pki-pke/zip/unclass-certificates_pkcs7_ECA.zip; then echo "✓ DoD ECA downloaded via HTTP fallback" else echo "✗ All DoD ECA download attempts failed" fi # Process the downloaded certificates if [ -f "unclass-certificates_pkcs7_ECA.zip" ]; then unzip ./unclass-certificates_pkcs7_ECA.zip -d ECA_CA cd ECA_CA/certificates_pkcs7_v5_12_eca/ openssl pkcs7 -inform DER -in ./certificates_pkcs7_v5_12_eca_ECA_Root_CA_5_der.p7b -print_certs | awk '/BEGIN/{i++} {print > ("eca_cert" i ".pem")}' rm -f eca_cert.pem # first one is always invalid because of how awk is breaking it up cp *.pem ../../ echo "✓ DoD ECA certificates processed successfully" else echo "✗ DoD ECA zip file not found after download attempts" fi ) echo "Downloading VA certificates..." wget \ --level=1 \ --quiet \ --recursive \ --no-parent \ --no-host-directories \ --no-directories \ --accept="VA*.cer" \ http://aia.pki.va.gov/PKI/AIA/VA/ # Check if any certificate files exist before processing shopt -s nullglob cert_files=(*.cer *.pem) shopt -u nullglob if [ ${#cert_files[@]} -eq 0 ]; then echo "Warning: No certificate files found to process" else echo "Processing ${#cert_files[@]} certificate files..." fi for cert in *.{cer,pem} do # Process certificate file [ ! -f "$cert" ] && continue if file "${cert}" | grep -q 'PEM' then cp "${cert}" "${cert}.crt" elif file "${cert}" | grep -q 'ASCII text' then # Handle base64-encoded DER (like VA-Internal-S2-ICA22.cer) if base64 -d "${cert}" > "${cert}.der" && [ -s "${cert}.der" ] then if openssl x509 -in "${cert}.der" -inform der -outform pem -out "${cert}.crt" then rm "${cert}.der" else echo "Error: Failed to convert ${cert} from DER to PEM format" rm -f "${cert}.der" "${cert}.crt" exit 1 fi else echo "Error: Failed to decode base64 data in ${cert}" rm -f "${cert}.der" exit 1 fi else # Binary DER format openssl x509 -in "${cert}" -inform der -outform pem -out "${cert}.crt" fi rm "${cert}" done update-ca-certificates --fresh # Display VA Internal certificates that are now trusted awk -v cmd='openssl x509 -noout -subject' '/BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt \ | grep -iE '(VA-Internal|DigiCert)' )
0
code_files
code_files/vets-api-private/Dangerfile
# frozen_string_literal: true require 'ostruct' require 'open3' require_relative 'lib/dangerfile/parameter_filtering_allowlist_checker' module VSPDanger HEAD_SHA = ENV.fetch('GITHUB_HEAD_REF', '').empty? ? `git rev-parse --abbrev-ref HEAD`.chomp.freeze : "origin/#{ENV.fetch('GITHUB_HEAD_REF')}" BASE_SHA = ENV.fetch('GITHUB_BASE_REF', '').empty? ? 'origin/master' : "origin/#{ENV.fetch('GITHUB_BASE_REF')}" class Runner def self.run prepare_git [ SidekiqEnterpriseGaurantor.new.run, ChangeLimiter.new.run, MigrationIsolator.new.run, CodeownersCheck.new.run, GemfileLockPlatformChecker.new.run, ::Dangerfile::ParameterFilteringAllowlistChecker.new(base_sha: BASE_SHA, head_sha: HEAD_SHA).run ] end def self.prepare_git `git fetch --depth=1000000 --prune origin +refs/heads/master:refs/remotes/origin/master` end end class Result ERROR = :error WARNING = :warning SUCCESS = :success attr_reader :severity, :message def initialize(severity, message) @severity = severity @message = message end def self.error(message) Result.new(ERROR, message) end def self.warn(message) Result.new(WARNING, message) end def self.success(message) Result.new(SUCCESS, message) end end class ChangeLimiter EXCLUSIONS = %w[ *.csv *.json *.tsv *.txt *.md Gemfile.lock app/swagger modules/mobile/docs spec/fixtures/ spec/support/vcr_cassettes/ modules/mobile/spec/support/vcr_cassettes/ db/seeds modules/vaos/app/docs modules/meb_api/app/docs modules/appeals_api/app/swagger/ *.bru *.pdf modules/*/spec/fixtures/* modules/*/spec/factories/* modules/*/spec/**/*.rb spec/**/*.rb modules/*/docs/**/*.yaml modules/*/docs/**/*.yml modules/*/app/docs/**/*.yaml modules/*/app/docs/**/*.yml ].freeze PR_SIZE = { recommended: 200, maximum: 500 }.freeze def run return Result.error(error_message) if lines_changed > PR_SIZE[:maximum] return Result.warn(warning_message) if lines_changed > PR_SIZE[:recommended] Result.success('All set.') end private def error_message <<~EMSG This PR changes `#{lines_changed}` LoC (not counting whitespace/newlines). In order to ensure each PR receives the proper attention it deserves, those exceeding `#{PR_SIZE[:maximum]}` will not be reviewed, nor will they be allowed to merge. Please break this PR up into smaller ones. If you have reason to believe that this PR should be granted an exception, please see the [Submitting pull requests for approval - FAQ](https://depo-platform-documentation.scrollhelp.site/developer-docs/Submitting-pull-requests-for-approval.655032351.html#Submittingpullrequestsforapproval-FAQ). #{file_summary} Big PRs are difficult to review, often become stale, and cause delays. EMSG end def warning_message <<~EMSG This PR changes `#{lines_changed}` LoC (not counting whitespace/newlines). In order to ensure each PR receives the proper attention it deserves, we recommend not exceeding `#{PR_SIZE[:recommended]}`. Expect some delays getting reviews. #{file_summary} Big PRs are difficult to review, often become stale, and cause delays. EMSG end def file_summary <<~MSG <details> <summary>File Summary</summary> #### Files #{changes.collect { |change| "- #{change.file_name} (+#{change.insertions}/-#{change.deletions})" }.join "\n"} #### _Note: We exclude files matching the following when considering PR size:_ ``` #{EXCLUSIONS.join ', '} ``` </details> MSG end def lines_changed @lines_changed ||= changes.sum(&:total_changes) end def changes @changes ||= `#{files_command}`.split("\n").map do |file_changes| insertions, deletions, file_name = file_changes.split "\t" insertions = insertions.to_i deletions = deletions.to_i next if insertions.zero? && deletions.zero? # Skip unchanged files next if insertions == '-' && deletions == '-' # Skip Binary files (should be caught by `to_i` and `zero?`) # rename or copy - use the reported changes from earlier instead - `file_name` will not exist # eg: {lib => modules/pensions/lib}/pdf_fill/forms/va21p527ez.rb unless file_name.include?(' => ') lines = file_git_diff(file_name).split("\n") changed = { '+' => 0, '-' => 0 } lines.each do |line| next if (line =~ /^(\+[^+]|-[^-])/).nil? # Only changed lines, exclude metadata action = line[0].to_s clean_line = line[1..].strip # Remove leading '+' or '-' # Skip comments and empty lines next if clean_line.start_with?('#') || clean_line.empty? changed[action] += 1 end # the actual count of changed lines insertions, deletions = changed.values end OpenStruct.new( total_changes: insertions + deletions, insertions:, deletions:, file_name: ) end.compact end def files_command "git diff #{BASE_SHA}...#{HEAD_SHA} --numstat -w --ignore-blank-lines -- . #{exclusions}" end def exclusions EXCLUSIONS.map { |exclusion| "':!#{exclusion}'" }.join ' ' end def file_git_diff(file_name) `git diff #{BASE_SHA}...#{HEAD_SHA} -w --ignore-blank-lines -- #{file_name}` end end class CodeownersCheck def fetch_git_diff `git diff #{BASE_SHA}...#{HEAD_SHA} -- .github/CODEOWNERS` end def error_message(required_group, index, line) <<~EMSG New entry on line #{index + 1} of CODEOWNERS does not include #{required_group}. Please add #{required_group} to the entry Offending line: `#{line}` EMSG end def run required_group = '@department-of-veterans-affairs/backend-review-group' exception_groups = %w[@department-of-veterans-affairs/octo-identity @department-of-veterans-affairs/mobile-api-team @department-of-veterans-affairs/fed-eng-admin] diff = fetch_git_diff if diff.empty? Result.success('CODEOWNERS file is unchanged.') else lines = diff.split("\n") lines.each_with_index do |line, index| next unless line.start_with?('+') # Only added lines next if line.start_with?('+++') # Skip metadata lines clean_line = line[1..].strip # Remove leading '+' # Skip comments, empty lines, or exceptions next if clean_line.start_with?('#') || clean_line.empty? || exception_groups.any? { |group| clean_line.include?(group) } unless clean_line.include?(required_group) return Result.error(error_message(required_group, index, clean_line)) end end Result.success("All new entries in CODEOWNERS include #{required_group}.") end end end class MigrationIsolator DB_PATHS = ['db/migrate/', 'db/schema.rb'].freeze SEEDS_PATHS = ['db/seeds/', 'db/seeds.rb'].freeze # Pre-compile regex patterns for performance DB_PATTERN = Regexp.union(DB_PATHS).freeze SEEDS_PATTERN = Regexp.union(SEEDS_PATHS).freeze # Allowed app file patterns when migrations are present # Based on strong_migrations best practices ALLOWED_APP_PATTERNS = [ %r{spec/.+_spec\.rb$}, # Test files %r{modules/.+/spec/.+_spec\.rb$}, # Module test files %r{spec/factories/.+\.rb$}, # Factory changes %r{modules/.+/spec/factories/.+\.rb$} # Module factory changes ].freeze def run return Result.success('All set.') unless db_files.any? # Check for column removal without ignored_columns return Result.warn(column_removal_warning) if migration_removes_columns? && !ignored_columns_in_models? disallowed_files = app_files.reject { |file| allowed_app_file?(file) } return Result.error(error_message(disallowed_files)) if disallowed_files.any? return Result.warn(warning_message) if app_files.any? Result.success('All set.') end private def migration_removes_columns? # Use git grep for efficiency - searches without reading entire files return false if migration_files.empty? # Validate file paths for security validated_files = validate_file_paths(migration_files) return false if validated_files.empty? # Check all migration files at once with git grep # Use Open3 for secure command execution migration_pattern = 'remove_column|remove_columns|drop_column' cmd = ['git', 'grep', '-l', migration_pattern, '--'] + validated_files stdout, _stderr, status = Open3.capture3(*cmd) status.success? && !stdout.strip.empty? end def ignored_columns_in_models? model_files = app_files.grep(%r{app/models/.+\.rb$}) return false if model_files.empty? # Validate file paths for security validated_files = validate_file_paths(model_files) return false if validated_files.empty? # Check all model files at once with git grep # Use Open3 for secure command execution cmd = ['git', 'grep', '-l', 'ignored_columns', '--'] + validated_files stdout, _stderr, status = Open3.capture3(*cmd) status.success? && !stdout.strip.empty? end def validate_file_paths(file_list) # Validate that file paths are safe and within repo file_list.select do |file| # Ensure no path traversal attempts !file.include?('..') && # Ensure no absolute paths !file.start_with?('/') && # Ensure no null bytes or special chars that could break commands !file.match?(/[\x00-\x1f]/) && # Ensure file is within expected directories file.match?(%r{^(app|db|lib|spec|modules|config)/}) end end def migration_files db_files.grep(%r{db/migrate/.+\.rb$}) end def column_removal_warning <<~EMSG ⚠️ **Column Removal Detected Without `ignored_columns`** This PR contains a migration that removes columns but doesn't include `ignored_columns` in any models. **Strong Migrations recommends a 3-step process:** 1. **First PR:** Add `ignored_columns` to the model 2. **Second PR:** Remove the column with `safety_assured` 3. **Third PR:** Remove `ignored_columns` from the model **Example for step 1:** ```ruby class YourModel < ApplicationRecord self.ignored_columns += ["column_to_remove"] end ``` **Why this matters:** - Active Record caches columns at runtime - Removing columns without ignoring them first can cause production errors - Rolling deployments may have servers with different code versions Consider splitting this into separate PRs following the Strong Migrations pattern. For more info: - [Strong Migrations - Removing a column](https://github.com/ankane/strong_migrations#removing-a-column) - [vets-api Database Migrations](https://depo-platform-documentation.scrollhelp.site/developer-docs/Vets-API-Database-Migrations.689832034.html) EMSG end def allowed_app_file?(file) ALLOWED_APP_PATTERNS.any? { |pattern| file.match?(pattern) } end def warning_message <<~EMSG This PR contains both migration and application code changes. The following files were modified alongside migrations: - #{app_files.join "\n- "} These changes appear to be test-related files that need updating for the migration. This is generally acceptable as tests need to validate the new schema. Please ensure these changes are necessary for the migration's safety. For more info: - [Strong Migrations Best Practices](https://github.com/ankane/strong_migrations#removing-a-column) - [vets-api Database Migrations](https://depo-platform-documentation.scrollhelp.site/developer-docs/Vets-API-Database-Migrations.689832034.html) EMSG end def error_message(disallowed_files) <<~EMSG This PR contains migrations with disallowed application code changes. <details> <summary>File Summary</summary> #### DB File(s) - #{db_files.join "\n- "} #### Disallowed App File(s) - #{disallowed_files.join "\n- "} #{(app_files - disallowed_files).any? ? "#### Allowed App File(s)\n- #{(app_files - disallowed_files).join "\n- "}" : ''} </details> **Allowed changes with migrations:** - Test files and factories (to validate the migration) - Strong migrations configuration **Not allowed:** - Model changes (including `ignored_columns` - these should be in a separate PR) - Controller changes - Service object changes - Background job changes - Other business logic changes These should be deployed separately to ensure backwards compatibility. For more info: - [Strong Migrations Best Practices](https://github.com/ankane/strong_migrations) - [vets-api Database Migrations](https://depo-platform-documentation.scrollhelp.site/developer-docs/Vets-API-Database-Migrations.689832034.html) EMSG end def app_files (files - db_files - seed_files).reject { |file| file == File.basename(__FILE__) } end def db_files files.grep(DB_PATTERN) end def seed_files files.grep(SEEDS_PATTERN) end def files @files ||= `git diff #{BASE_SHA}...#{HEAD_SHA} --name-only`.split("\n") end end class GemfileLockPlatformChecker def run errors = [] errors << "#{ruby_error_message}\n#{ruby_resolution_message}" if ruby_platform_removed? if (darwin_platform = darwin_platform_added) errors << "#{darwin_error_message(darwin_platform)}\n#{darwin_resolution_message(darwin_platform)}" end return Result.success('Gemfile.lock platform checks passed.') if errors.empty? errors << redownload_message Result.error(errors.join("\n\n")) end private def ruby_platform_removed? !platforms_section.include?('ruby') end def darwin_platform_added platforms_section[/.*-darwin-\d+/] end def ruby_error_message "You've removed the `ruby` platform from the Gemfile.lock! You must restore it before merging this PR." end def ruby_resolution_message <<~TEXT ``` bundle lock --add-platform ruby ``` TEXT end def darwin_error_message(darwin_platform) "You've added a Darwin platform to the Gemfile.lock: `#{darwin_platform.strip}`. You must remove it before merging this PR." end def darwin_resolution_message(darwin_platform) <<~TEXT ``` bundle lock --remove-platform #{darwin_platform.strip} ``` TEXT end def redownload_message <<~TEXT Redownload your gems after making the necessary changes: ``` bundle install --redownload ``` TEXT end def platforms_section @platforms_section ||= gemfile_lock.match(/^PLATFORMS$(.*?)^\n/m)[1] end def gemfile_lock File.read('Gemfile.lock') end end class SidekiqEnterpriseGaurantor def run return Result.error(error_message) if enterprise_remote_removed? Result.success('Sidekiq Enterprise is preserved.') end private def enterprise_remote_removed? gemfile_diff.include?('- remote: https://enterprise.contribsys.com/') end def error_message <<~EMSG You've removed Sidekiq Enterprise from the gemfile! You must restore it before merging this PR. More details about Sidekiq Enterprise can be found in the [README](https://github.com/department-of-veterans-affairs/vets-api/blob/master/README.md). EMSG end def gemfile_diff `git diff #{BASE_SHA}...#{HEAD_SHA} -- Gemfile.lock` end end if $PROGRAM_NAME == __FILE__ require 'minitest/autorun' class ChangeLimiterTest < Minitest::Test def test_rubocop assert system('rubocop --format simple') end # TODO: Remove dummy test def test_recommended_pr_size assert_equal ChangeLimiter::PR_SIZE[:recommended], 200 end end end end if $PROGRAM_NAME != __FILE__ VSPDanger::Runner.run.each do |result| case result.severity when VSPDanger::Result::ERROR failure result.message when VSPDanger::Result::WARNING warn result.message end end end
0
code_files
code_files/vets-api-private/Gemfile
# frozen_string_literal: true source 'https://rubygems.org' ruby '~> 3.3.6' # Modules path 'modules' do gem 'accredited_representative_portal' gem 'appeals_api' gem 'apps_api' gem 'ask_va_api' gem 'avs' gem 'banners' gem 'bpds' gem 'burials' gem 'check_in' gem 'claims_api' gem 'claims_evidence_api' gem 'debts_api' gem 'decision_reviews' gem 'dependents_benefits' gem 'dependents_verification' gem 'dhp_connected_devices' gem 'digital_forms_api' gem 'employment_questionnaires' gem 'facilities_api' gem 'income_and_assets' gem 'income_limits' gem 'increase_compensation' gem 'ivc_champva' gem 'meb_api' gem 'medical_expense_reports' gem 'mobile' gem 'mocked_authentication' gem 'my_health' gem 'pensions' gem 'representation_management' gem 'simple_forms_api' gem 'sob' gem 'survivors_benefits' gem 'test_user_dashboard' gem 'travel_pay' gem 'va_notify' gem 'vaos' gem 'vass' gem 'vba_documents' gem 'veteran' gem 'vre' gem 'vye' end gem 'rails', '~> 7.2.3' gem 'aasm' gem 'activerecord-import' gem 'activerecord-postgis-adapter' gem 'addressable' gem 'avro' gem 'aws-msk-iam-sasl-signer', '~> 0.1.1' gem 'aws-sdk-kms' gem 'aws-sdk-s3', '~> 1' gem 'aws-sdk-sns', '~> 1' gem 'betamocks', git: 'https://github.com/department-of-veterans-affairs/betamocks', branch: 'master' gem 'bgs_ext', git: 'https://github.com/department-of-veterans-affairs/bgs-ext.git', require: 'bgs', ref: 'a68ea30' gem 'blind_index' gem 'blueprinter' gem 'bootsnap', require: false gem 'breakers' gem 'carrierwave' gem 'carrierwave-aws' gem 'clamav-client', require: 'clamav/client' gem 'combine_pdf' gem 'committee-rails' gem 'config' gem 'connect_vbms', git: 'https://github.com/adhocteam/connect_vbms', tag: 'v2.1.1', require: 'vbms' gem 'csv' gem 'datadog' gem 'date_validator' gem 'dogstatsd-ruby' gem 'dry-struct' gem 'dry-types' gem 'ethon', '>=0.13.0' gem 'faraday', '~> 2.14' gem 'faraday-follow_redirects' gem 'faraday-httpclient' gem 'faraday-multipart' gem 'faraday-retry' gem 'faraday-typhoeus' gem 'fastimage' gem 'fhir_client', git: 'https://github.com/department-of-veterans-affairs/fhir_client.git', tag: 'v6.1.0' gem 'fitbit_api' gem 'flipper' gem 'flipper-active_record' gem 'flipper-active_support_cache_store' gem 'flipper-ui' gem 'foreman' gem 'google-api-client' gem 'google-apis-core' gem 'google-apis-generator' gem 'googleauth' gem 'google-protobuf' # For Datadog Profiling gem 'govdelivery-tms', git: 'https://github.com/department-of-veterans-affairs/govdelivery-tms-ruby.git', tag: 'v4.2.0', require: 'govdelivery/tms/mail/delivery_method' gem 'gyoku' gem 'hexapdf' gem 'holidays' gem 'httpclient' # for lib/evss/base_service.rb gem 'ice_nine' gem 'iso_country_codes' gem 'json' gem 'jsonapi-parser' gem 'jsonapi-serializer' gem 'json-schema' gem 'json_schemer' gem 'jwe' gem 'jwt' gem 'kms_encrypted' gem 'liquid' gem 'lockbox' gem 'mail' gem 'memoist' gem 'mimemagic' gem 'mini_magick' gem 'net-sftp' gem 'nkf' gem 'nokogiri' gem 'notifications-ruby-client' gem 'octokit' gem 'oj' # Amazon Linux `json` gem causes conflicts, but `multi_json` will prefer `oj` if installed gem 'okcomputer' gem 'olive_branch' gem 'operating_hours' gem 'ox' gem 'parallel' gem 'pdf-forms' gem 'pdf-reader' gem 'pg' gem 'pg_query' gem 'pg_search' gem 'pkce_challenge' gem 'prawn', '~> 2.4.0' # Pinned to version 2.4.0 to avoid embedded font issues (https://github.com/prawnpdf/ttfunk/issues/102) gem 'prawn-markup' gem 'prawn-table' gem 'puma' gem 'pundit' gem 'rack', '~> 2.2.21' gem 'rack-attack' gem 'rack-cors', require: 'rack/cors' gem 'rack-timeout', require: 'rack/timeout/base' gem 'rails_semantic_logger' gem 'rails-session_cookie' gem 'ransack' gem 'redis' gem 'redis-namespace' gem 'request_store' gem 'require_all' gem 'restforce' gem 'rgeo-geojson' gem 'roo' gem 'rswag-ui' gem 'rtesseract' gem 'ruby-saml' gem 'rubyzip' gem 'savon' gem 'sentry-ruby', '5.28.1' gem 'shrine' gem 'sign_in_service' gem 'slack-notify' gem 'socksify' gem 'staccato' gem 'statsd-instrument' gem 'strong_migrations' gem 'swagger-blocks' gem 'ttfunk', '~> 1.7.0' # Include the IANA Time Zone Database on Windows, where Windows doesn't ship with a timezone database. # POSIX systems should have this already, so we're not going to bring it in on other platforms gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] gem 'utf8-cleaner' gem 'vets_json_schema', git: 'https://github.com/department-of-veterans-affairs/vets-json-schema', branch: 'master' gem 'virtus' gem 'warden-github' gem 'waterdrop' gem 'will_paginate' gem 'with_advisory_lock' group :development, :production do # This needs to be required as early as possible in the initialization # process because it starts collecting data on 'require'. # Only require this in development and production to avoid slowing down tests. gem 'coverband' end group :development do gem 'guard-rubocop' gem 'seedbank' # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', platforms: :ruby end group :test do gem 'apivore', git: 'https://github.com/department-of-veterans-affairs/apivore', tag: 'v2.1.0.vsp' gem 'hashdiff' gem 'mock_redis' gem 'pdf-inspector' gem 'rspec_junit_formatter' gem 'rspec-retry' gem 'rspec-sidekiq' gem 'rubocop-junit-formatter' gem 'rufus-scheduler' gem 'shoulda-matchers' gem 'simplecov', require: false gem 'super_diff' gem 'vcr' gem 'webrick' end group :development, :test do gem 'awesome_print' # Pretty print your Ruby objects in full color and with proper indentation gem 'brakeman' gem 'bundler-audit' gem 'byebug', platforms: :ruby # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'danger' gem 'database_cleaner' gem 'debug' gem 'factory_bot_rails' gem 'faker' # CAUTION: faraday_curl may not provide all headers used in the actual faraday request. Be cautious if using this to # assist with debugging production issues (https://github.com/department-of-veterans-affairs/vets.gov-team/pull/6262) gem 'faraday_curl' gem 'fuubar' gem 'guard-rspec' gem 'parallel_tests' gem 'pry-byebug' gem 'rack-test', '2.2.0', require: 'rack/test' gem 'rack-vcr' gem 'rainbow' # Used to colorize output for rake tasks gem 'rspec-instrumentation-matcher' gem 'rspec-its' gem 'rspec-rails' gem 'rswag-specs' gem 'rubocop', require: false gem 'rubocop-capybara' gem 'rubocop-factory_bot' gem 'rubocop-rails' gem 'rubocop-rspec' gem 'rubocop-rspec_rails' gem 'rubocop-thread_safety' gem 'sidekiq' gem 'timecop' gem 'webmock' gem 'yard' end # sidekiq enterprise requires a license key to download. In many cases, basic sidekiq is enough for local development if (Bundler::Settings.new(Bundler.app_config_path)['enterprise.contribsys.com'].nil? || Bundler::Settings.new(Bundler.app_config_path)['enterprise.contribsys.com']&.empty?) && ENV.fetch('BUNDLE_ENTERPRISE__CONTRIBSYS__COM', '').empty? && ENV.keys.grep(/DEPENDABOT/).empty? Bundler.ui.warn 'No credentials found to install Sidekiq Enterprise. This is fine for local development but you may not check in this Gemfile.lock with any Sidekiq gems removed. The README file in this directory contains more information.' else source 'https://enterprise.contribsys.com/' do gem 'sidekiq-ent' gem 'sidekiq-pro' end end
0
code_files
code_files/vets-api-private/.rubocop.yml
inherit_from: - .rubocop_explicit_enables.yml - .rubocop_todo.yml require: - './lib/rubocop/cops/ams_serializer.rb' plugins: - rubocop-rails - rubocop-rspec - rubocop-capybara - rubocop-factory_bot - rubocop-rspec_rails - rubocop-thread_safety AllCops: NewCops: disable TargetRailsVersion: 6.1 Include: - '**/Dangerfile' - '**/Gemfile' - '**/config.ru' - '**/Rakefile' - '**/*.rake' - '**/*.rb' Exclude: - db/schema.rb - db/audit_schema.rb - db/seeds.rb - db/migrate/*.rb - db/audit_migrate/*.rb - 'vendor/**/*' - modules/**/db/migrate/*.rb - 'tmp/**/*' Style/Documentation: Enabled: false Style/ClassAndModuleChildren: Enabled: false Style/GlobalVars: AllowedVariables: - $redis Style/HashSyntax: EnforcedShorthandSyntax: always # Bug in 1.11.0 RSpec/VariableName: Exclude: - spec/sidekiq/facilities/pssg_download_spec.rb # This cop forces you to put a return at the beginning of a block of code rather than having an if statement # whose body carries to the end of the function. For example: # # def foo # ... # if test # ... # end # end # # would be considered bad, and the cop would force you to put a `return if !test` before that block and # then remove the if. The problem is that this hides intent, since the if test does have a purpose in # readability, and it could also be easier for future changes to miss the return statement and add code # after it expecting it to be executed. Style/GuardClause: Enabled: false # This is pretty much the same thing as the one above. Inside a loop, it forces you to use next to skip # iteration rather than using an if block that runs to the end of the loop, and it suffers from the same # problems as above. Style/Next: Enabled: false # This forces you to replace things like: `[1, 2, 3].length == 0` with `[1,2,3].empty?`. The problem is that # not all things that implement length also implement empty? so you will get errors that cannot be resolved, # and the cop will encourage you to do things that are incorrect. Style/ZeroLengthPredicate: Enabled: false Layout/LineLength: Max: 120 Exclude: - 'Gemfile' - 'Dangerfile' Rails: Enabled: true Exclude: - 'Dangerfile' Rails/Output: Exclude: - 'lib/tasks/**/*' - 'bin/lib/vets-api/**/*' Metrics/MethodLength: Max: 20 Exclude: - 'spec/support/form1010cg_helpers/build_claim_data_for.rb' - 'spec/simplecov_helper.rb' - 'app/sidekiq/education_form/create_daily_spool_files.rb' - 'lib/map/security_token/service.rb' - 'Dangerfile' Metrics/ClassLength: Max: 400 Rails/LexicallyScopedActionFilter: Exclude: - "app/controllers/concerns/filterable.rb" - 'modules/mobile/app/controllers/mobile/application_controller.rb' # Blocks are limited to 25 lines or less # removing block length rule for rspec DSL Metrics/BlockLength: Exclude: - 'spec/**/*.rb' - 'rakelib/**/*.rake' - 'lib/tasks/**/*.rake' - 'config/**/*.rb' - 'app/swagger/**/*.rb' - 'app/controllers/v0/apidocs_controller.rb' - 'app/controllers/v1/apidocs_controller.rb' - 'modules/*/spec/**/*.rb' - 'modules/*/app/swagger/**/*.rb' - 'modules/*/config/routes.rb' # Don't worry about ambiguous blocks in RSpec # Official recommendation from rubocop team is to disable this rule for specs. # See: https://github.com/rubocop-hq/rubocop/issues/4222 Lint/AmbiguousBlockAssociation: Exclude: - "spec/**/*" # This file does not need to be snake case Naming/FileName: Exclude: - '**/Gemfile' - '**/Guardfile' - '**/Rakefile' - 'config/initializers/rswag-ui.rb' # TODO: REVIEW THESE AND MAKE CHANGES # We should try to use StandardError, but some errors like timeout inherit from Exception (beware) Style/RescueStandardError: EnforcedStyle: implicit # Skipping for now, should revisit: Rails/HasManyOrHasOneDependent: Exclude: - "app/models/education_benefits_claim.rb" - "app/models/saved_claim/education_benefits.rb" - "app/models/saved_claim.rb" - modules/accredited_representative_portal/app/models/accredited_representative_portal/power_of_attorney_request.rb - modules/accredited_representative_portal/app/models/accredited_representative_portal/power_of_attorney_request_resolution.rb - modules/accredited_representative_portal/app/models/accredited_representative_portal/saved_claim/benefits_intake.rb - modules/income_limits/app/models/std_state.rb # The suggestions here don't seem to make sense in most cases. Skip for now. Naming/MemoizedInstanceVariableName: Enabled: false # It was determined these suggestions had the potential to change behavior. Rails/ActiveRecordAliases: Enabled: false # The suggestions would break 54 files. Skip for now. Rails/Pluck: Enabled: false # The use of variables such as n to represent number, x and y for x-axis and y-axis, el for element, # v for value, i for index, and e for error are all standard abbreviations and should be excluded. Naming/MethodParameterName: Enabled: false # FactoryBot 5.x replaced static factory attributes with dynamic ones. Auto-converting using rubocop-rspec # always uses {...} which means a lot of existing factories because invalid. Allowed exception in pr #3300. Style/BlockDelimiters: Exclude: - "spec/factories/*.rb" - "modules/*/spec/factories/*.rb" # Excluding modules specs for now and a few that may need to be revisited. RSpec/SpecFilePathFormat: Enabled: true Exclude: - 'modules/**/*' - 'spec/lib/common/models/**/*' - 'spec/lib/saml/*_user_spec.rb' - 'spec/requests/in_progress_forms_request_spec.rb' - 'spec/sidekiq/pagerduty/**/*' - 'spec/lib/pagerduty/**/*' - 'spec/lib/common/client/middleware/response/appeals_response_middleware_spec.rb' - 'spec/lib/common/client/middleware/response/gids_response_middleware_spec.rb' - 'spec/lib/common/client/middleware/response/response_middleware_spec.rb' - 'spec/lib/sm/client/message_drafts_spec.rb' - 'spec/lib/lighthouse/veterans_health/integration/client_spec.rb' - 'spec/lib/mail_automation/integration/client_spec.rb' - 'spec/rakelib/piilog_repl/piilog_helpers_spec.rb' CustomTransform: SSOeSettingsService: ssoe_settings_service # Use in conjunction with SpecFilePathFormat RSpec/SpecFilePathSuffix: Enabled: true # Was determined that using described_class makes the code less readable. RSpec/DescribedClass: Enabled: false # Excluding these for now. May need to be revisited. RSpec/DescribeClass: Exclude: - 'spec/lib/mhv_ac/client_spec.rb' - 'spec/lib/mhv_logging/api/audits_spec.rb' - 'spec/rakelib/vet360_spec.rb' - 'spec/requests/**/*' - 'spec/lib/sm/client/preferences_spec.rb' - 'spec/lib/sm/client/triage_teams_spec.rb' - 'spec/lib/sm/client/messages_spec.rb' - 'spec/lib/bb/client_spec.rb' - 'spec/lib/gi/client_spec.rb' - 'spec/lib/sm/client/folders_spec.rb' # Determined to be too benign and/or numerous to justify changing RSpec/AnyInstance: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/BeforeAfterAll: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/ExpectInLet: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/IndexedLet: Enabled: false RSpec/RemoveConst: Exclude: - 'spec/sidekiq/kms_key_rotation/batch_initiator_job_spec.rb' - 'modules/vba_documents/spec/mailers/unsuccessful_report_mailer_spec.rb' # Determined to be too benign and/or numerous to justify changing RSpec/ContextWording: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/MissingExpectationTargetMethod: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/ExampleLength: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/ExpectInHook: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/InstanceVariable: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/LeakyConstantDeclaration: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/MultipleMemoizedHelpers: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/MessageSpies: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/NamedSubject: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/VerifiedDoubles: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/MultipleExpectations: Enabled: false # Determined to be too benign and/or numerous to justify changing RSpec/NestedGroups: Enabled: false # This seems to generate a lot of false positives RSpec/EmptyExampleGroup: Enabled: false # This seems to generate a lot of false positives RSpec/LetSetup: Enabled: false # Might be worth revisiting at some point RSpec/MessageChain: Exclude: - 'modules/veteran_verification/spec/requests/service_history_request_spec.rb' - 'modules/veteran_verification/spec/requests/veteran_status_request_spec.rb' - 'spec/lib/va_profile/service_spec.rb' - 'spec/requests/service_history_request_spec.rb' - 'spec/requests/swagger_spec.rb' # These instances seem to be necessary RSpec/MultipleDescribes: Exclude: - 'spec/sidekiq/evss/document_upload_spec.rb' - 'spec/sidekiq/evss/request_decision_spec.rb' - 'spec/requests/swagger_spec.rb' # These instances seem to be false positives RSpec/RepeatedExample: Exclude: - 'modules/vba_documents/spec/sidekiq/upload_processor_spec.rb' - 'modules/vba_documents/spec/models/upload_submission_spec.rb' - 'modules/vba_documents/spec/request/v0/reports_request_spec.rb' - 'modules/vba_documents/spec/request/v1/reports_request_spec.rb' # Might be worth revisiting at some point RSpec/ScatteredLet: Exclude: - 'spec/controllers/openid_application_controller_spec.rb' - 'spec/controllers/v0/dependents_applications_controller_spec.rb' - 'spec/controllers/v0/post911_gi_bill_statuses_controller_spec.rb' - 'spec/lib/bb/client_spec.rb' - 'spec/lib/evss/auth_headers_spec.rb' - 'spec/lib/evss/gi_bill_status/service_spec.rb' - 'spec/lib/sentry/scrubbers/log_as_warning_spec.rb' - 'spec/mailers/spool_submissions_report_mailer_spec.rb' - 'spec/models/form_profile_spec.rb' - 'spec/models/va_profile_redis/v2/contact_information_spec.rb' - 'spec/requests/health_care_applications_request_spec.rb' - 'spec/requests/http_method_not_allowed_spec.rb' - 'spec/requests/swagger_spec.rb' # Might be worth revisiting at some point RSpec/SubjectStub: Exclude: - 'modules/vaos/spec/services/user_service_spec.rb' - 'spec/sidekiq/education_form/create_daily_spool_files_spec.rb' - 'spec/sidekiq/education_form/process10203_submissions_spec.rb' - 'spec/sidekiq/education_form/create10203_applicant_decision_letters_spec.rb' - 'spec/sidekiq/education_form/forms/va1990_spec.rb' - 'spec/sidekiq/transactional_email_analytics_job_spec.rb' - 'spec/sidekiq/form526_confirmation_email_job_spec.rb' - 'spec/lib/bb/generate_report_request_form_spec.rb' - 'spec/lib/common/models/redis_store_spec.rb' - 'spec/lib/evss/disability_compensation_form/data_translation_all_claim_spec.rb' - 'spec/lib/evss/disability_compensation_form/data_translation_spec.rb' - 'spec/lib/mpi/service_spec.rb' - 'spec/lib/sm/client/folders_spec.rb' - 'spec/models/session_spec.rb' - 'spec/services/evss_claim_service_spec.rb' - 'spec/uploaders/evss_claim_document_uploader_spec.rb' - 'spec/services/form1010cg/service_spec.rb' - 'spec/services/form1010cg/auditor_spec.rb' # the default style recently changed, but it's not worth changing Rails/FilePath: EnforcedStyle: arguments # This one doesn’t always make sense, it’s mostly the swagger, # factories and pact provider states — which need a tear_down block regardless Lint/EmptyBlock: Enabled: false Layout/EmptyLineBetweenDefs: AllowAdjacentOneLineDefs: true Cops/AmsSerializer: Enabled: true Rails/Exit: Exclude: - bin/**/*.rb - modules/mobile/lib/scripts/parse_rspec_xml.rb # kms_encrypted_model_patch is for a gem and the method name shouldn't be changed Naming/PredicatePrefix: Exclude: - app/models/concerns/kms_encrypted_model_patch.rb - app/models/preneeds/burial_form.rb Rails/UnusedIgnoredColumns: Exclude: - modules/test_user_dashboard/app/models/test_user_dashboard/tud_account.rb Rails/InverseOf: Exclude: - modules/income_limits/app/models/std_state.rb - modules/accredited_representative_portal/app/models/accredited_representative_portal/power_of_attorney_request.rb - modules/accredited_representative_portal/app/models/accredited_representative_portal/power_of_attorney_request_notification.rb - modules/accredited_representative_portal/app/models/accredited_representative_portal/saved_claim/benefits_intake.rb Lint/DuplicateMethods: Exclude: - modules/appeals_api/app/services/appeals_api/pdf_construction/supplemental_claim/v4/form_data.rb Rails/UniqueValidationWithoutIndex: Exclude: - modules/test_user_dashboard/app/models/test_user_dashboard/tud_account.rb Lint/ShadowingOuterLocalVariable: Exclude: - 'rakelib/decision_review_repl.rb' Style/SafeNavigation: Exclude: - 'modules/mobile/app/models/mobile/v0/adapters/immunizations.rb'
0
code_files
code_files/vets-api-private/Gemfile.lock
GIT remote: https://github.com/adhocteam/connect_vbms revision: 2284b8e9a68d2b44dda52a098ffc83f8fa283211 tag: v2.1.1 specs: connect_vbms (2.1.1) httpclient (~> 2.8.0) httpi (~> 4.0) mail nokogiri (>= 1.8.4) nori xmldsig (~> 0.3.1) xmlenc GIT remote: https://github.com/department-of-veterans-affairs/apivore revision: 1c7d19c4a52f71a3ef07940697ad9520f1872dd6 tag: v2.1.0.vsp specs: apivore (2.1.0.vsp) actionpack (>= 4) hashie (~> 5.0) json-schema (~> 5.0) rspec (~> 3) rspec-expectations (~> 3.1) rspec-mocks (~> 3.1) GIT remote: https://github.com/department-of-veterans-affairs/betamocks revision: 88bda10e03c92a97067d2d4fecb89783c6de227f branch: master specs: betamocks (0.11.0) activesupport (>= 4.2) adler32 faraday (>= 1.2.0, < 3.0) GIT remote: https://github.com/department-of-veterans-affairs/bgs-ext.git revision: a68ea30a8f2a33e2aad890be640fc6c29fb20a14 ref: a68ea30 specs: bgs_ext (0.23.3) httpclient nokogiri (>= 1.13.6) savon (~> 2.15.1) GIT remote: https://github.com/department-of-veterans-affairs/fhir_client.git revision: 81d0c0c98f317e7ad25c8211011d81f52d6e31a2 tag: v6.1.0 specs: fhir_client (6.1.0) activesupport (>= 3) addressable (>= 2.3) fhir_dstu2_models (>= 1.1.1) fhir_models (>= 4.2.1) fhir_stu3_models (>= 3.1.1) http (~> 5.1) nokogiri (>= 1.10.4) oauth2 (>= 1.1) rack (>= 1.5) tilt (>= 1.1) GIT remote: https://github.com/department-of-veterans-affairs/govdelivery-tms-ruby.git revision: 933fc6187e0dab7a51629eca25a4ed22feab946f tag: v4.2.0 specs: govdelivery-tms (4.1.0) activesupport (>= 5.2.4.3, < 9.0.0) faraday mime-types GIT remote: https://github.com/department-of-veterans-affairs/vets-json-schema revision: 531d9b1ef4f1738b825953b5e5a7e3d6fe1e1eec branch: master specs: vets_json_schema (25.2.37) multi_json (~> 1.0) script_utils (= 0.0.4) PATH remote: modules specs: accredited_representative_portal (0.1.0) blind_index appeals_api (0.0.1) jsonapi-serializer (>= 2.2.0) sidekiq apps_api (0.0.1) faraday sidekiq ask_va_api (0.1.0) avs (0.1.0) banners (0.1.0) bpds (0.1.0) burials (0.1.0) check_in (0.1.0) claims_api (0.0.1) dry-schema claims_evidence_api (0.1.0) debts_api (0.1.0) decision_reviews (0.1.0) rails (>= 7.1.4.1) dependents_benefits (0.1.0) dependents_verification (0.1.0) dhp_connected_devices (0.1.0) digital_forms_api (0.1.0) employment_questionnaires (0.1.0) facilities_api (0.1.0) income_and_assets (0.1.0) income_limits (0.1.0) increase_compensation (0.1.0) ivc_champva (0.1.0) meb_api (0.1.0) medical_expense_reports (0.1.0) mobile (0.1.0) dry-validation mocked_authentication (0.1.0) rails my_health (0.1.0) rails pensions (0.1.0) representation_management (0.1.0) simple_forms_api (0.1.0) sob (0.1.0) survivors_benefits (0.1.0) test_user_dashboard (0.1.0) rails travel_pay (0.1.0) va_notify (0.1.0) vaos (0.1.0) sidekiq vass (0.0.1) vba_documents (1.0.0) aws-sdk-s3 (~> 1) sidekiq veteran (0.0.1) vre (0.1.0) vye (0.1.0) GEM remote: https://enterprise.contribsys.com/ specs: sidekiq-ent (7.3.4) einhorn (~> 1.0) gserver sidekiq (>= 7.3.7, < 8) sidekiq-pro (>= 7.3.4, < 8) sidekiq-pro (7.3.6) sidekiq (>= 7.3.7, < 8) GEM remote: https://rubygems.org/ specs: Ascii85 (2.0.1) aasm (5.5.2) concurrent-ruby (~> 1.0) actioncable (7.2.3) actionpack (= 7.2.3) activesupport (= 7.2.3) nio4r (~> 2.0) websocket-driver (>= 0.6.1) zeitwerk (~> 2.6) actionmailbox (7.2.3) actionpack (= 7.2.3) activejob (= 7.2.3) activerecord (= 7.2.3) activestorage (= 7.2.3) activesupport (= 7.2.3) mail (>= 2.8.0) actionmailer (7.2.3) actionpack (= 7.2.3) actionview (= 7.2.3) activejob (= 7.2.3) activesupport (= 7.2.3) mail (>= 2.8.0) rails-dom-testing (~> 2.2) actionpack (7.2.3) actionview (= 7.2.3) activesupport (= 7.2.3) cgi nokogiri (>= 1.8.5) racc rack (>= 2.2.4, < 3.3) rack-session (>= 1.0.1) rack-test (>= 0.6.3) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) useragent (~> 0.16) actiontext (7.2.3) actionpack (= 7.2.3) activerecord (= 7.2.3) activestorage (= 7.2.3) activesupport (= 7.2.3) globalid (>= 0.6.0) nokogiri (>= 1.8.5) actionview (7.2.3) activesupport (= 7.2.3) builder (~> 3.1) cgi erubi (~> 1.11) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) activejob (7.2.3) activesupport (= 7.2.3) globalid (>= 0.3.6) activemodel (7.2.3) activesupport (= 7.2.3) activerecord (7.2.3) activemodel (= 7.2.3) activesupport (= 7.2.3) timeout (>= 0.4.0) activerecord-import (2.2.0) activerecord (>= 4.2) activerecord-postgis-adapter (10.0.1) activerecord (~> 7.2.0) rgeo-activerecord (~> 8.0.0) activestorage (7.2.3) actionpack (= 7.2.3) activejob (= 7.2.3) activerecord (= 7.2.3) activesupport (= 7.2.3) marcel (~> 1.0) activesupport (7.2.3) base64 benchmark (>= 0.3) bigdecimal concurrent-ruby (~> 1.0, >= 1.3.1) connection_pool (>= 2.2.5) drb i18n (>= 1.6, < 2) logger (>= 1.4.2) minitest (>= 5.1) securerandom (>= 0.3) tzinfo (~> 2.0, >= 2.0.5) addressable (2.8.8) public_suffix (>= 2.0.2, < 8.0) adler32 (0.0.2) afm (1.0.0) akami (1.3.3) base64 gyoku (>= 0.4.0) nokogiri argon2-kdf (0.3.1) fiddle ast (2.4.3) attr_extras (7.1.0) avro (1.12.1) multi_json (~> 1.0) awesome_print (1.9.2) aws-eventstream (1.4.0) aws-msk-iam-sasl-signer (0.1.1) aws-sdk-kafka thor aws-partitions (1.1197.0) aws-sdk-core (3.240.0) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) base64 bigdecimal jmespath (~> 1, >= 1.6.1) logger aws-sdk-kafka (1.89.0) aws-sdk-core (~> 3, >= 3.216.0) aws-sigv4 (~> 1.5) aws-sdk-kms (1.118.0) aws-sdk-core (~> 3, >= 3.239.1) aws-sigv4 (~> 1.5) aws-sdk-s3 (1.208.0) aws-sdk-core (~> 3, >= 3.234.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) aws-sdk-sns (1.109.0) aws-sdk-core (~> 3, >= 3.239.1) aws-sigv4 (~> 1.5) aws-sigv4 (1.12.1) aws-eventstream (~> 1, >= 1.0.2) axiom-types (0.1.1) descendants_tracker (~> 0.0.4) ice_nine (~> 0.11.0) thread_safe (~> 0.3, >= 0.3.1) base64 (0.3.0) bcp47 (0.3.3) i18n benchmark (0.5.0) bigdecimal (3.3.1) bigdecimal (3.3.1-java) bindex (0.8.1) blind_index (2.7.0) activesupport (>= 7.1) argon2-kdf (>= 0.2) blueprinter (1.2.1) bootsnap (1.19.0) msgpack (~> 1.2) brakeman (7.1.1) racc breakers (1.0) base64 (~> 0.2) faraday (>= 1.2.0, < 3.0) multi_json (~> 1.0) builder (3.3.0) bundler-audit (0.9.3) bundler (>= 1.2.0) thor (~> 1.0) byebug (12.0.0) carrierwave (3.1.2) activemodel (>= 6.0.0) activesupport (>= 6.0.0) addressable (~> 2.6) image_processing (~> 1.1) marcel (~> 1.0.0) ssrf_filter (~> 1.0) carrierwave-aws (1.6.0) aws-sdk-s3 (~> 1.0) carrierwave (>= 2.0, < 4) cgi (0.5.0) cgi (0.5.0-java) claide (1.1.0) claide-plugins (0.9.2) cork nap open4 (~> 1.3) clamav-client (3.2.0) cliver (0.3.2) cmdparse (3.0.7) coderay (1.1.3) coercible (1.0.0) descendants_tracker (~> 0.0.1) colored2 (3.1.2) combine_pdf (1.0.31) matrix ruby-rc4 (>= 0.1.5) committee (5.6.1) json_schema (~> 0.14, >= 0.14.3) openapi_parser (~> 2.0) rack (>= 1.5) committee-rails (0.9.0) actionpack (>= 6.0) activesupport (>= 6.0) committee (>= 5.1.0) railties (>= 6.0) concurrent-ruby (1.3.5) config (5.6.1) deep_merge (~> 1.2, >= 1.2.1) ostruct connection_pool (2.5.4) content_disposition (1.0.0) cork (0.3.0) colored2 (~> 3.1) coverband (6.1.6) base64 redis (>= 3.0) crack (1.0.1) bigdecimal rexml crass (1.0.6) csv (3.3.5) danger (9.5.3) base64 (~> 0.2) claide (~> 1.0) claide-plugins (>= 0.9.2) colored2 (>= 3.1, < 5) cork (~> 0.1) faraday (>= 0.9.0, < 3.0) faraday-http-cache (~> 2.0) git (>= 1.13, < 3.0) kramdown (>= 2.5.1, < 3.0) kramdown-parser-gfm (~> 1.0) octokit (>= 4.0) pstore (~> 0.1) terminal-table (>= 1, < 5) database_cleaner (2.1.0) database_cleaner-active_record (>= 2, < 3) database_cleaner-active_record (2.2.0) activerecord (>= 5.a) database_cleaner-core (~> 2.0.0) database_cleaner-core (2.0.1) datadog (2.22.0) datadog-ruby_core_source (~> 3.4, >= 3.4.1) libdatadog (~> 22.0.1.1.0) libddwaf (~> 1.25.1.1.0) logger msgpack datadog-ruby_core_source (3.4.1) date (3.5.0) date (3.5.0-java) date_time_precision (0.8.1) date_validator (0.12.0) activemodel (>= 3) activesupport (>= 3) debug (1.11.0) irb (~> 1.10) reline (>= 0.3.8) declarative (0.0.20) deep_merge (1.2.2) descendants_tracker (0.0.4) thread_safe (~> 0.3, >= 0.3.1) diff-lcs (1.6.2) docile (1.4.0) dogstatsd-ruby (5.7.1) domain_name (0.6.20240107) down (5.4.2) addressable (~> 2.8) drb (2.2.3) dry-configurable (1.3.0) dry-core (~> 1.1) zeitwerk (~> 2.6) dry-core (1.1.0) concurrent-ruby (~> 1.0) logger zeitwerk (~> 2.6) dry-inflector (1.2.0) dry-initializer (3.2.0) dry-logic (1.6.0) bigdecimal concurrent-ruby (~> 1.0) dry-core (~> 1.1) zeitwerk (~> 2.6) dry-schema (1.14.1) concurrent-ruby (~> 1.0) dry-configurable (~> 1.0, >= 1.0.1) dry-core (~> 1.1) dry-initializer (~> 3.2) dry-logic (~> 1.5) dry-types (~> 1.8) zeitwerk (~> 2.6) dry-struct (1.8.0) dry-core (~> 1.1) dry-types (~> 1.8, >= 1.8.2) ice_nine (~> 0.11) zeitwerk (~> 2.6) dry-types (1.8.3) bigdecimal (~> 3.0) concurrent-ruby (~> 1.0) dry-core (~> 1.0) dry-inflector (~> 1.0) dry-logic (~> 1.4) zeitwerk (~> 2.6) dry-validation (1.11.1) concurrent-ruby (~> 1.0) dry-core (~> 1.1) dry-initializer (~> 3.2) dry-schema (~> 1.14) zeitwerk (~> 2.6) einhorn (1.0.0) erb (6.0.0) erb (6.0.0-java) erubi (1.13.1) et-orbi (1.2.11) tzinfo ethon (0.18.0) ffi (>= 1.15.0) logger factory_bot (6.5.5) activesupport (>= 6.1.0) factory_bot_rails (6.5.1) factory_bot (~> 6.5) railties (>= 6.1.0) faker (3.5.3) i18n (>= 1.8.11, < 2) faraday (2.14.0) faraday-net_http (>= 2.0, < 3.5) json logger faraday-follow_redirects (0.3.0) faraday (>= 1, < 3) faraday-http-cache (2.5.1) faraday (>= 0.8) faraday-httpclient (2.0.2) httpclient (>= 2.2) faraday-multipart (1.1.1) multipart-post (~> 2.0) faraday-net_http (3.4.2) net-http (~> 0.5) faraday-retry (2.3.2) faraday (~> 2.0) faraday-typhoeus (1.1.0) faraday (~> 2.0) typhoeus (~> 1.4) faraday_curl (0.0.2) faraday (>= 0.9.0) fastimage (2.4.0) ffi (1.17.2) ffi (1.17.2-java) ffi-compiler (1.3.2) ffi (>= 1.15.5) rake fhir_dstu2_models (1.1.1) bcp47 (>= 0.3) date_time_precision (>= 0.8) mime-types (>= 3.0) nokogiri (>= 1.11.4) fhir_models (4.2.2) bcp47 (>= 0.3) date_time_precision (>= 0.8) mime-types (>= 3.0) nokogiri (>= 1.11.4) fhir_stu3_models (3.1.1) bcp47 (>= 0.3) date_time_precision (>= 0.8) mime-types (>= 3.0) nokogiri (>= 1.11.4) fiddle (1.1.8) fitbit_api (1.1.0) oauth2 (~> 2.0) flipper (1.3.6) concurrent-ruby (< 2) flipper-active_record (1.3.5) activerecord (>= 4.2, < 9) flipper (~> 1.3.5) flipper-active_support_cache_store (1.3.6) activesupport (>= 4.2, < 9) flipper (~> 1.3.6) flipper-ui (1.3.6) erubi (>= 1.0.0, < 2.0.0) flipper (~> 1.3.6) rack (>= 1.4, < 4) rack-protection (>= 1.5.3, < 5.0.0) rack-session (>= 1.0.2, < 3.0.0) sanitize (< 8) foreman (0.90.0) thor (~> 1.4) formatador (1.1.0) fugit (1.11.1) et-orbi (~> 1, >= 1.2.11) raabro (~> 1.4) fuubar (2.5.1) rspec-core (~> 3.0) ruby-progressbar (~> 1.4) gems (1.3.0) geom2d (0.4.1) git (2.3.3) activesupport (>= 5.0) addressable (~> 2.8) process_executer (~> 1.1) rchardet (~> 1.8) globalid (1.3.0) activesupport (>= 6.1) google-api-client (0.53.0) google-apis-core (~> 0.1) google-apis-generator (~> 0.1) google-apis-core (0.18.0) addressable (~> 2.5, >= 2.5.1) googleauth (~> 1.9) httpclient (>= 2.8.3, < 3.a) mini_mime (~> 1.0) mutex_m representable (~> 3.0) retriable (>= 2.0, < 4.a) google-apis-discovery_v1 (0.20.0) google-apis-core (>= 0.15.0, < 2.a) google-apis-generator (0.18.0) activesupport (>= 5.0) gems (~> 1.2) google-apis-core (>= 0.15.0, < 2.a) google-apis-discovery_v1 (~> 0.18) thor (>= 0.20, < 2.a) google-cloud-env (2.3.1) base64 (~> 0.2) faraday (>= 1.0, < 3.a) google-logging-utils (0.2.0) google-protobuf (4.33.2) bigdecimal rake (>= 13) google-protobuf (4.33.2-aarch64-linux-gnu) bigdecimal rake (>= 13) google-protobuf (4.33.2-java) bigdecimal ffi (~> 1) ffi-compiler (~> 1) rake (>= 13) google-protobuf (4.33.2-x86-mingw32) bigdecimal rake (>= 13) google-protobuf (4.33.2-x86_64-linux-gnu) bigdecimal rake (>= 13) googleauth (1.16.0) faraday (>= 1.0, < 3.a) google-cloud-env (~> 2.2) google-logging-utils (~> 0.1) jwt (>= 1.4, < 4.0) multi_json (~> 1.11) os (>= 0.9, < 2.0) signet (>= 0.16, < 2.a) gserver (0.0.1) guard (2.18.1) formatador (>= 0.2.4) listen (>= 2.7, < 4.0) lumberjack (>= 1.0.12, < 2.0) nenv (~> 0.1) notiffany (~> 0.0) pry (>= 0.13.0) shellany (~> 0.0) thor (>= 0.18.1) guard-compat (1.2.1) guard-rspec (4.7.3) guard (~> 2.1) guard-compat (~> 1.1) rspec (>= 2.99.0, < 4.0) guard-rubocop (1.5.0) guard (~> 2.0) rubocop (< 2.0) gyoku (1.4.0) builder (>= 2.1.2) rexml (~> 3.0) hana (1.3.7) hashdiff (1.2.1) hashery (2.1.2) hashie (5.0.0) hexapdf (1.4.1) cmdparse (~> 3.0, >= 3.0.3) geom2d (~> 0.4, >= 0.4.1) openssl (>= 2.2.1) strscan (>= 3.1.2) holidays (8.8.0) http (5.2.0) addressable (~> 2.8) base64 (~> 0.1) http-cookie (~> 1.0) http-form_data (~> 2.2) llhttp-ffi (~> 0.5.0) http-cookie (1.0.5) domain_name (~> 0.5) http-form_data (2.3.0) httpclient (2.8.3) httpi (4.0.4) base64 mutex_m nkf rack (>= 2.0, < 4) i18n (1.14.7) concurrent-ruby (~> 1.0) ice_nine (0.11.2) image_processing (1.14.0) mini_magick (>= 4.9.5, < 6) ruby-vips (>= 2.0.17, < 3) io-console (0.8.1) io-console (0.8.1-java) irb (1.15.3) pp (>= 0.6.0) rdoc (>= 4.0.0) reline (>= 0.4.2) iso_country_codes (0.7.8) jar-dependencies (0.5.5) jmespath (1.6.2) jruby-openssl (0.15.5-java) json (2.18.0) json (2.18.0-java) json-schema (5.2.2) addressable (~> 2.8) bigdecimal (~> 3.1) json_schema (0.21.0) json_schemer (2.5.0) bigdecimal hana (~> 1.3) regexp_parser (~> 2.0) simpleidn (~> 0.2) jsonapi-parser (0.1.1) jsonapi-serializer (2.2.0) activesupport (>= 4.2) jwe (1.1.1) base64 jwt (2.10.2) base64 karafka-core (2.5.8) karafka-rdkafka (>= 0.20.0) logger (>= 1.6.0) karafka-rdkafka (0.23.1) ffi (~> 1.17.1) json (> 2.0) logger mini_portile2 (~> 2.6) rake (> 12) karafka-rdkafka (0.23.1-aarch64-linux-gnu) ffi (~> 1.17.1) json (> 2.0) logger mini_portile2 (~> 2.6) rake (> 12) karafka-rdkafka (0.23.1-x86_64-linux-gnu) ffi (~> 1.17.1) json (> 2.0) logger mini_portile2 (~> 2.6) rake (> 12) kms_encrypted (1.8.0) activesupport (>= 7.2) base64 kramdown (2.5.1) rexml (>= 3.3.9) kramdown-parser-gfm (1.1.0) kramdown (~> 2.0) language_server-protocol (3.17.0.5) libdatadog (22.0.1.1.0) libdatadog (22.0.1.1.0-aarch64-linux) libdatadog (22.0.1.1.0-x86_64-linux) libddwaf (1.25.1.1.0) ffi (~> 1.0) libddwaf (1.25.1.1.0-aarch64-linux) ffi (~> 1.0) libddwaf (1.25.1.1.0-x86_64-linux) ffi (~> 1.0) lint_roller (1.1.0) liquid (5.11.0) bigdecimal strscan (>= 3.1.1) listen (3.8.0) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) llhttp-ffi (0.5.0) ffi-compiler (~> 1.0) rake (~> 13.0) lockbox (2.1.0) logger (1.7.0) loofah (2.24.1) crass (~> 1.0.2) nokogiri (>= 1.12.0) lumberjack (1.2.10) mail (2.9.0) logger mini_mime (>= 0.1.1) net-imap net-pop net-smtp marcel (1.0.4) matrix (0.4.2) memoist (0.16.2) method_source (1.1.0) mime-types (3.6.0) logger mime-types-data (~> 3.2015) mime-types-data (3.2025.0107) mimemagic (0.4.3) nokogiri (~> 1) rake mini_magick (5.3.1) logger mini_mime (1.1.5) mini_portile2 (2.8.9) minitest (5.26.2) mock_redis (0.51.0) redis (~> 5) msgpack (1.8.0) msgpack (1.8.0-java) multi_json (1.18.0) multi_xml (0.6.0) multipart-post (2.4.1) mutex_m (0.3.0) nap (1.1.0) nenv (0.3.0) net-http (0.9.1) uri (>= 0.11.1) net-imap (0.5.12) date net-protocol net-pop (0.1.2) net-protocol net-protocol (0.2.2) timeout net-sftp (4.0.0) net-ssh (>= 5.0.0, < 8.0.0) net-smtp (0.5.1) net-protocol net-ssh (7.2.0) nio4r (2.7.5) nio4r (2.7.5-java) nkf (0.2.0) nkf (0.2.0-java) nokogiri (1.18.10) mini_portile2 (~> 2.8.2) racc (~> 1.4) nokogiri (1.18.10-aarch64-linux-gnu) racc (~> 1.4) nokogiri (1.18.10-java) racc (~> 1.4) nokogiri (1.18.10-x86_64-linux-gnu) racc (~> 1.4) nori (2.7.1) bigdecimal notiffany (0.1.3) nenv (~> 0.1) shellany (~> 0.0) notifications-ruby-client (6.3.0) jwt (>= 1.5, < 4) oauth2 (2.0.9) faraday (>= 0.17.3, < 3.0) jwt (>= 1.0, < 3.0) multi_xml (~> 0.5) rack (>= 1.2, < 4) snaky_hash (~> 2.0) version_gem (~> 1.1) octokit (10.0.0) faraday (>= 1, < 3) sawyer (~> 0.9) oj (3.16.13) bigdecimal (>= 3.0) ostruct (>= 0.2) okcomputer (1.19.1) benchmark olive_branch (4.0.1) multi_json rails (>= 4.0) open4 (1.3.4) openapi_parser (2.3.1) openssl (3.3.1) openssl (3.3.1-java) jruby-openssl (~> 0.14) operating_hours (0.1.0) optimist (3.2.1) os (1.1.4) ostruct (0.6.3) ox (2.14.23) bigdecimal (>= 3.0) parallel (1.27.0) parallel_tests (5.5.0) parallel parser (3.3.10.0) ast (~> 2.4.1) racc patience_diff (1.2.0) optimist (~> 3.0) pdf-core (0.9.0) pdf-forms (1.5.2) cliver (~> 0.3.2) rexml (~> 3.2, >= 3.2.6) safe_shell (>= 1.0.3, < 2.0) pdf-inspector (1.3.0) pdf-reader (>= 1.0, < 3.0.a) pdf-reader (2.15.0) Ascii85 (>= 1.0, < 3.0, != 2.0.0) afm (>= 0.2.1, < 2) hashery (~> 2.0) ruby-rc4 ttfunk pg (1.6.2) pg_query (6.1.0) google-protobuf (>= 3.25.3) pg_search (2.3.7) activerecord (>= 6.1) activesupport (>= 6.1) pkce_challenge (1.0.0) pp (0.6.3) prettyprint prawn (2.4.0) pdf-core (~> 0.9.0) ttfunk (~> 1.7) prawn-markup (1.1.0) nokogiri prawn prawn-table prawn-table (0.2.2) prawn (>= 1.3.0, < 3.0.0) prettyprint (0.2.0) prism (1.6.0) process_executer (1.3.0) pry (0.15.2) coderay (~> 1.1) method_source (~> 1.0) pry (0.15.2-java) coderay (~> 1.1) method_source (~> 1.0) spoon (~> 0.0) pry-byebug (3.11.0) byebug (~> 12.0) pry (>= 0.13, < 0.16) pstore (0.2.0) psych (5.2.6) date stringio psych (5.2.6-java) date jar-dependencies (>= 0.1.7) public_suffix (7.0.0) puma (7.1.0) nio4r (~> 2.0) puma (7.1.0-java) nio4r (~> 2.0) pundit (2.5.2) activesupport (>= 3.0.0) raabro (1.4.0) racc (1.8.1) racc (1.8.1-java) rack (2.2.21) rack-attack (6.8.0) rack (>= 1.0, < 4) rack-cors (2.0.2) rack (>= 2.0.0) rack-protection (3.2.0) base64 (>= 0.1.0) rack (~> 2.2, >= 2.2.4) rack-session (1.0.2) rack (< 3) rack-test (2.2.0) rack (>= 1.3) rack-timeout (0.7.0) rack-vcr (0.1.6) vcr (>= 2.9) rackup (1.0.1) rack (< 3) webrick rails (7.2.3) actioncable (= 7.2.3) actionmailbox (= 7.2.3) actionmailer (= 7.2.3) actionpack (= 7.2.3) actiontext (= 7.2.3) actionview (= 7.2.3) activejob (= 7.2.3) activemodel (= 7.2.3) activerecord (= 7.2.3) activestorage (= 7.2.3) activesupport (= 7.2.3) bundler (>= 1.15.0) railties (= 7.2.3) rails-dom-testing (2.3.0) activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) rails-html-sanitizer (1.6.2) loofah (~> 2.21) nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) rails-session_cookie (0.3.0) rails (>= 4.0) rails_semantic_logger (4.18.0) rack railties (>= 5.1) semantic_logger (~> 4.16) railties (7.2.3) actionpack (= 7.2.3) activesupport (= 7.2.3) cgi irb (~> 1.13) rackup (>= 1.0.0) rake (>= 12.2) thor (~> 1.0, >= 1.2.2) tsort (>= 0.2) zeitwerk (~> 2.6) rainbow (3.1.1) rake (13.3.1) ransack (4.4.1) activerecord (>= 7.2) activesupport (>= 7.2) i18n rb-fsevent (0.11.2) rb-inotify (0.10.1) ffi (~> 1.0) rchardet (1.9.0) rdoc (6.15.1) erb psych (>= 4.0.0) tsort redis (5.4.1) redis-client (>= 0.22.0) redis-client (0.26.1) connection_pool redis-namespace (1.11.0) redis (>= 4) regexp_parser (2.11.3) reline (0.6.3) io-console (~> 0.5) representable (3.2.0) declarative (< 0.1.0) trailblazer-option (>= 0.1.1, < 0.2.0) uber (< 0.2.0) request_store (1.7.0) rack (>= 1.4) require_all (3.0.0) restforce (8.0.0) faraday (>= 1.1.0, < 3.0.0) faraday-follow_redirects (<= 0.3.0, < 1.0.0) faraday-multipart (>= 1.0.0, < 2.0.0) faraday-net_http (< 4.0.0) hashie (>= 1.2.0, < 6.0) jwt (>= 1.5.6) retriable (3.1.2) rexml (3.4.4) rgeo (3.0.1) rgeo-activerecord (8.0.0) activerecord (>= 7.0) rgeo (>= 3.0) rgeo-geojson (2.2.0) multi_json (~> 1.15) rgeo (>= 1.0.0) roo (3.0.0) base64 (~> 0.2) csv (~> 3) logger (~> 1) nokogiri (~> 1) rubyzip (>= 3.0.0, < 4.0.0) rspec (3.13.0) rspec-core (~> 3.13.0) rspec-expectations (~> 3.13.0) rspec-mocks (~> 3.13.0) rspec-core (3.13.6) rspec-support (~> 3.13.0) rspec-expectations (3.13.5) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) rspec-instrumentation-matcher (0.0.9) activesupport rspec-expectations rspec-its (2.0.0) rspec-core (>= 3.13.0) rspec-expectations (>= 3.13.0) rspec-mocks (3.13.5) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) rspec-rails (8.0.2) actionpack (>= 7.2) activesupport (>= 7.2) railties (>= 7.2) rspec-core (~> 3.13) rspec-expectations (~> 3.13) rspec-mocks (~> 3.13) rspec-support (~> 3.13) rspec-retry (0.6.2) rspec-core (> 3.3) rspec-sidekiq (5.2.0) rspec-core (~> 3.0) rspec-expectations (~> 3.0) rspec-mocks (~> 3.0) sidekiq (>= 5, < 9) rspec-support (3.13.6) rspec_junit_formatter (0.6.0) rspec-core (>= 2, < 4, != 2.12.0) rswag-specs (2.17.0) activesupport (>= 5.2, < 8.2) json-schema (>= 2.2, < 7.0) railties (>= 5.2, < 8.2) rspec-core (>= 2.14) rswag-ui (2.17.0) actionpack (>= 5.2, < 8.2) railties (>= 5.2, < 8.2) rtesseract (3.1.4) rubocop (1.81.7) json (~> 2.3) language_server-protocol (~> 3.17.0.2) lint_roller (~> 1.1.0) parallel (~> 1.10) parser (>= 3.3.0.2) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 2.9.3, < 3.0) rubocop-ast (>= 1.47.1, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 2.4.0, < 4.0) rubocop-ast (1.48.0) parser (>= 3.3.7.2) prism (~> 1.4) rubocop-capybara (2.22.1) lint_roller (~> 1.1) rubocop (~> 1.72, >= 1.72.1) rubocop-factory_bot (2.28.0) lint_roller (~> 1.1) rubocop (~> 1.72, >= 1.72.1) rubocop-junit-formatter (0.1.4) rubocop-rails (2.33.4) activesupport (>= 4.2.0) lint_roller (~> 1.1) rack (>= 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.44.0, < 2.0) rubocop-rspec (3.8.0) lint_roller (~> 1.1) rubocop (~> 1.81) rubocop-rspec_rails (2.32.0) lint_roller (~> 1.1) rubocop (~> 1.72, >= 1.72.1) rubocop-rspec (~> 3.5) rubocop-thread_safety (0.7.3) lint_roller (~> 1.1) rubocop (~> 1.72, >= 1.72.1) rubocop-ast (>= 1.44.0, < 2.0) ruby-progressbar (1.13.0) ruby-rc4 (0.1.5) ruby-saml (1.18.1) nokogiri (>= 1.13.10) rexml ruby-vips (2.2.3) ffi (~> 1.12) logger rubyzip (3.2.2) rufus-scheduler (3.9.2) fugit (~> 1.1, >= 1.11.1) safe_shell (1.1.0) sanitize (7.0.0) crass (~> 1.0.2) nokogiri (>= 1.16.8) savon (2.15.1) akami (~> 1.2) builder (>= 2.1.2) gyoku (~> 1.2) httpi (>= 4, < 5) mail (~> 2.5) nokogiri (>= 1.8.1) nori (~> 2.4) wasabi (>= 3.7, < 6) sawyer (0.9.2) addressable (>= 2.3.5) faraday (>= 0.17.3, < 3) script_utils (0.0.4) securerandom (0.4.1) seedbank (0.5.0) rake (>= 10.0) semantic_logger (4.17.0) concurrent-ruby (~> 1.0) sentry-ruby (5.28.1) bigdecimal concurrent-ruby (~> 1.0, >= 1.0.2) shellany (0.0.1) shoulda-matchers (7.0.1) activesupport (>= 7.1) shrine (3.6.0) content_disposition (~> 1.0) down (~> 5.1) sidekiq (7.3.7) connection_pool (>= 2.3.0) logger rack (>= 2.2.4) redis-client (>= 0.22.2) sign_in_service (0.4.0) faraday (~> 2.7) jwt (~> 2.8) signet (0.21.0) addressable (~> 2.8) faraday (>= 0.17.5, < 3.a) jwt (>= 1.5, < 4.0) multi_json (~> 1.10) simplecov (0.22.0) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.4) simpleidn (0.2.3) slack-notify (0.6.0) faraday (>= 0.9) json (>= 1.8) snaky_hash (2.0.1) hashie version_gem (~> 1.1, >= 1.1.1) socksify (1.8.1) spoon (0.0.6) ffi ssrf_filter (1.2.0) staccato (0.5.3) statsd-instrument (3.9.10) stringio (3.1.8) strong_migrations (2.5.0) activerecord (>= 7.1) strscan (3.1.5) strscan (3.1.5-java) super_diff (0.18.0) attr_extras (>= 6.2.4) diff-lcs patience_diff swagger-blocks (3.0.0) terminal-table (4.0.0) unicode-display_width (>= 1.1.1, < 4) thor (1.4.0) thread_safe (0.3.6) thread_safe (0.3.6-java) tilt (2.3.0) timecop (0.9.10) timeout (0.4.4) trailblazer-option (0.1.2) tsort (0.2.0) ttfunk (1.7.0) typhoeus (1.4.1) ethon (>= 0.9.0) tzinfo (2.0.6) concurrent-ruby (~> 1.0) tzinfo-data (1.2025.2) tzinfo (>= 1.0.0) uber (0.1.0) unicode-display_width (3.2.0) unicode-emoji (~> 4.1) unicode-emoji (4.1.0) uri (1.1.1) useragent (0.16.11) utf8-cleaner (1.0.0) activesupport vcr (6.3.1) base64 version_gem (1.1.3) virtus (2.0.0) axiom-types (~> 0.1) coercible (~> 1.0) descendants_tracker (~> 0.0, >= 0.0.3) warden (1.2.9) rack (>= 2.0.9) warden-github (1.3.2) activesupport (> 3.0) octokit (> 2.1.0) warden (> 1.0) wasabi (5.0.3) addressable faraday (>= 1.9, < 3) nokogiri (>= 1.13.9) waterdrop (2.8.15) karafka-core (>= 2.4.9, < 3.0.0) karafka-rdkafka (>= 0.23.1) zeitwerk (~> 2.3) web-console (4.2.1) actionview (>= 6.0.0) activemodel (>= 6.0.0) bindex (>= 0.4.0) railties (>= 6.0.0) webmock (3.26.1) addressable (>= 2.8.0) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) webrick (1.9.2) websocket-driver (0.8.0) base64 websocket-extensions (>= 0.1.0) websocket-driver (0.8.0-java) base64 websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) will_paginate (4.0.1) with_advisory_lock (7.0.2) activerecord (>= 7.2) zeitwerk (>= 2.7) xmldsig (0.3.2) nokogiri xmlenc (0.8.0) activemodel (>= 3.0.0) activesupport (>= 3.0.0) nokogiri (>= 1.6.0, < 2.0.0) xmlmapper (>= 0.7.3) xmlmapper (0.8.1) nokogiri (~> 1.11) yard (0.9.38) zeitwerk (2.7.4) PLATFORMS aarch64-linux java ruby x64-mingw32 x86-mingw32 x86-mswin32 x86_64-linux DEPENDENCIES aasm accredited_representative_portal! activerecord-import activerecord-postgis-adapter addressable apivore! appeals_api! apps_api! ask_va_api! avro avs! awesome_print aws-msk-iam-sasl-signer (~> 0.1.1) aws-sdk-kms aws-sdk-s3 (~> 1) aws-sdk-sns (~> 1) banners! betamocks! bgs_ext! blind_index blueprinter bootsnap bpds! brakeman breakers bundler-audit burials! byebug carrierwave carrierwave-aws check_in! claims_api! claims_evidence_api! clamav-client combine_pdf committee-rails config connect_vbms! coverband csv danger database_cleaner datadog date_validator debts_api! debug decision_reviews! dependents_benefits! dependents_verification! dhp_connected_devices! digital_forms_api! dogstatsd-ruby dry-struct dry-types employment_questionnaires! ethon (>= 0.13.0) facilities_api! factory_bot_rails faker faraday (~> 2.14) faraday-follow_redirects faraday-httpclient faraday-multipart faraday-retry faraday-typhoeus faraday_curl fastimage fhir_client! fitbit_api flipper flipper-active_record flipper-active_support_cache_store flipper-ui foreman fuubar google-api-client google-apis-core google-apis-generator google-protobuf googleauth govdelivery-tms! guard-rspec guard-rubocop gyoku hashdiff hexapdf holidays httpclient ice_nine income_and_assets! income_limits! increase_compensation! iso_country_codes ivc_champva! json json-schema json_schemer jsonapi-parser jsonapi-serializer jwe jwt kms_encrypted liquid lockbox mail meb_api! medical_expense_reports! memoist mimemagic mini_magick mobile! mock_redis mocked_authentication! my_health! net-sftp nkf nokogiri notifications-ruby-client octokit oj okcomputer olive_branch operating_hours ox parallel parallel_tests pdf-forms pdf-inspector pdf-reader pensions! pg pg_query pg_search pkce_challenge prawn (~> 2.4.0) prawn-markup prawn-table pry-byebug puma pundit rack (~> 2.2.21) rack-attack rack-cors rack-test (= 2.2.0) rack-timeout rack-vcr rails (~> 7.2.3) rails-session_cookie rails_semantic_logger rainbow ransack redis redis-namespace representation_management! request_store require_all restforce rgeo-geojson roo rspec-instrumentation-matcher rspec-its rspec-rails rspec-retry rspec-sidekiq rspec_junit_formatter rswag-specs rswag-ui rtesseract rubocop rubocop-capybara rubocop-factory_bot rubocop-junit-formatter rubocop-rails rubocop-rspec rubocop-rspec_rails rubocop-thread_safety ruby-saml rubyzip rufus-scheduler savon seedbank sentry-ruby (= 5.28.1) shoulda-matchers shrine sidekiq sidekiq-ent! sidekiq-pro! sign_in_service simple_forms_api! simplecov slack-notify sob! socksify staccato statsd-instrument strong_migrations super_diff survivors_benefits! swagger-blocks test_user_dashboard! timecop travel_pay! ttfunk (~> 1.7.0) tzinfo-data utf8-cleaner va_notify! vaos! vass! vba_documents! vcr veteran! vets_json_schema! virtus vre! vye! warden-github waterdrop web-console webmock webrick will_paginate with_advisory_lock yard RUBY VERSION ruby 3.3.6p108 BUNDLED WITH 2.5.23
0
code_files
code_files/vets-api-private/docker-compose.yml
version: '3.8' x-app: &common build: args: BUNDLE_ENTERPRISE__CONTRIBSYS__COM: "${BUNDLE_ENTERPRISE__CONTRIBSYS__COM}" context: . environment: BUNDLE_ENTERPRISE__CONTRIBSYS__COM: "${BUNDLE_ENTERPRISE__CONTRIBSYS__COM}" SETTINGS__DATABASE_URL: "postgis://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DATABASE:-vets_api_development}?pool=4" SETTINGS__TEST_DATABASE_URL: "postgis://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DATABASE:-vets_api_test}" SETTINGS__REDIS__APP_DATA__URL: "redis://redis:6379" SETTINGS__REDIS__SIDEKIQ__URL: "redis://redis:6379" SETTINGS__REDIS__RAILS_CACHE__URL: "redis://redis:6379" image: vets-api:${DOCKER_IMAGE:-latest} volumes: - "../vets-api-mockdata:/cache" - .:/app:cached - shared-vol:/tmp working_dir: /app depends_on: - clamav - postgres - redis links: - clamav - postgres - redis services: clamav: image: clamav/clamav ports: - 33100:3310 volumes: - shared-vol:/vets-api platform: linux/amd64 redis: image: redis:6.2-alpine ports: - 63790:6379 postgres: command: postgres -c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all -c max_connections=200 environment: POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-password}" POSTGRES_USER: "${POSTGRES_USER:-postgres}" PGDATA: /tmp image: postgis/postgis:14-3.3-alpine ports: - 54320:5432 volumes: - ./data:/var/lib/postgresql/data:cached web: <<: *common ports: - 3000:3000 worker: <<: *common command: bundle exec sidekiq -q critical,4 -q tasker,3 -q default,2 -q low,1 volumes: shared-vol:
0
code_files
code_files/vets-api-private/docker-compose.test.yml
version: '3.4' services: redis: image: ${ECR_REGISTRY_WITH_SLASH}redis:6.2-alpine postgres: image: ${ECR_REGISTRY_WITH_SLASH}postgis/postgis:14-3.3-alpine command: postgres -c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all -c max_connections=200 environment: POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-password}" POSTGRES_USER: "${POSTGRES_USER:-postgres}" web: build: context: . args: sidekiq_license: "${BUNDLE_ENTERPRISE__CONTRIBSYS__COM}" userid: "${VETS_API_USER_ID}" image: "vets-api:${DOCKER_IMAGE:-latest}" volumes: - ".:/app" - test_bundle:/usr/local/bundle environment: SETTINGS__DATABASE_URL: "postgis://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DATABASE:-vets_api_development}?pool=4" SETTINGS__TEST_DATABASE_URL: "postgis://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DATABASE:-vets_api_test}" SETTINGS__REDIS__APP_DATA__URL: "redis://redis:6379" SETTINGS__REDIS__SIDEKIQ__URL: "redis://redis:6379" POSTGRES_HOST: "${POSTGRES_HOST:-postgres}" POSTGRES_PORT: "${POSTGRES_PORT:-5432}" POSTGRES_USER: "${POSTGRES_USER:-postgres}" POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-password}" CI: "true" RAILS_ENV: test CC_TEST_REPORTER_ID: '0c396adc254b0317e2c3a89a1c929fd61270b133c944d3e9c0f13b3937a7ce45' CHANGE_ID: "${CHANGE_ID}" GIT_URL: "${GIT_URL}" JENKINS_URL: "${JENKINS_URL}" DANGER_GITHUB_API_TOKEN: "${DANGER_GITHUB_API_TOKEN}" DISABLE_BOOTSNAP: "true" depends_on: - postgres - redis links: - postgres - redis volumes: test_bundle:
0
code_files
code_files/vets-api-private/Brewfile
brew 'clamav' # anti-virus scanner brew 'coreutils' # gnu coreutils brew 'docker-compose' brew 'imagemagick@6' brew 'memcached' brew 'poppler' # pdf rendering brew 'redis' brew 'gs' # Note: Installing psql@14 may be difficult to complete using Homebrew. See # docs/setup/native.md#OSX for more information. Included here for completeness. # # brew 'postgresql@14' brew 'pex' # package installer for psql brew 'postgis' # gis functions for psql brew 'xpdf' # for pdfinfo executable
0
code_files
code_files/vets-api-private/Procfile
web: bundle exec puma -p 3000 -C ./config/puma.rb job: bundle exec sidekiq -q critical,4 -q tasker,3 -q default,2 -q low,1
0
code_files
code_files/vets-api-private/SECURITY.md
# Security Policy The Department of Veterans Affairs participates in a Responsible Vulnerability Disclosure Program through Bugcrowd. Please report any security-related issues using our [Bugcrowd program](https://bugcrowd.com/va-vdp). If your Bugcrowd submission is related to an open GH issue, please include that issue ID in the description field of your disclosure. But, please do not open new security-related issues. If you are a developer and have concerns, you can reach out on our internal Slack channel #platform-security.
0
code_files
code_files/vets-api-private/.rspec_parallel
--color --require spec_helper --format documentation <% if ENV['CI'] %> --format RspecJunitFormatter --out log/rspec<%= ENV['TEST_ENV_NUMBER'] %>.xml <% end %>
0
code_files
code_files/vets-api-private/catalog-info.yaml
apiVersion: backstage.io/v1alpha1 kind: System metadata: title: Veterans API name: vets-api description: This project provides common APIs for applications that live on VA.gov (formerly vets.gov APIs). annotations: github.com/project-slug: department-of-veterans-affairs/vets-api # project slug for the VSP sentry project sentry.io/project-slug: platform-api backstage.io/techdocs-ref: dir:. tags: - ruby - rails links: - url: https://app.ddog-gov.com/sb/f327ad72-c02a-11ec-a50a-da7ad0900007-6611d274b64e8b40b8db40fd6c94d2b5 title: Datadog - VSP - Breakers icon: dashboard - url: https://app.ddog-gov.com/sb/f327ad72-c02a-11ec-a50a-da7ad0900007-ce3061a8ca28b90d49fcb95d4444b080 title: Datadog - VSP Utility - Backend Service Report icon: dashboard - url: https://app.ddog-gov.com/sb/f327ad72-c02a-11ec-a50a-da7ad0900007-a1dfad12b43924de9033ad82897aadab title: Datadog - VSP - External Service Performance Indicators icon: dashboard - url: https://grafana.vfs.va.gov/ title: Grafana icon: dashboard - url: http://sentry.vfs.va.gov/organizations/vsp/ title: Sentry - VSP icon: dashboard - url: https://api.va.gov/sidekiq title: Sidekiq UI (Production) icon: dashboard - url: http://sidekiq-ui-dev.vfs.va.gov/ title: Sidekiq UI (Dev Environment Isolated from Veterans API) icon: dashboard - url: http://sidekiq-ui-staging.vfs.va.gov/ title: Sidekiq UI (Staging Environment Isolated from Veterans API) icon: dashboard spec: owner: platform-console-services domain: platform-and-vfs
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/reencode_images.rb
# frozen_string_literal: true module ReencodeImages extend ActiveSupport::Concern include CarrierWave::MiniMagick included do process :reencode end def reencode unless file.content_type == 'application/pdf' manipulate! do |img| img.strip img.format(img.type) img end end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/evss_claim_document_uploader_base.rb
# frozen_string_literal: true class EVSSClaimDocumentUploaderBase < CarrierWave::Uploader::Base include SetAWSConfig include ValidatePdf include CarrierWave::MiniMagick include ConvertFileType version :converted, if: :tiff_or_incorrect_extension? do process(convert: :jpg, if: :tiff?) def full_filename(original_name_for_file) name = "converted_#{original_name_for_file}" extension = CarrierWave::SanitizedFile.new(nil).send(:split_extension, original_name_for_file)[1] mimemagic_object = self.class.inspect_binary file if self.class.incorrect_extension?(extension:, mimemagic_object:) extension = self.class.extensions_from_mimemagic_object(mimemagic_object).max return "#{name.gsub('.', '_')}.#{extension}" end name end end before :store, :validate_file_size def size_range (1.byte)...(99.megabytes) end def extension_allowlist %w[pdf gif png tiff tif jpeg jpg bmp txt] end def max_file_size_non_pdf 50.megabytes end # EVSS will split PDF's larger than 50mb before sending to VBA who has a limit of 50mb. so, # PDF's can be larger than other files def validate_file_size(file) if file.content_type != 'application/pdf' && file.size > max_file_size_non_pdf raise CarrierWave::IntegrityError, I18n.t(:'errors.messages.max_size_error', max_size: '50MB') end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/lighthouse_document_uploader_base.rb
# frozen_string_literal: true class LighthouseDocumentUploaderBase < CarrierWave::Uploader::Base include SetAWSConfig include ValidatePdf include CarrierWave::MiniMagick include ConvertFileType include UploaderVirusScan version :converted, if: :tiff_or_incorrect_extension? do process(convert: :jpg, if: :tiff?) def full_filename(original_name_for_file) name = "converted_#{original_name_for_file}" extension = CarrierWave::SanitizedFile.new(nil).send(:split_extension, original_name_for_file)[1] mimemagic_object = self.class.inspect_binary file if self.class.incorrect_extension?(extension:, mimemagic_object:) extension = self.class.extensions_from_mimemagic_object(mimemagic_object).max return "#{name.gsub('.', '_')}.#{extension}" end name end end before :store, :validate_file_size def size_range (1.byte)...(150.megabytes) end def extension_allowlist %w[pdf gif png tiff tif jpeg jpg bmp txt] end def max_file_size_non_pdf 50.megabytes end # Lighthouse will split PDF's larger than 50mb before sending to VBA who has a limit of 50mb. so, # PDF's can be larger than other files def validate_file_size(file) if file.content_type != 'application/pdf' && file.size > max_file_size_non_pdf raise CarrierWave::IntegrityError, I18n.t(:'errors.messages.max_size_error', max_size: '50MB') end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/validate_pdf.rb
# frozen_string_literal: true require 'pdf_info' module ValidatePdf extend ActiveSupport::Concern included do before :store, :validate_pdf end def validate(temp_file) metadata = PdfInfo::Metadata.read(temp_file) if metadata.encrypted? raise Common::Exceptions::UnprocessableEntity.new(detail: I18n.t('errors.messages.uploads.pdf.locked'), source: 'ValidatePdf') end temp_file.rewind rescue PdfInfo::MetadataReadError raise Common::Exceptions::UnprocessableEntity.new(detail: I18n.t('errors.messages.uploads.pdf.invalid'), source: 'ValidatePdf') end def validate_pdf(file) # Skip when the pdf file is generated by DisabilityCompensationJob return if file.respond_to?(:fast_track) temp_file = file.tempfile return unless File.extname(temp_file) == '.pdf' && !temp_file.nil? validate temp_file end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/convert_file_type.rb
# frozen_string_literal: true module ConvertFileType extend ActiveSupport::Concern class_methods do def tiff?(mimemagic_object: nil, carrier_wave_sanitized_file: nil) return mimemagic_object.type == 'image/tiff' if mimemagic_object carrier_wave_sanitized_file&.content_type == 'image/tiff' end def incorrect_extension?(extension:, mimemagic_object:) extension = extension.to_s.downcase true_extensions = extensions_from_mimemagic_object(mimemagic_object).map(&:downcase) true_extensions.present? && !extension.in?(true_extensions) end def extensions_from_mimemagic_object(mimemagic_object) mimemagic_object&.extensions || [] end def inspect_binary(carrier_wave_sanitized_file) file_obj = carrier_wave_sanitized_file&.to_file file_obj && MimeMagic.by_magic(file_obj) ensure file_obj.close if file_obj.respond_to? :close end end def converted_exists? converted.present? && converted.file.exists? end def final_filename if converted_exists? converted.file.filename else file.filename end end def read_for_upload if converted_exists? converted.read else read end end private def tiff?(carrier_wave_sanitized_file) self.class.tiff?( carrier_wave_sanitized_file:, mimemagic_object: self.class.inspect_binary(carrier_wave_sanitized_file) ) end def tiff_or_incorrect_extension?(carrier_wave_sanitized_file) mimemagic_object = self.class.inspect_binary carrier_wave_sanitized_file self.class.tiff?( carrier_wave_sanitized_file:, mimemagic_object: ) || self.class.incorrect_extension?( extension: carrier_wave_sanitized_file.extension, mimemagic_object: ) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/supporting_evidence_attachment_uploader.rb
# frozen_string_literal: true # Files uploaded as part of a form526 submission that will be sent to EVSS upon form submission. class SupportingEvidenceAttachmentUploader < EVSSClaimDocumentUploaderBase before :store, :log_transaction_start after :store, :log_transaction_complete def initialize(guid, _unused = nil) # carrierwave allows only 2 arguments, which they will pass onto # different versions by calling the initialize function again # so the _unused argument is necessary super @guid = guid # defaults to CarrierWave::Storage::File if not AWS if Rails.env.production? set_aws_config( Settings.evss.s3.aws_access_key_id, Settings.evss.s3.aws_secret_access_key, Settings.evss.s3.region, Settings.evss.s3.bucket ) end end def store_dir raise 'missing guid' if @guid.blank? "disability_compensation_supporting_form/#{@guid}" end def log_transaction_start(uploaded_file = nil) log = { process_id: Process.pid, filesize: uploaded_file.try(:size), upload_start: Time.current } Rails.logger.info(log) end def log_transaction_complete(uploaded_file = nil) log = { process_id: Process.pid, filesize: uploaded_file.try(:size), upload_complete: Time.current } Rails.logger.info(log) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/log_metrics.rb
# frozen_string_literal: true module LogMetrics extend ActiveSupport::Concern KEY_PREFIX = 'api.upload.' included do after(:store, :log_metrics) end def log_metrics(file) class_name = self.class.to_s.gsub('::', '_').underscore class_prefix = "#{KEY_PREFIX}#{class_name}" args = [ "#{class_prefix}.size", file.size ] kw_args = {} file.content_type.tap do |content_type| next if content_type.blank? kw_args[:tags] = ["content_type:#{content_type.split('/')[1]}"] end StatsD.measure(*args, **kw_args) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/uploader_virus_scan.rb
# frozen_string_literal: true require 'common/file_helpers' require 'common/virus_scan' module UploaderVirusScan extend ActiveSupport::Concern class VirusFoundError < StandardError end included do before(:store, :validate_virus_free) end def validate_virus_free(file) return unless Rails.env.production? temp_file_path = Common::FileHelpers.generate_clamav_temp_file(file.read) result = Common::VirusScan.scan(temp_file_path) File.delete(temp_file_path) # Common::VirusScan result will return true or false unless result # unless safe file.delete raise VirusFoundError, "Virus Found + #{temp_file_path}" end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/evss_claim_document_uploader.rb
# frozen_string_literal: true # Files that will be associated with a previously submitted claim, from the Claim Status tool class EVSSClaimDocumentUploader < EVSSClaimDocumentUploaderBase def initialize(user_uuid, ids) # carrierwave allows only 2 arguments, which they will pass onto # different versions by calling the initialize function again, # that's why i put all ids in the 2nd argument instead of adding a 3rd argument super @user_uuid = user_uuid @ids = ids set_storage_options! end def store_dir store_dir = "evss_claim_documents/#{@user_uuid}" @ids.compact.each do |id| store_dir += "/#{id}" end store_dir end def move_to_cache false end private def set_storage_options! if Settings.evss.s3.uploads_enabled set_aws_config( Settings.evss.s3.aws_access_key_id, Settings.evss.s3.aws_secret_access_key, Settings.evss.s3.region, Settings.evss.s3.bucket ) else self.class.storage = :file end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/async_processing.rb
# frozen_string_literal: true module AsyncProcessing extend ActiveSupport::Concern included do after(:store, :process_file) end def process_file(_file) ProcessFileJob.perform_async(self.class::PROCESSING_CLASS.to_s, store_dir, filename) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/set_aws_config.rb
# frozen_string_literal: true module SetAWSConfig def set_aws_config(aws_access_key_id, aws_secret_access_key, region, bucket) self.aws_credentials = { access_key_id: aws_access_key_id, secret_access_key: aws_secret_access_key, region: } self.aws_acl = 'private' self.aws_bucket = bucket self.aws_attributes = { server_side_encryption: 'AES256' } self.class.storage = :aws end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/decision_review_evidence_attachment_uploader.rb
# frozen_string_literal: true # Files uploaded as part of a Notice of Disagreement submission that will be sent to Lighthouse upon form submission. class DecisionReviewEvidenceAttachmentUploader < CarrierWave::Uploader::Base include SetAWSConfig def size_range (1.byte)...(100_000_000.bytes) end def extension_allowlist %w[pdf] end def initialize(decision_review_guid) super @decision_review_guid = decision_review_guid set_storage_options! end def store_dir raise 'missing guid' if @decision_review_guid.blank? "decision_review/#{@decision_review_guid}" end def set_storage_options! s3_settings = Settings.decision_review.s3 # defaults to CarrierWave::Storage::File if not AWS unless a real aws_access_key_id is set if s3_settings.aws_access_key_id.present? set_aws_config( s3_settings.aws_access_key_id, s3_settings.aws_secret_access_key, s3_settings.region, s3_settings.bucket ) end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/preneed_attachment_uploader.rb
# frozen_string_literal: true class PreneedAttachmentUploader < CarrierWave::Uploader::Base include SetAWSConfig include UploaderVirusScan include CarrierWave::MiniMagick def size_range (1.byte)...(25.megabytes) end process(convert: 'pdf', if: :not_pdf?) def initialize(guid) super @guid = guid if Rails.env.production? set_aws_config( Settings.preneeds.s3.aws_access_key_id, Settings.preneeds.s3.aws_secret_access_key, Settings.preneeds.s3.region, Settings.preneeds.s3.bucket ) end end def extension_allowlist %w[pdf jpg jpeg png] end def store_dir raise 'missing guid' if @guid.blank? "preneed_attachments/#{@guid}" end def filename "#{super.chomp(File.extname(super))}.pdf" end private def not_pdf?(file) file.content_type != 'application/pdf' end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/lighthouse_document_uploader.rb
# frozen_string_literal: true # Files that will be associated with a previously submitted claim, from the Claim Status tool class LighthouseDocumentUploader < LighthouseDocumentUploaderBase def initialize(icn, ids) # carrierwave allows only 2 arguments, which they will pass onto # different versions by calling the initialize function again, # that's why i put all ids in the 2nd argument instead of adding a 3rd argument super @icn = icn @ids = ids set_storage_options! end def store_dir store_dir = "lighthouse_documents/#{@icn}" @ids.compact.each do |id| store_dir += "/#{id}" end store_dir end def move_to_cache false end private def set_storage_options! if Settings.lighthouse.s3.uploads_enabled set_aws_config( Settings.lighthouse.s3.aws_access_key_id, Settings.lighthouse.s3.aws_secret_access_key, Settings.lighthouse.s3.region, Settings.lighthouse.s3.bucket ) else self.class.storage = :file end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/hca_attachment_uploader.rb
# frozen_string_literal: true class HCAAttachmentUploader < CarrierWave::Uploader::Base include SetAWSConfig include UploaderVirusScan include CarrierWave::MiniMagick def size_range (1.byte)...(10.megabytes) end process(convert: 'jpg', if: :png?) process(convert: 'jpg', if: :heic?) def initialize(guid) super @guid = guid if Rails.env.production? set_aws_config( Settings.hca.s3.aws_access_key_id, Settings.hca.s3.aws_secret_access_key, Settings.hca.s3.region, Settings.hca.s3.bucket ) end end # accepted by enrollment system: PDF,WORD,JPG,RTF def extension_allowlist if Flipper.enabled?(:hca_heif_attachments_enabled) %w[pdf doc docx jpg jpeg rtf png heic heif] else %w[pdf doc docx jpg jpeg rtf png] end end def store_dir 'hca_attachments' end def filename @guid end private def png?(file) file.content_type == 'image/png' end def heic?(file) file.content_type =~ %r{^image/(heic|heif)$} end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/uploaders/vets_shrine.rb
# frozen_string_literal: true require 'shrine/plugins/storage_from_config' require 'shrine/plugins/validate_virus_free' class VetsShrine < Shrine plugin :validation_helpers plugin :metadata_attributes plugin :rack_file plugin :validate_virus_free end
0
code_files/vets-api-private/app/uploaders
code_files/vets-api-private/app/uploaders/form_upload/uploader.rb
# frozen_string_literal: true require 'shrine/plugins/validate_unlocked_pdf' require 'shrine/plugins/validate_pdf_page_count' require 'shrine/plugins/validate_correct_form' class FormUpload::Uploader < VetsShrine plugin :storage_from_config, settings: Settings.shrine.claims plugin :activerecord, callbacks: false plugin :validate_unlocked_pdf plugin :store_dimensions plugin :validate_pdf_page_count plugin :validate_correct_form Attacher.validate do validate_virus_free validate_max_size 25.megabytes validate_min_size 1.kilobyte validate_mime_type_inclusion %w[image/jpg image/jpeg image/png application/pdf] validate_max_width 5000 if get.width validate_max_height 10_000 if get.height validate_unlocked_pdf validate_pdf_page_count(max_pages: record.max_pages, min_pages: record.min_pages) validate_correct_form(form_id: record.form_id) end end
0
code_files/vets-api-private/app/uploaders/simple_forms_api
code_files/vets-api-private/app/uploaders/simple_forms_api/form_remediation/uploader.rb
# frozen_string_literal: true require 'simple_forms_api/form_remediation/configuration/base' module SimpleFormsApi module FormRemediation class Uploader < CarrierWave::Uploader::Base include UploaderVirusScan def initialize(directory:, config:) raise 'The S3 directory is missing.' if directory.blank? raise 'The configuration is missing.' unless config @config = config @directory = directory super() set_storage_options! end def size_range (1.byte)...(150.megabytes) end # Allowed file types, including those specific to benefits intake def extension_allowlist %w[bmp csv gif jpeg jpg json pdf png tif tiff txt zip] end def store_dir @directory end def store!(file) raise 'Invalid file object provided for upload. Skipping.' if file.nil? || !file.respond_to?(:filename) super(file) rescue Aws::S3::Errors::ServiceError => e Rails.logger.error("Upload failed for #{file.filename}. Enqueuing for retry.", e) UploadRetryJob.perform_async(file, @directory, config) rescue RuntimeError => e config.handle_error('An error occurred while uploading the file.', e) end def get_s3_link(file_path, filename = nil) filename ||= File.basename(file_path) s3_obj(file_path).presigned_url( :get, expires_in: 30.minutes.to_i, response_content_disposition: "attachment; filename=\"#{filename}\"" ) end def get_s3_file(from_path, to_path) s3_obj(from_path).get(response_target: to_path) rescue Aws::S3::Errors::NoSuchKey nil rescue => e config.handle_error('An error occurred while downloading the file.', e) end private attr_reader :config def s3_obj(file_path) client = Aws::S3::Client.new(region: config.s3_settings.region) resource = Aws::S3::Resource.new(client:) resource.bucket(config.s3_settings.bucket).object(file_path) end def set_storage_options! settings = config.s3_settings self.aws_credentials = { region: settings.region } self.aws_acl = 'private' self.aws_bucket = settings.bucket self.aws_attributes = { server_side_encryption: 'AES256' } self.class.storage = :aws end end end end
0
code_files/vets-api-private/app/uploaders
code_files/vets-api-private/app/uploaders/claim_documentation/uploader.rb
# frozen_string_literal: true require 'shrine/plugins/validate_unlocked_pdf' # Shrine logic for claim evidence uploads, optimistically named so # that they cover any sort of claim documentation in a sane way. class ClaimDocumentation::Uploader < VetsShrine plugin :storage_from_config, settings: Settings.shrine.claims plugin :activerecord, callbacks: false plugin :validate_unlocked_pdf plugin :store_dimensions Attacher.validate do validate_virus_free validate_max_size 100.megabytes validate_min_size 1.kilobyte validate_mime_type_inclusion %w[image/jpg image/jpeg image/png application/pdf] validate_max_width 5616 if get.width validate_max_height 7272 if get.height validate_unlocked_pdf end end
0
code_files/vets-api-private/app/uploaders
code_files/vets-api-private/app/uploaders/form1010cg/poa_uploader.rb
# frozen_string_literal: true module Form1010cg class PoaUploader < CarrierWave::Uploader::Base include SetAWSConfig include LogMetrics include UploaderVirusScan storage :aws attr_reader :store_dir def initialize(form_attachment_guid) super set_aws_config( Settings.form_10_10cg.poa.s3.aws_access_key_id, Settings.form_10_10cg.poa.s3.aws_secret_access_key, Settings.form_10_10cg.poa.s3.region, Settings.form_10_10cg.poa.s3.bucket ) @store_dir = form_attachment_guid end def extension_allowlist %w[jpg jpeg png pdf] end def content_type_allowlist %w[image/jpg image/jpeg image/png application/pdf] end def size_range (1.byte)...(10.megabytes) end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form0781_state_snapshot_job.rb
# frozen_string_literal: true # Log information about Form 0781 submissions to populate an admin facing Datadog dashboard class Form0781StateSnapshotJob include Sidekiq::Job sidekiq_options retry: false STATSD_PREFIX = 'form526.form0781.state.snapshot' def perform if Flipper.enabled?(:disability_compensation_0781_stats_job) write_0781_snapshot else Rails.logger.info('0781 state snapshot job disabled', class: self.class.name, message: 'Flipper flag disability_compensation_0781_stats_job is disabled') end rescue => e Rails.logger.error('Error logging 0781 state snapshot', class: self.class.name, message: e.try(:message)) end def write_0781_snapshot state_as_counts.each do |description, count| StatsD.gauge("#{STATSD_PREFIX}.#{description}", count) end end def state_as_counts @state_as_counts ||= {}.tap do |abbreviation| snapshot_state.each do |dp, ids| abbreviation[:"#{dp}_count"] = ids.count end end end def snapshot_state @snapshot_state ||= load_snapshot_state end def load_snapshot_state { # New 0781 form metrics new_0781_in_progress_forms:, new_0781_submissions:, new_0781_successful_submissions:, new_0781_failed_submissions:, new_0781_primary_path_submissions:, new_0781_secondary_path_submissions:, # Old 0781 form metrics old_0781_in_progress_forms:, old_0781_submissions:, old_0781_successful_submissions:, old_0781_failed_submissions: } end # Helper methods for new 0781 form metrics def new_0781_in_progress_forms InProgressForm.where(form_id: '21-526EZ').where("metadata->>'sync_modern0781_flow' = 'true'").pluck(:id) end def new_0781_submissions_saved_claims @new_0781_submissions_saved_claims ||= SavedClaim::DisabilityCompensation::Form526AllClaim.where.not(metadata: nil) end def new_0781_submissions new_0781_submissions_saved_claims.pluck(:id) end def new_0781_successful_submissions Form526Submission.where( saved_claim_id: new_0781_submissions_saved_claims.pluck(:id) ).where('submitted_claim_id IS NOT NULL OR backup_submitted_claim_id IS NOT NULL').pluck(:id) end def new_0781_failed_submissions Form526Submission.where( saved_claim_id: new_0781_submissions_saved_claims.pluck(:id) ).where('submitted_claim_id IS NULL AND backup_submitted_claim_id IS NULL').pluck(:id) end def new_0781_primary_path_submissions Form526Submission.where( saved_claim_id: new_0781_submissions_saved_claims.pluck(:id) ).where.not(submitted_claim_id: nil).pluck(:id) end def new_0781_secondary_path_submissions Form526Submission.where( saved_claim_id: new_0781_submissions_saved_claims.pluck(:id) ).where.not(backup_submitted_claim_id: nil).pluck(:id) end # Helper methods for old 0781 form metrics def old_0781_in_progress_forms InProgressForm.where(form_id: '21-526EZ').where.not("metadata::jsonb ? 'sync_modern0781_flow'").pluck(:id) end def old_0781_submissions_saved_claims @old_0781_submissions_saved_claims ||= SavedClaim::DisabilityCompensation::Form526AllClaim.where( metadata: nil, created_at: new_0781_submissions_saved_claims.first.created_at..Time.current ) end def old_0781_submissions old_0781_submissions_saved_claims.pluck(:id) end def old_0781_successful_submissions Form526Submission.where( saved_claim_id: old_0781_submissions_saved_claims.pluck(:id) ).where('submitted_claim_id IS NOT NULL OR backup_submitted_claim_id IS NOT NULL').pluck(:id) end def old_0781_failed_submissions Form526Submission.where( saved_claim_id: old_0781_submissions_saved_claims.pluck(:id) ).where('submitted_claim_id IS NULL AND backup_submitted_claim_id IS NULL').pluck(:id) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_confirmation_email_job.rb
# frozen_string_literal: true require 'va_notify/service' class Form526ConfirmationEmailJob include Sidekiq::Job sidekiq_options expires_in: 1.day STATSD_ERROR_NAME = 'worker.form526_confirmation_email.error' STATSD_SUCCESS_NAME = 'worker.form526_confirmation_email.success' def perform(personalization_parameters) @notify_client ||= VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key) @template_id ||= Settings.vanotify.services.va_gov.template_id.form526_confirmation_email @notify_client.send_email( email_address: personalization_parameters['email'], template_id: @template_id, personalisation: { 'claim_id' => personalization_parameters['submitted_claim_id'], 'date_submitted' => personalization_parameters['date_submitted'], 'date_received' => personalization_parameters['date_received'], 'first_name' => personalization_parameters['first_name'] } ) StatsD.increment(STATSD_SUCCESS_NAME) rescue => e handle_errors(e) end def handle_errors(ex) Rails.logger.error('Form526ConfirmationEmailJob error', error: ex) StatsD.increment(STATSD_ERROR_NAME) raise ex if ex.status_code.between?(500, 599) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/process_file_job.rb
# frozen_string_literal: true class ProcessFileJob include Sidekiq::Job def perform(processing_class, store_dir, filename) uploader = processing_class.constantize.new(store_dir, filename) uploader.retrieve_from_store!(filename) old_file = uploader.file uploader.store!(old_file) old_file.delete end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/external_services_status_job.rb
# frozen_string_literal: true class ExternalServicesStatusJob include Sidekiq::Job sidekiq_options(retry: false) def perform ExternalServicesRedis::Status.new.fetch_or_cache end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_status_polling_job.rb
# frozen_string_literal: true require 'benefits_intake_service/service' class Form526StatusPollingJob include Sidekiq::Job sidekiq_options retry: false STATS_KEY = 'api.benefits_intake.submission_status' MAX_BATCH_SIZE = 1000 attr_reader :max_batch_size def initialize(max_batch_size: MAX_BATCH_SIZE) @max_batch_size = max_batch_size @total_handled = 0 end def perform Rails.logger.info('Beginning Form 526 Intake Status polling') submissions.in_batches(of: max_batch_size) do |batch| batch_ids = batch.pluck(:backup_submitted_claim_id).flatten response = api_to_poll.get_bulk_status_of_uploads(batch_ids) handle_response(response) end Rails.logger.info('Form 526 Intake Status polling complete', total_handled: @total_handled) rescue => e Rails.logger.error('Error processing 526 Intake Status batch', class: self.class.name, message: e.message) end private def api_to_poll @api_to_poll ||= BenefitsIntakeService::Service.new end def submissions @submissions ||= Form526Submission.pending_backup end def handle_response(response) response.body['data']&.each do |submission| status = submission.dig('attributes', 'status') form_submission = Form526Submission.find_by(backup_submitted_claim_id: submission['id']) handle_submission(status, form_submission) @total_handled += 1 end end def handle_submission(status, form_submission) submission_id = form_submission.id if %w[error expired].include? status log_result('failure', submission_id) form_submission.rejected! notify_veteran(submission_id) elsif status == 'vbms' log_result('true_success', submission_id) form_submission.accepted! elsif status == 'success' log_result('paranoid_success', submission_id) form_submission.paranoid_success! # Send Received Email once Backup Path is successful! if Flipper.enabled?(:disability_526_send_received_email_from_backup_path) form_submission.send_received_email('Form526StatusPollingJob#handle_submission paranoid_success!') end else Rails.logger.info( 'Unknown or incomplete status returned from Benefits Intake API for 526 submission', status:, submission_id: ) end end def log_result(result, submission_id) StatsD.increment("#{STATS_KEY}.526.#{result}") StatsD.increment("#{STATS_KEY}.all_forms.#{result}") Rails.logger.warn('Form526StatusPollingJob submission failure', { result:, submission_id: }) if result == 'failure' end def notify_veteran(submission_id) if Flipper.enabled?(:form526_send_backup_submission_polling_failure_email_notice) Form526SubmissionFailureEmailJob.perform_async(submission_id, Time.now.utc.to_s) end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_paranoid_success_polling_job.rb
# frozen_string_literal: true require 'benefits_intake_service/service' class Form526ParanoidSuccessPollingJob include Sidekiq::Job sidekiq_options retry: false MAX_BATCH_SIZE = 1000 attr_reader :max_batch_size, :change_totals, :total_checked def initialize(max_batch_size: MAX_BATCH_SIZE) @max_batch_size = max_batch_size @total_checked = 0 @change_totals = {} end def perform Rails.logger.info('Beginning Form 526 paranoid_success polling') submissions.in_batches(of: max_batch_size) do |batch| batch_ids = batch.pluck(:backup_submitted_claim_id).flatten response = api_to_poll.get_bulk_status_of_uploads(batch_ids) handle_response(response) end Rails.logger.info('Form 526 paranoid_success polling complete', total_checked:, change_totals:) rescue => e Rails.logger.error('Error processing 526 paranoid_success batch', class: self.class.name, message: e.message) end private def api_to_poll @api_to_poll ||= BenefitsIntakeService::Service.new end def submissions @submissions ||= Form526Submission.paranoid_success_type end def handle_response(response) response.body['data']&.each do |submission| status = submission.dig('attributes', 'status') id = submission['id'] form_submission = Form526Submission.find_by(backup_submitted_claim_id: id) handle_submission(form_submission, status, id) @total_checked += 1 end end def handle_submission(form_submission, status, id) if %w[error expired].include?(status) form_submission.rejected! log_result('failed', id) elsif status == 'vbms' form_submission.accepted! log_result('marked as true success', id) elsif status == 'processing' form_submission.update!(backup_submitted_claim_status: nil) log_result('reverted to processing', id) elsif status != 'success' Rails.logger.error('Paranoid Success transitioned to unknown status', status:, submission_id: id) form_submission.rejected! end count_change(status) unless status == 'success' end def count_change(status) change_totals[status] ||= 0 change_totals[status] += 1 end def log_result(change, submission_id) Rails.logger.info('Paranoid Success submission changed', submission_id:, change:) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/user_actions_cleanup_job.rb
# frozen_string_literal: true class UserActionsCleanupJob include Sidekiq::Job sidekiq_options unique_for: 30.minutes, retry: false EXPIRATION_TIME = 1.year def perform UserAction.where(created_at: ...EXPIRATION_TIME.ago).delete_all end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/va_notify_email_job.rb
# frozen_string_literal: true require 'vets/shared_logging' ########################################################################################### # This class is deprecated in favor of modules/va_notify/app/sidekiq/va_notify/email_job.rb # Use that one instead. ########################################################################################### # TODO: Remove this class class VANotifyEmailJob include Sidekiq::Job include Vets::SharedLogging # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 def perform(email, template_id, personalisation = nil) notify_client = VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key) notify_client.send_email( **{ email_address: email, template_id:, personalisation: }.compact ) rescue VANotify::Error => e if e.status_code == 400 log_exception_to_sentry( e, { args: { template_id:, personalisation: } }, { error: :va_notify_email_job } ) log_exception_to_rails(e) else raise e end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/feature_cleaner_job.rb
# frozen_string_literal: true class FeatureCleanerJob include Sidekiq::Job def perform Rails.logger.info "FeatureCleanerJob Removing: #{removed_features.join(', ')}" # removed_features.each do |feature| # Flipper.remove(feature) # end end private def removed_features @removed_features ||= Flipper.features.collect(&:name) - FLIPPER_FEATURE_CONFIG['features'].keys end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/benefits_intake_remediation_status_job.rb
# frozen_string_literal: true require 'lighthouse/benefits_intake/service' # Reporting job for Lighthouse Benefit Intake Failures # @see https://vagov.ddog-gov.com/dashboard/8zk-ja2-xvm/benefits-intake-submission-remediation-report class BenefitsIntakeRemediationStatusJob include Sidekiq::Job sidekiq_options retry: false # metrics key STATS_KEY = 'api.benefits_intake.remediation_status' # job batch size BATCH_SIZE = Settings.lighthouse.benefits_intake.report.batch_size || 1000 # create an instance def initialize(batch_size: BATCH_SIZE) @batch_size = batch_size @total_handled = 0 end # search all submissions for outstanding failures # poll LH endpoint to see if status has changed (case if endpoint had an error initially) # report stats on submissions, grouped by form-type def perform(form_id = nil) Rails.logger.info('BenefitsIntakeRemediationStatusJob started') form_submissions = FormSubmission.includes(:form_submission_attempts) failures = outstanding_failures(form_submissions.all) # filter running this job to a specific form_id/form_type @form_id = form_id failures.select! { |f| f.form_type == form_id } if form_id batch_process(failures) unless failures.empty? submission_audit Rails.logger.info('BenefitsIntakeRemediationStatusJob ended', total_handled:) rescue => e # catch and log, but not re-raise to avoid sidekiq exhaustion alerts Rails.logger.error('BenefitsIntakeRemediationStatusJob ERROR', class: self.class.name, message: e.message) end private attr_reader :batch_size, :total_handled, :form_id # determine if a claim has an outstanding failure # each claim can have multiple FormSubmission, which can have multiple FormSubmissionAttempt # conflate these and search for a non-failure, which rejects the claim from the list # # @param submissions [Array<FormSubmission>] # def outstanding_failures(submissions) failures = submissions.group_by(&:saved_claim_id) failures.map do |_claim_id, fs| fs.sort_by!(&:created_at) attempts = fs.map(&:form_submission_attempts).flatten.sort_by(&:created_at) not_failure = attempts.find { |att| att.aasm_state != 'failure' } not_failure ? nil : fs.last end.compact end # perform a bulk_status check in Lighthouse to retrieve current statuses # a processing error will abort the job (no retries) # # @param failures [Array<FormSubmission>] submissions with only 'failure' statuses # def batch_process(failures) intake_service = BenefitsIntake::Service.new failures.each_slice(batch_size) do |batch| batch_uuids = batch.map { |submission| submission.latest_attempt&.benefits_intake_uuid } Rails.logger.info('BenefitsIntakeRemediationStatusJob processing batch', batch_uuids:) response = intake_service.bulk_status(uuids: batch_uuids) raise response.body unless response.success? next unless (data = response.body['data']) handle_response(data, batch) end end # process response from Lighthouse to update outstanding failures # # @param response_date [Hash] Lighthouse Benefits Intake API response # @param failure_batch [Array<FormSubmission>] current batch being processed # def handle_response(response_data, failure_batch) response_data.each do |submission| uuid = submission['id'] form_submission = failure_batch.find do |submission_from_db| submission_from_db.latest_attempt&.benefits_intake_uuid == uuid end form_submission.form_type form_submission_attempt = form_submission.form_submission_attempts.last # https://developer.va.gov/explore/api/benefits-intake/docs status = submission.dig('attributes', 'status') lighthouse_updated_at = submission.dig('attributes', 'updated_at') if status == 'vbms' # submission was successfully uploaded into a Veteran's eFolder within VBMS form_submission_attempt.update(lighthouse_updated_at:) form_submission_attempt.remediate! end @total_handled = total_handled + 1 end end # gather metrics - grouped by form type # @see #submission_audit_metrics def submission_audit # requery form_submissions in case there was an update form_submissions = FormSubmission.includes(:form_submission_attempts) form_submission_groups = form_submissions.all.group_by(&:form_type) form_submission_groups.each do |form_type, submissions| next if form_id && form_id != form_type fs_saved_claim_ids = submissions.map(&:saved_claim_id).uniq.compact next unless (earliest = fs_saved_claim_ids.min) claims = SavedClaim.where(form_id: form_type).where('id >= ?', earliest) claim_ids = claims.map(&:id).uniq unsubmitted = claim_ids - fs_saved_claim_ids orphaned = fs_saved_claim_ids - claim_ids failures = outstanding_failures(submissions) failures.map! do |fs| { claim_id: fs.saved_claim_id, uuid: fs.latest_attempt.benefits_intake_uuid, error_message: fs.latest_attempt.error_message } end submission_audit_metrics(form_type, unsubmitted, orphaned, failures) end end # report metrics # # @param form_type [String] the saved_claim form id # @param unsubmitted [Array<Integer>] list of SavedClaim ids that do not have a FormSubmission record # @param orphaned [Array<Integer>] list of saved_claim_ids with a FormSubmission, but no SavedClaim # @param failures [Array<Hash>] list of outstanding failures (claim.id, benefits_intake_uuid, error_message) def submission_audit_metrics(form_type, unsubmitted, orphaned, failures) audit_log = "BenefitsIntakeRemediationStatusJob submission audit #{form_type}" StatsD.gauge("#{STATS_KEY}.unsubmitted_claims", unsubmitted.length, tags: ["form_id:#{form_type}"]) StatsD.gauge("#{STATS_KEY}.orphaned_submissions", orphaned.length, tags: ["form_id:#{form_type}"]) StatsD.gauge("#{STATS_KEY}.outstanding_failures", failures.length, tags: ["form_id:#{form_type}"]) Rails.logger.info(audit_log, form_id: form_type, unsubmitted:, orphaned:, failures:) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/export_breaker_status.rb
# frozen_string_literal: true class ExportBreakerStatus include Sidekiq::Job def perform Breakers.client.services.each do |service| # trying to avoid double-negative with open/closed here, up of 1 is "closed" or "up" up = service.latest_outage && !service.latest_outage.ended? ? 0 : 1 StatsD.gauge("api.external_service.#{service.name}.up", up) end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/load_average_days_for_claim_completion_job.rb
# frozen_string_literal: true class LoadAverageDaysForClaimCompletionJob include Sidekiq::Job # this will go away once the file publishing is setup. def connection @conn ||= Faraday.new('https://www.va.gov/') do |faraday| faraday.use :breakers faraday.use Faraday::Response::RaiseError faraday.request :json faraday.response :json, content_type: /\bjson/ faraday.adapter Faraday.default_adapter end end AVERAGE_DAYS_REGEX = /([0-9]{1,3}(\.[0-9]{1,2})) days/ def load_average_days rtn = connection.get('/disability/after-you-file-claim/').body matches = AVERAGE_DAYS_REGEX.match(rtn) if matches.present? && matches.length >= 1 rec = AverageDaysForClaimCompletion.new rec.average_days = matches[1].to_f rec.save! else logger.error('Unable to load average days, possibly the page has changed and the regex no longer matches!') end rescue Faraday::ClientError => e logger.error("Unable to load average days: #{e.message}") end def perform logger.info('Beginning: LoadAverageDaysForClaimCompletionJob') load_average_days logger.info('Completing: LoadAverageDaysForClaimCompletionJob') end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_submitted_email_job.rb
# frozen_string_literal: true require 'va_notify/service' class Form526SubmittedEmailJob include Sidekiq::Job sidekiq_options expires_in: 1.day STATSD_ERROR_NAME = 'worker.form526_submitted_email.error' STATSD_SUCCESS_NAME = 'worker.form526_submitted_email.success' def perform(personalization_parameters) @notify_client ||= VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key) @template_id ||= Settings.vanotify.services.va_gov.template_id.form526_submitted_email @notify_client.send_email( email_address: personalization_parameters['email'], template_id: @template_id, personalisation: { 'claim_id' => personalization_parameters['submitted_claim_id'], 'date_submitted' => personalization_parameters['date_submitted'], 'first_name' => personalization_parameters['first_name'] } ) StatsD.increment(STATSD_SUCCESS_NAME) rescue => e handle_errors(e) end def handle_errors(ex) Rails.logger.error('Form526SubmittedEmailJob error', error: ex) StatsD.increment(STATSD_ERROR_NAME) raise ex if ex.status_code.between?(500, 599) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_submission_processing_report_job.rb
# frozen_string_literal: true # Log information about Form526Submission state to populate an admin facing Datadog dashboard class Form526SubmissionProcessingReportJob include Sidekiq::Job sidekiq_options retry: false attr_reader :start_date, :end_date END_DATE = Time.zone.today.beginning_of_day START_DATE = END_DATE - 1.week def initialize(start_date: START_DATE, end_date: END_DATE) @start_date = start_date @end_date = end_date end def perform write_as_log rescue => e Rails.logger.error('Error logging 526 state data', class: self.class.name, message: e.try(:message), start_date:, end_date:) end def write_as_log Rails.logger.info('Form 526 State Data', state_log: state_as_counts, start_date:, end_date:) end def state_as_counts @state_as_counts ||= {}.tap do |abbreviation| timeboxed_state.each do |dp, ids| abbreviation[:"#{dp}_count"] = ids.count end end end def timeboxed_state @timeboxed_state ||= load_timeboxed_state end def load_timeboxed_state { timeboxed: timeboxed_submissions.pluck(:id).sort, timeboxed_primary_successes: timeboxed_submissions.accepted_to_primary_path.pluck(:id).sort, timeboxed_exhausted_primary_job: timeboxed_submissions.with_exhausted_primary_jobs.pluck(:id).sort, timeboxed_exhausted_backup_job: timeboxed_submissions.with_exhausted_backup_jobs.pluck(:id).sort, timeboxed_incomplete_type: timeboxed_submissions.incomplete_type.pluck(:id).sort } end def sub_arel @sub_arel ||= Form526Submission.arel_table end def timeboxed_submissions @timeboxed_submissions ||= Form526Submission .where(sub_arel_created_at.gt(start_date)) .where(sub_arel_created_at.lt(end_date)) end def sub_arel_created_at sub_arel[:created_at] end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/va_notify_dd_email_job.rb
# frozen_string_literal: true class VANotifyDdEmailJob include Sidekiq::Job # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 STATSD_ERROR_NAME = 'worker.direct_deposit_confirmation_email.error' STATSD_SUCCESS_NAME = 'worker.direct_deposit_confirmation_email.success' def self.send_to_emails(user_emails) if user_emails.present? user_emails.each do |email| perform_async(email) end else Rails.logger.info( event: 'direct_deposit_confirmation_skipped', reason: 'missing_email', context: { feature: 'direct_deposit', job: name }, message: 'No email address present for Direct Deposit confirmation email' ) end end def perform(email) notify_client = VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key) template_id = Settings.vanotify.services.va_gov.template_id[:direct_deposit] notify_client.send_email( email_address: email, template_id: ) StatsD.increment(STATSD_SUCCESS_NAME) rescue => e handle_errors(e) end def handle_errors(exception) StatsD.increment(STATSD_ERROR_NAME) Rails.logger.error( message: 'Direct Deposit confirmation email job failed', error: exception.message, backtrace: exception.backtrace.take(5), source: self.class.name ) raise exception if exception.status_code.between?(500, 599) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/transactional_email_analytics_job.rb
# frozen_string_literal: true class TransactionalEmailAnalyticsJob include Sidekiq::Job sidekiq_options(unique_for: 30.minutes, retry: false) def initialize unless FeatureFlipper.send_email? raise Common::Exceptions::ParameterMissing.new( 'GovDelivery token or server', detail: 'It should be configured in settings.yml' ) end if Settings.google_analytics.tracking_id.blank? raise Common::Exceptions::ParameterMissing.new( 'Google Analytics tracking ID', detail: 'It should be configured in settings.yml' ) end @tracker = Staccato.tracker(Settings.google_analytics.tracking_id) @time_range_start = 1445.minutes.ago @time_range_end = 5.minutes.ago end def perform page = 0 loop do page += 1 relevant_emails(page).each do |mailer, emails| emails.each do |email| eval_email(email, mailer) end end break if we_should_break? end end # mailers descendant of TransactionalEmailMailer # these are declared explicitly because `.descendants` doesn't play well with zeitwerk autoloading def self.mailers [ StemApplicantConfirmationMailer, SchoolCertifyingOfficialsMailer, DirectDepositMailer, StemApplicantScoMailer, StemApplicantDenialMailer ] end private def we_should_break? Time.zone.parse(@all_emails.collection.last.created_at) < @time_range_start || @all_emails.collection.count < 50 end def relevant_emails(page) @all_emails = govdelivery_client.email_messages.get( page:, sort_by: 'created_at', sort_order: 'DESC', page_size: 50 ) grouped_emails = TransactionalEmailAnalyticsJob.mailers.index_with { |_mailer| [] } @all_emails.collection.each do |email| created_at = Time.zone.parse(email.created_at) if created_at > @time_range_start && created_at <= @time_range_end && email.status == 'completed' TransactionalEmailMailer.descendants.each_with_object(grouped_emails) do |mailer, grouped| grouped[mailer] << email if email.subject == mailer::SUBJECT end end end grouped_emails end def govdelivery_client @govdelivery_client ||= GovDelivery::TMS::Client.new( Settings.govdelivery.token, api_root: "https://#{Settings.govdelivery.server}", logger: ENV['CI'] == 'true' ? nil : logger ) end def eval_email(email, mailer) email.failed.get event_params = { category: 'email', non_interactive: true, campaign_name: mailer::GA_CAMPAIGN_NAME, campaign_medium: 'email', campaign_source: 'gov-delivery', document_title: email.subject, document_path: mailer::GA_DOCUMENT_PATH, label: mailer::GA_LABEL } @tracker.event(event_params.merge(action: 'completed')) @tracker.event(event_params.merge(action: 'failed')) if email.failed.collection.count.positive? end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/in_progress_form_cleaner.rb
# frozen_string_literal: true class InProgressFormCleaner include Sidekiq::Job def perform forms = InProgressForm.where('expires_at < ?', Time.now.utc) form_counts = forms.group(:form_id).count form_counts.each do |form_id, count| if count.positive? StatsD.increment("worker.in_progress_form_cleaner.#{form_id.downcase.tr('-', '_')}_deleted", count) end end logger.info("Deleting #{forms.count} old saved forms") forms.delete_all end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/email_verification_job.rb
# frozen_string_literal: true require 'sidekiq/attr_package' class EmailVerificationJob include Sidekiq::Job include Vets::SharedLogging sidekiq_options retry: 5 # exponential backoff, retries for ~17 mins STATS_KEY = 'api.vanotify.email_verification' sidekiq_retries_exhausted do |msg, _ex| job_id = msg['jid'] job_class = msg['class'] error_class = msg['error_class'] error_message = msg['error_message'] args = msg['args'] template_type = args[0] if args&.length&.positive? cache_key = args[1] if args&.length&.>(1) message = "#{job_class} retries exhausted" Rails.logger.error(message, { job_id:, error_class:, error_message:, template_type: }) StatsD.increment("#{STATS_KEY}.retries_exhausted") # Clean up the cache key if it exists and retries are exhausted if cache_key.present? begin Sidekiq::AttrPackage.delete(cache_key) rescue Sidekiq::AttrPackageError => e Rails.logger.warn('Failed to clean up AttrPackage after retries exhausted', { cache_key:, error: e.message }) end end end # TODO: Add back email_address param when ready to send real emails # rubocop:disable Metrics/MethodLength def perform(template_type, cache_key) return unless Flipper.enabled?(:auth_exp_email_verification_enabled) # Retrieve PII data from Redis using the cache key personalisation_data = Sidekiq::AttrPackage.find(cache_key) unless personalisation_data Rails.logger.error('EmailVerificationJob failed: Missing personalisation data in Redis', { template_type:, cache_key_present: cache_key.present? }) raise ArgumentError, 'Missing personalisation data in Redis' end # Build personalisation hash based on template type and available data personalisation = build_personalisation(template_type, personalisation_data) validate_personalisation!(template_type, personalisation) Rails.logger.info('Email verification sent (logging only - not actually sent)', { template_type: }) # TODO: Replace above log with actual VA Notify call: # notify_client = VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key, callback_options(template_type)) # notify_client.send_email( # { # email_address: personalisation_data[:email], # template_id: get_template_id(template_type), # personalisation: # }.compact # ) StatsD.increment("#{STATS_KEY}.success") # Clean up the cache after successful processing Sidekiq::AttrPackage.delete(cache_key) rescue ArgumentError => e # Log application logic errors for debugging - these go to Sidekiq's Dead Job Queue (no retries) Rails.logger.error('EmailVerificationJob validation failed', { error: e.message, template_type: }) raise e rescue Sidekiq::AttrPackageError => e # Log AttrPackage errors as application logic errors (no retries) Rails.logger.error('EmailVerificationJob AttrPackage error', { error: e.message, template_type: }) raise ArgumentError, e.message rescue => e # Log and count service/operational failures # Service failures get retried by Sidekiq (5xx errors), 400s don't retry Rails.logger.error('EmailVerificationJob failed', { error: e.message, template_type: }) StatsD.increment("#{STATS_KEY}.failure") raise e end # rubocop:enable Metrics/MethodLength private def build_personalisation(template_type, personalisation_data) case template_type when 'initial_verification', 'annual_verification', 'email_change_verification' { 'verification_link' => personalisation_data[:verification_link], 'first_name' => personalisation_data[:first_name], 'email_address' => personalisation_data[:email] } when 'verification_success' { 'first_name' => personalisation_data[:first_name] } else raise ArgumentError, 'Unknown template type' end end def callback_options(template_type) { callback_klass: 'EmailVerificationCallback', callback_metadata: { statsd_tags: { service: 'vagov-profile-email-verification', function: "#{template_type}_email" } } } end def get_template_id(template_type) case template_type when 'initial_verification', 'annual_verification' Settings.vanotify.services.va_gov.template_id.contact_email_address_confirmation_needed_email when 'email_change_verification' Settings.vanotify.services.va_gov.template_id.contact_email_address_change_confirmation_needed_email when 'verification_success' Settings.vanotify.services.va_gov.template_id.contact_email_address_confirmed_email else raise ArgumentError, 'Unknown template type' end end def validate_personalisation!(template_type, personalisation) raise ArgumentError, 'Personalisation cannot be nil' if personalisation.nil? case template_type when 'initial_verification', 'annual_verification', 'email_change_verification' validate_required_fields!(personalisation, %w[verification_link first_name email_address]) when 'verification_success' validate_required_fields!(personalisation, %w[first_name]) else raise ArgumentError, 'Unknown template type' end end def validate_required_fields!(personalisation, required_fields) missing_fields = required_fields.select { |field| personalisation[field].blank? } unless missing_fields.empty? raise ArgumentError, "Missing required personalisation fields: #{missing_fields.join(', ')}" end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/delete_in_progress_form_job.rb
# frozen_string_literal: true class DeleteInProgressFormJob include Sidekiq::Job sidekiq_options retry: 5 def perform(form_id, user_uuid) return unless user_uuid InProgressForm.find_by(form_id:, user_uuid:)&.destroy end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_submission_failed_email_job.rb
# frozen_string_literal: true require 'va_notify/service' class Form526SubmissionFailedEmailJob include Sidekiq::Job sidekiq_options expires_in: 1.day STATSD_ERROR_NAME = 'worker.form526_submission_failed_email.error' STATSD_SUCCESS_NAME = 'worker.form526_submission_failed_email.success' def perform(personalization_parameters) @notify_client ||= VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key) @template_id ||= Settings.vanotify.services.va_gov.template_id.form526_submission_failed_email @notify_client.send_email( email_address: personalization_parameters['email'], template_id: @template_id, personalisation: { 'claim_id' => personalization_parameters['submitted_claim_id'], 'date_submitted' => personalization_parameters['date_submitted'], 'first_name' => personalization_parameters['first_name'] } ) StatsD.increment(STATSD_SUCCESS_NAME) rescue => e handle_errors(e) end def handle_errors(ex) Rails.logger.error('Form526SubmissionFailedEmailJob error', error: ex) StatsD.increment(STATSD_ERROR_NAME) raise ex if ex.respond_to?(:status_code) && ex.status_code.between?(500, 599) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form_pdf_change_detection_job.rb
# frozen_string_literal: true require 'forms/client' # FormPdfChangeDetectionJob # # This Sidekiq job monitors VA form PDF revisions by comparing current SHA256 checksums # against cached values to detect when forms have been updated. # # Why: # - Enables automated tracking of form revisions for compliance and version management. # - Provides metrics and logging for form change analytics and auditing. # - Helps maintain awareness of form updates that may affect user experience. # # How: # - Fetches current form data and SHA256 checksums from the VA Lighthouse Forms API. # - Compares current checksums against cached values from previous runs. # - Logs detected changes with StatsD metrics and detailed logging. # - Updates the Rails cache with new checksums for future comparisons. # # See also: Forms::Client for API integration class FormPdfChangeDetectionJob include Sidekiq::Job sidekiq_options retry: 10 CACHE_TTL = 7.days.to_i.freeze # Keep longer than daily job frequency CACHE_PREFIX = 'form_pdf_revision_sha256' META_DATA = "[#{name}]".freeze def perform return unless Flipper.enabled?(:form_pdf_change_detection) Rails.logger.info("#{META_DATA} - Job started.") forms = fetch_forms_data cache_keys, current_sha_map = get_current_form_data(forms) cached_sha_map = Rails.cache.read_multi(*cache_keys) log_form_revisions(current_sha_map, cached_sha_map) update_cached_values(current_sha_map) Rails.logger.info("#{META_DATA} - Job finished successfully.") rescue => e Rails.logger.error("#{META_DATA} - Job raised an error: #{e.message}") raise e end private def fetch_forms_data response = Forms::Client.new(nil).get_all response.body['data'] end def get_current_form_data(forms) cache_keys = [] current_sha_map = {} forms.each do |form| form_id = form['id'] current_sha256 = form.dig('attributes', 'sha256') next unless form_id && current_sha256 cache_key = "#{CACHE_PREFIX}:#{form_id}" cache_keys << cache_key current_sha_map[cache_key] = { sha256: current_sha256, form: } rescue => e Rails.logger.error("#{META_DATA} - Error processing form #{form&.dig('id')}: #{e.message}") end [cache_keys, current_sha_map] end def update_cached_values(current_sha_map) cache_data = current_sha_map.transform_values { |data| data[:sha256] } Rails.cache.write_multi(cache_data, expires_in: CACHE_TTL) unless cache_data.empty? end def log_form_revisions(current_sha_map, cached_sha_map) current_sha_map.each do |cache_key, data| current_sha256 = data[:sha256] form = data[:form] last_known_sha256 = cached_sha_map[cache_key] log_form_revision(form['attributes'], form['id']) if last_known_sha256 && last_known_sha256 != current_sha256 end end def log_form_revision(form_attributes, form_id) form_name = form_attributes['form_name'] last_revision_on = form_attributes['last_revision_on'] url = form_attributes['url'] StatsD.increment('form.pdf.change.detected', tags: ["form:#{form_name}", "form_id:#{form_id}"]) Rails.logger.info( "#{META_DATA} - PDF form #{form_name} (form_id: #{form_id}) was revised. " \ "Last revised on date: #{last_revision_on}. " \ "URL: #{url}" ) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/delete_old_pii_logs_job.rb
# frozen_string_literal: true class DeleteOldPiiLogsJob include Sidekiq::Job sidekiq_options unique_for: 30.minutes, retry: false EXPIRATION_TIME = 2.weeks BATCH_SIZE = 10_000 def perform loop do records = PersonalInformationLog.where('created_at < ?', EXPIRATION_TIME.ago).limit(BATCH_SIZE) break if records.empty? records.delete_all end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/gi_bill_feedback_submission_job.rb
# frozen_string_literal: true require 'gibft/service' class GIBillFeedbackSubmissionJob include Sidekiq::Job sidekiq_options retry: false def perform(feedback_id, form, user_uuid) @feedback_id = feedback_id gi_bill_feedback.form = form gi_bill_feedback.user = User.find(user_uuid) if user_uuid.present? gi_bill_feedback.response = Gibft::Service.new.submit(gi_bill_feedback.transform_form).to_json gi_bill_feedback.state = 'success' gi_bill_feedback.save! rescue gi_bill_feedback.state = 'failed' gi_bill_feedback.save! raise end def gi_bill_feedback @gi_bill_feedback ||= GIBillFeedback.find(@feedback_id) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/delete_old_transactions_job.rb
# frozen_string_literal: true require 'vets/shared_logging' class DeleteOldTransactionsJob include Sidekiq::Job include Vets::SharedLogging # :nocov: def perform AsyncTransaction::Base .stale .find_each do |tx| tx.destroy! rescue ActiveRecord::RecordNotDestroyed => e log_message_to_sentry( 'DeleteOldTransactionsJob raised an exception', :error, { model: self.class.to_s, transaction_id: tx.id, exception: e.message } ) log_message_to_rails( 'DeleteOldTransactionsJob raised an exception', :error, { model: self.class.to_s, transaction_id: tx.id, exception: e.message } ) end end # :nocov: end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_failure_state_snapshot_job.rb
# frozen_string_literal: true # Log information about Form526Submission state to populate an admin facing Datadog dashboard class Form526FailureStateSnapshotJob include Sidekiq::Job sidekiq_options retry: false STATSD_PREFIX = 'form526.state.snapshot' def perform write_failure_snapshot rescue => e Rails.logger.error('Error logging 526 state snapshot', class: self.class.name, message: e.try(:message)) end def write_failure_snapshot state_as_counts.each do |description, count| StatsD.gauge("#{STATSD_PREFIX}.#{description}", count) end end def state_as_counts @state_as_counts ||= {}.tap do |abbreviation| snapshot_state.each do |dp, ids| abbreviation[:"#{dp}_count"] = ids.count end end end def snapshot_state @snapshot_state ||= load_snapshot_state end def load_snapshot_state { total_awaiting_backup_status: Form526Submission.pending_backup.pluck(:id).sort, total_incomplete_type: Form526Submission.incomplete_type.pluck(:id).sort, total_failure_type: Form526Submission.failure_type.pluck(:id).sort } end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/benefits_intake_status_job.rb
# frozen_string_literal: true require 'lighthouse/benefits_intake/service' require 'lighthouse/benefits_intake/sidekiq/submission_status_job' require 'pcpg/monitor' require 'dependents/monitor' require 'vre/monitor' # Datadog Dashboard: # https://vagov.ddog-gov.com/dashboard/4d8-3fn-dbp/benefits-intake-form-submission-tracking?fromUser=false&refresh_mode=sliding&view=spans&from_ts=1717772535566&to_ts=1718377335566&live=true class BenefitsIntakeStatusJob include Sidekiq::Job sidekiq_options retry: false STATS_KEY = 'api.benefits_intake.submission_status' STALE_SLA = Settings.lighthouse.benefits_intake.report.stale_sla || 10 BATCH_SIZE = Settings.lighthouse.benefits_intake.report.batch_size || 1000 attr_reader :batch_size def initialize(batch_size: BATCH_SIZE) @batch_size = batch_size end def perform StatsD.increment("#{STATS_KEY}.job.started") Rails.logger.info('BenefitsIntakeStatusJob started') begin process_pending_submissions rescue => e handle_job_failure(e) raise end end private def process_pending_submissions pending_form_submission_attempts = fetch_pending_attempts total_handled, result = batch_process(pending_form_submission_attempts) record_job_result(result, total_handled) end def fetch_pending_attempts pending_attempts = FormSubmissionAttempt.where(aasm_state: 'pending') .includes(:form_submission).to_a form_ids = BenefitsIntake::SubmissionStatusJob::FORM_HANDLERS.keys.map(&:to_s) pending_attempts.reject { |pfsa| form_ids.include?(pfsa.form_submission.form_type) } end def record_job_result(result, total_handled) if result StatsD.increment("#{STATS_KEY}.job.completed") Rails.logger.info('BenefitsIntakeStatusJob ended', total_handled:) else StatsD.increment("#{STATS_KEY}.job.failed") end end def handle_job_failure(exception) StatsD.increment("#{STATS_KEY}.job.failed") Rails.logger.error('BenefitsIntakeStatusJob failed with exception', class: self.class.name, message: exception.message) end def batch_process(pending_form_submission_attempts) total_handled = 0 errors = [] intake_service = BenefitsIntake::Service.new pending_form_submission_attempts.each_slice(batch_size) do |batch| batch_uuids = batch.map(&:benefits_intake_uuid) response = intake_service.bulk_status(uuids: batch_uuids) # Log the entire response for debugging purposes Rails.logger.info("Received bulk status response: #{response.body}") errors << response.body unless response.success? total_handled += handle_response(response) end unless errors.empty? Rails.logger.error('Errors occurred while processing Intake Status batch', class: self.class.name, errors:) end [total_handled, true] rescue => e Rails.logger.error('Benefits Intake Status Job failed, some batched submissions may not have been processed', class: self.class.name, message: e.message) [total_handled, false] end # rubocop:disable Metrics/MethodLength def handle_response(response) total_handled = 0 # Ensure response body contains data, and log the data for debugging if response.body['data'].blank? Rails.logger.error("Response data is blank or missing: #{response.body}") return total_handled end response.body['data']&.each do |submission| uuid = submission['id'] form_submission_attempt = form_submission_attempts_hash[uuid] form_submission = form_submission_attempt&.form_submission form_id = form_submission&.form_type saved_claim_id = form_submission&.saved_claim_id time_to_transition = (Time.zone.now - form_submission_attempt.created_at).truncate # https://developer.va.gov/explore/api/benefits-intake/docs status = submission.dig('attributes', 'status') # Log the status for debugging Rails.logger.info("Processing submission UUID: #{uuid}, Status: #{status}") lighthouse_updated_at = submission.dig('attributes', 'updated_at') if status == 'expired' # Expired - Indicate that documents were not successfully uploaded within the 15-minute window. error_message = 'expired' form_submission_attempt.update(error_message:, lighthouse_updated_at:) form_submission_attempt.fail! log_result('failure', form_id, uuid, time_to_transition, error_message) monitor_failure(form_id, saved_claim_id, uuid) elsif status == 'error' # Error - Indicates that there was an error. Refer to the error code and detail for further information. error_message = "#{submission.dig('attributes', 'code')}: #{submission.dig('attributes', 'detail')}" form_submission_attempt.update(error_message:, lighthouse_updated_at:) form_submission_attempt.fail! log_result('failure', form_id, uuid, time_to_transition, error_message) monitor_failure(form_id, saved_claim_id, uuid) elsif status == 'vbms' # submission was successfully uploaded into a Veteran's eFolder within VBMS form_submission_attempt.update(lighthouse_updated_at:) form_submission_attempt.vbms! log_result('success', form_id, uuid, time_to_transition) elsif time_to_transition > STALE_SLA.days # exceeds SLA (service level agreement) days for submission completion log_result('stale', form_id, uuid, time_to_transition) else # no change being tracked log_result('pending', form_id, uuid) Rails.logger.info( "Submission UUID: #{uuid} is still pending, status: #{status}, time to transition: #{time_to_transition}" ) end total_handled += 1 end total_handled end # rubocop:enable Metrics/MethodLength def log_result(result, form_id, uuid, time_to_transition = nil, error_message = nil) StatsD.increment("#{STATS_KEY}.#{form_id}.#{result}") StatsD.increment("#{STATS_KEY}.all_forms.#{result}") if result == 'failure' Rails.logger.error('BenefitsIntakeStatusJob', result:, form_id:, uuid:, time_to_transition:, error_message:) else Rails.logger.info('BenefitsIntakeStatusJob', result:, form_id:, uuid:, time_to_transition:) end end # rubocop:disable Metrics/MethodLength def monitor_failure(form_id, saved_claim_id, bi_uuid) context = { form_id:, claim_id: saved_claim_id, benefits_intake_uuid: bi_uuid } call_location = caller_locations.first # Dependents if %w[686C-674 686C-674-V2 21-674 21-674-V2].include?(form_id) claim = SavedClaim::DependencyClaim.find(saved_claim_id) email = if claim.present? claim.parsed_form.dig('dependents_application', 'veteran_contact_information', 'email_address') end if claim.present? && email.present? claim.send_failure_email(email) claim.monitor.log_silent_failure_no_confirmation(context, call_location:) else monitor = claim.present? ? claim.monitor : Dependents::Monitor.new(false) monitor.log_silent_failure(context, call_location:) end end # PCPG if %w[28-8832].include?(form_id) claim = SavedClaim::EducationCareerCounselingClaim.find(saved_claim_id) email = claim.parsed_form.dig('claimantInformation', 'emailAddress') if claim.present? if claim.present? && email.present? claim.send_failure_email(email) PCPG::Monitor.new.log_silent_failure_no_confirmation(context, call_location:) else PCPG::Monitor.new.log_silent_failure(context, call_location:) end end # VRE if %w[28-1900].include?(form_id) claim = SavedClaim::VeteranReadinessEmploymentClaim.find(saved_claim_id) email = claim.parsed_form['email'] if claim.present? if claim.present? && email.present? claim.send_failure_email(email) VRE::Monitor.new.log_silent_failure_no_confirmation(context, call_location:) else VRE::Monitor.new.log_silent_failure(context, call_location:) end end end # rubocop:enable Metrics/MethodLength def form_submission_attempts_hash @_form_submission_attempts_hash ||= FormSubmissionAttempt .where(aasm_state: 'pending') .index_by(&:benefits_intake_uuid) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/delete_attachment_job.rb
# frozen_string_literal: true class DeleteAttachmentJob include Sidekiq::Job sidekiq_options(unique_for: 30.minutes, retry: false) EXPIRATION_TIME = 2.months def perform FormAttachment.where( 'created_at < ?', self.class::EXPIRATION_TIME.ago ).where( type: self.class::ATTACHMENT_CLASSES ).where.not(guid: uuids_to_keep).find_each(&:destroy!) end def uuids_to_keep uuids = [] InProgressForm.where(form_id: self.class::FORM_ID).find_each do |in_progress_form| uuids += get_uuids(in_progress_form.data_and_metadata[:formData]) end uuids end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/sidekiq/form526_submission_failure_email_job.rb
# frozen_string_literal: true require 'va_notify/service' class Form526SubmissionFailureEmailJob include Sidekiq::Job attr_accessor :submission STATSD_PREFIX = 'api.form_526.veteran_notifications.form526_submission_failure_email' # https://github.com/department-of-veterans-affairs/va.gov-team-sensitive/blob/274bea7fb835e51626259ac16b32c33ab0b2088a/platform/practices/zero-silent-failures/logging-silent-failures.md#capture-silent-failures-state ZSF_DD_TAG_FUNCTION = '526_backup_submission_to_lighthouse' VA_NOTIFY_CALLBACK_OPTIONS = { callback_metadata: { notification_type: 'error', form_number: Form526Submission::FORM_526, statsd_tags: { service: Form526Submission::ZSF_DD_TAG_SERVICE, function: ZSF_DD_TAG_FUNCTION } } }.freeze DD_ZSF_TAGS = [ "service:#{Form526Submission::ZSF_DD_TAG_SERVICE}", "function:#{ZSF_DD_TAG_FUNCTION}" ].freeze FORM_DESCRIPTIONS = { 'form4142' => 'VA Form 21-4142', 'form0781' => 'VA Form 21-0781', 'form0781a' => 'VA Form 21-0781a', 'form0781v2' => 'VA Form 21-0781', 'form8940' => 'VA Form 21-8940' }.freeze FORM_KEYS = { 'form4142' => 'form4142', 'form0781' => 'form0781.form0781', 'form0781a' => 'form0781.form0781a', 'form0781v2' => 'form0781.form0781v2', 'form8940' => 'form8940' }.freeze # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 sidekiq_retries_exhausted do |msg, _ex| job_id = msg['jid'] error_class = msg['error_class'] error_message = msg['error_message'] form526_submission_id = msg['args'].first timestamp = Time.now.utc Rails.logger.warn( 'Form526SubmissionFailureEmailJob retries exhausted', { job_id:, timestamp:, form526_submission_id:, error_class:, error_message: } ) StatsD.increment("#{STATSD_PREFIX}.exhausted") StatsD.increment('silent_failure', tags: DD_ZSF_TAGS) rescue => e Rails.logger.error( 'Failure in Form526SubmissionFailureEmailJob#sidekiq_retries_exhausted', { job_id:, messaged_content: e.message, submission_id:, pre_exhaustion_failure: { error_class:, error_message: } } ) raise e end def perform(submission_id, date_of_failure = Time.now.utc.to_s) @submission = Form526Submission.find(submission_id) @date_of_failure = Time.zone.parse(date_of_failure) send_email track_remedial_action log_success rescue => e log_failure(e) raise end private def send_email email_client = VaNotify::Service.new(Settings.vanotify.services.benefits_disability.api_key, VA_NOTIFY_CALLBACK_OPTIONS) template_id = Settings.vanotify.services.benefits_disability.template_id .form526_submission_failure_notification_template_id email_client.send_email( email_address: submission.veteran_email_address, template_id:, personalisation: ) end def list_forms_submitted FORM_KEYS.each_with_object([]) do |(key, path), forms| forms << FORM_DESCRIPTIONS[key] if form.dig(*path.split('.')).present? end end def list_files_submitted return [] if form['form526_uploads'].blank? guids = form['form526_uploads'].map { |data| data&.dig('confirmationCode') }.compact files = SupportingEvidenceAttachment.where(guid: guids) files.map(&:obscured_filename) end def personalisation { first_name: submission.get_first_name, date_submitted: submission.format_creation_time_for_mailers, forms_submitted: list_forms_submitted.presence || 'None', files_submitted: list_files_submitted.presence || 'None', date_of_failure: parsed_date_of_failure } end def parsed_date_of_failure @date_of_failure.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.') end def track_remedial_action Form526SubmissionRemediation.create!( form526_submission: submission, remediation_type: Form526SubmissionRemediation.remediation_types['email_notified'], lifecycle: ['Email failure notification sent'] ) end def log_success Rails.logger.info( 'Form526SubmissionFailureEmailJob notification dispatched', { form526_submission_id: submission.id, timestamp: Time.now.utc } ) StatsD.increment("#{STATSD_PREFIX}.success") end def log_failure(error) Rails.logger.error( 'Form526SubmissionFailureEmailJob notification failed', { form526_submission_id: submission&.id, error_message: error.try(:message), timestamp: Time.now.utc } ) StatsD.increment("#{STATSD_PREFIX}.error") end def form @form ||= submission.form end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/copay_notifications/parse_new_statements_job.rb
# frozen_string_literal: true module CopayNotifications class ParseNewStatementsJob include Sidekiq::Job sidekiq_options retry: false # time (in seconds) between scheduling batch of jobs JOB_INTERVAL = Settings.mcp.notifications.job_interval # number of jobs to perform at next interval BATCH_SIZE = Settings.mcp.notifications.batch_size STATSD_KEY_PREFIX = 'api.copay_notifications.json_file' sidekiq_retries_exhausted do |_msg, ex| StatsD.increment("#{STATSD_KEY_PREFIX}.retries_exhausted") Rails.logger.error <<~LOG CopayNotifications::ParseNewStatementsJob retries exhausted: Exception: #{ex.class} - #{ex.message} Backtrace: #{ex.backtrace.join("\n")} LOG end def perform(statements_json_byte) StatsD.increment("#{STATSD_KEY_PREFIX}.total") # Decode and parse large json file (~60-90k objects) statements_json = Oj.load(Base64.decode64(statements_json_byte)) unique_statements = statements_json.uniq { |statement| statement['veteranIdentifier'] } unique_statements.each_with_index do |statement, index| # For every BATCH_SIZE jobs, enqueue the next BATCH_SIZE amount of jobs JOB_INTERVAL seconds later CopayNotifications::NewStatementNotificationJob.perform_in( JOB_INTERVAL * (index / BATCH_SIZE), statement ) end end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/copay_notifications/new_statement_notification_job.rb
# frozen_string_literal: true require 'debt_management_center/statement_identifier_service' require 'debt_management_center/sidekiq/va_notify_email_job' require 'vets/shared_logging' module CopayNotifications class Vet360IdNotFound < StandardError def initialize(icn) message = "MPIProfileMissingVet360Id: MPI Profile is missing vet360id #{icn}" super(message) end end class NewStatementNotificationJob include Sidekiq::Job include Vets::SharedLogging MCP_NOTIFICATION_TEMPLATE = Settings.vanotify.services.dmc.template_id.vha_new_copay_statement_email STATSD_KEY_PREFIX = 'api.copay_notifications.new_statement' sidekiq_options retry: 5 sidekiq_retry_in do |count, exception, _jobhash| case exception when DebtManagementCenter::StatementIdentifierService::RetryableError 10 * (count + 1) else :kill end end sidekiq_retries_exhausted do |_msg, ex| StatsD.increment("#{STATSD_KEY_PREFIX}.failure") # remove when we get more data into the retries_exhausted below StatsD.increment("#{STATSD_KEY_PREFIX}.retries_exhausted") Rails.logger.error <<~LOG NewStatementNotificationJob retries exhausted: Exception: #{ex.class} - #{ex.message} Backtrace: #{ex.backtrace.join("\n")} LOG end def perform(statement) # rubocop:disable Lint/UselessAssignment StatsD.increment("#{STATSD_KEY_PREFIX}.total") statement_service = DebtManagementCenter::StatementIdentifierService.new(statement) user_data = statement_service.get_mpi_data icn = user_data[:icn] personalization = { 'name' => user_data[:first_name], 'date' => Time.zone.today.strftime('%B %d, %Y') } statement_date = statement['statementDate'] account_balance = statement['accountBalance'] Rails.logger.info("Notification Data: date-#{statement_date}, balance-#{account_balance}") # rubocop:enable Lint/UselessAssignment # pausing until further notice # DebtManagementCenter::VANotifyEmailJob.perform_async(icn, MCP_NOTIFICATION_TEMPLATE, personalization, 'icn') end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/kms_key_rotation/batch_initiator_job.rb
# frozen_string_literal: true module KmsKeyRotation class BatchInitiatorJob include Sidekiq::Worker sidekiq_options retry: false, queue: :low MAX_RECORDS_PER_BATCH = 15_000_000 MAX_RECORDS_PER_JOB = 100 MODELS_FOR_QUERY = { 'ClaimsApi::V2::AutoEstablishedClaim' => ClaimsApi::AutoEstablishedClaim }.freeze def perform(max_records_per_job = MAX_RECORDS_PER_JOB, max_records_per_batch = MAX_RECORDS_PER_BATCH) flag_rotation_records_on_rotation_day records_enqueued = 0 models.each do |model| if records_enqueued >= max_records_per_batch Rails.logger.info("Maximum enqueued #{records_enqueued} records for key rotation reached. Stopping.") break end Rails.logger.info("Enqueuing #{model} records for key rotation. #{records_enqueued} records enqueued so far") gids = gids_for_model(model, max_records_per_batch) gids.each_slice(max_records_per_job) do |slice| KmsKeyRotation::RotateKeysJob.perform_async(slice) end records_enqueued += gids.size end end private def models @models ||= ApplicationRecord.descendants_using_encryption.map(&:name).map(&:constantize) end def gids_for_model(model, max_records_per_batch) model = MODELS_FOR_QUERY[model.name] if MODELS_FOR_QUERY.key?(model.name) model .where(needs_kms_rotation: true) .limit(max_records_per_batch) .pluck(model.primary_key) .map { |id| URI::GID.build(app: GlobalID.app, model_name: model.name, model_id: id).to_s } end def rotation_date? today = Time.zone.today today.month == 10 && today.day == 12 end def flag_rotation_records_on_rotation_day return unless rotation_date? Rails.logger.info '[KmsKeyRotation] Flagging every record for rotation on October 12th' models.each do |encrypted_model| model = MODELS_FOR_QUERY.fetch(encrypted_model.name, encrypted_model) model.update_all(needs_kms_rotation: true) # rubocop:disable Rails/SkipsModelValidations end end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/kms_key_rotation/rotate_keys_job.rb
# frozen_string_literal: true module KmsKeyRotation class RotateKeysJob include Sidekiq::Worker sidekiq_options retry: false, queue: :low def perform(gids) Rails.logger.info { "Re-encrypting records: #{gids.join ', '}" } records = GlobalID::Locator.locate_many gids records.each do |r| original_key = r.encrypted_kms_key r.rotate_kms_key! rotated_key = r.encrypted_kms_key # rubocop is disabled because the updated_at field MUST stay the same # rubocop:disable Rails/SkipsModelValidations r.update_column('needs_kms_rotation', false) unless original_key == rotated_key # rubocop:enable Rails/SkipsModelValidations rescue => e Rails.logger.error("Error rotating record (id: #{r.to_global_id}): #{e.message}") end end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/hca/log_email_diff_job.rb
# frozen_string_literal: true # LogEmailDiffJob # # This Sidekiq job logs whether the email address in an in-progress form matches the user's VA Profile email. # # Why: # - Tracks discrepancies between user-provided emails and VA Profile emails for analytics and troubleshooting. # - Helps identify cases where users may be using different emails for forms and their official profile. # # How: # - Checks if a log already exists for the given user and form. # - Loads the in-progress form and parses the email. # - Compares the form email to the user's VA Profile email. # - Logs the result as 'same' or 'different' and increments a StatsD metric. # # See also: FormEmailMatchesProfileLog model for storage details. module HCA class LogEmailDiffJob include Sidekiq::Job sidekiq_options retry: false def perform(in_progress_form_id, user_uuid, user_account_id) return if FormEmailMatchesProfileLog.exists?( user_uuid:, user_account_id:, in_progress_form_id: ) in_progress_form = InProgressForm.find_by(id: in_progress_form_id) return if in_progress_form.nil? parsed_form = JSON.parse(in_progress_form.form_data) form_email = parsed_form['email'] return if form_email.blank? user = User.find(user_uuid) va_profile_email = user.va_profile_email tag_text = va_profile_email&.downcase == form_email.downcase ? 'same' : 'different' record_email_diff(tag_text, user_uuid, user_account_id, in_progress_form_id) end private def record_email_diff(tag_text, user_uuid, user_account_id, in_progress_form_id) email_diff_log = FormEmailMatchesProfileLog.find_or_create_by( user_uuid:, user_account_id:, in_progress_form_id: ) if email_diff_log.persisted? && email_diff_log.created_at == email_diff_log.updated_at StatsD.increment( "api.1010ez.in_progress_form_email.#{tag_text}" ) end end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/hca/std_institution_import_job.rb
# frozen_string_literal: true # StdInstitutionImportJob # # This Sidekiq job imports and synchronizes standard institution facility data from a remote CSV source. # # Why: # - Keeps the StdInstitutionFacility table up-to-date with authoritative data. # - Ensures downstream processes and user features have current institution information. # # How: # - Downloads a CSV file from a remote S3 bucket. # - Parses and maps the data to the local schema. # - Upserts new and updated records, and logs new institutions. # - Triggers a HealthFacilitiesImportJob to update related health facility data. # # See also: StdInstitutionFacility model, HealthFacilitiesImportJob for downstream updates. require 'csv' require 'net/http' module HCA class StdInstitutionImportJob include Sidekiq::Job STRING_ATTRIBUTES = { activation_date: 'ACTIVATIONDATE', deactivation_date: 'DEACTIVATIONDATE', name: 'NAME', station_number: 'STATIONNUMBER', vista_name: 'VISTANAME', street_address_line1: 'STREETADDRESSLINE1', street_address_line2: 'STREETADDRESSLINE2', street_address_line3: 'STREETADDRESSLINE3', street_city: 'STREETCITY', street_postal_code: 'STREETPOSTALCODE', mailing_address_line1: 'MAILINGADDRESSLINE1', mailing_address_line2: 'MAILINGADDRESSLINE2', mailing_address_line3: 'MAILINGADDRESSLINE3', mailing_city: 'MAILINGCITY', mailing_postal_code: 'MAILINGPOSTALCODE', created_by: 'CREATEDBY', updated_by: 'UPDATEDBY' }.freeze INTEGER_ATTRIBUTES = { agency_id: 'AGENCY_ID', street_country_id: 'STREETCOUNTRY_ID', street_state_id: 'STREETSTATE_ID', street_county_id: 'STREETCOUNTY_ID', mailing_country_id: 'MAILINGCOUNTRY_ID', mailing_state_id: 'MAILINGSTATE_ID', mailing_county_id: 'MAILINGCOUNTY_ID', facility_type_id: 'FACILITYTYPE_ID', mfn_zeg_recipient: 'MFN_ZEG_RECIPIENT', parent_id: 'PARENT_ID', realigned_from_id: 'REALIGNEDFROM_ID', realigned_to_id: 'REALIGNEDTO_ID', visn_id: 'VISN_ID', version: 'VERSION' }.freeze def fetch_csv_data csv_url = 'https://sitewide-public-websites-income-limits-data.s3-us-gov-west-1.amazonaws.com/std_institution.csv' uri = URI(csv_url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) response_code = response.code if response_code == '200' response.body else Rails.logger.warn("[HCA] - CSV retrieval failed with response code #{response_code}") nil end end def perform return unless Flipper.enabled?(:hca_health_facilities_update_job) import_facilities end def import_facilities(run_sync: false) Rails.logger.info("[HCA] - Job started with #{StdInstitutionFacility.count} existing facilities.") ActiveRecord::Base.transaction do data = fetch_csv_data raise 'Failed to fetch CSV data.' unless data import_institutions_from_csv(data) run_sync ? HCA::HealthFacilitiesImportJob.new.perform : HCA::HealthFacilitiesImportJob.perform_async Rails.logger.info("[HCA] - Job ended with #{StdInstitutionFacility.count} existing facilities.") end StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.ves_facilities_import_complete") end private def import_institutions_from_csv(data) new_facilities = [] CSV.parse(data, headers: true) do |row| id = row['ID'].to_i std_institution_facility = StdInstitutionFacility.find_or_initialize_by(id:) new_facilities << id if std_institution_facility.new_record? created = DateTime.strptime(row['CREATED'], '%F %H:%M:%S %z').to_s updated = DateTime.strptime(row['UPDATED'], '%F %H:%M:%S %z').to_s if row['UPDATED'] string_attributes = STRING_ATTRIBUTES.transform_values { |string_field| row[string_field]&.to_s } integer_attributes = INTEGER_ATTRIBUTES.transform_values { |integer_field| row[integer_field]&.to_i } std_institution_facility.assign_attributes( { created:, updated: }.merge(string_attributes).merge(integer_attributes) ) std_institution_facility.save! end Rails.logger.info("[HCA] - #{new_facilities.count} new institutions: #{new_facilities}") if new_facilities.any? end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/hca/submission_job.rb
# frozen_string_literal: true # SubmissionJob # # This Sidekiq job handles the submission of 10-10EZ health care applications to the HCA backend service. # # Why: # - Automates the process of submitting user health care applications asynchronously. # - Handles retries and error logging for robust, reliable processing. # # How: # - Decrypts the submitted form data. # - Submits the form to the HCA backend via the HCA::Service. # - Updates the HealthCareApplication record with the result or error state. # - Handles validation errors and logs them for analytics and auditing. # # See also: HCA::Service for submission logic, HealthCareApplication for persistence. require 'hca/service' require 'hca/soap_parser' require 'sidekiq/monitored_worker' module HCA class SubmissionJob include Sidekiq::Job include Sidekiq::MonitoredWorker VALIDATION_ERROR = HCA::SOAPParser::ValidationError # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 sidekiq_retries_exhausted do |msg, _e| health_care_application = HealthCareApplication.find(msg['args'][2]) form = decrypt_form(msg['args'][1]) health_care_application.update!( state: 'failed', form: form.to_json, google_analytics_client_id: msg['args'][3] ) end def retry_limits_for_notification [10] end def notify(params) # Add 1 to retry_count to match retry_monitoring logic retry_count = params['retry_count'].to_i + 1 health_care_application_id = params['args'][2] if retry_count == 10 StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.async.failed_ten_retries", tags: ["health_care_application_id:#{health_care_application_id}"]) end end def self.decrypt_form(encrypted_form) JSON.parse(HealthCareApplication::LOCKBOX.decrypt(encrypted_form)) end def submit(user_identifier, form, google_analytics_client_id) begin result = HCA::Service.new(user_identifier).submit_form(form) rescue VALIDATION_ERROR handle_enrollment_system_validation_error(form, google_analytics_client_id) return false end result end def perform(user_identifier, encrypted_form, health_care_application_id, google_analytics_client_id) @health_care_application = HealthCareApplication.find(health_care_application_id) form = self.class.decrypt_form(encrypted_form) result = submit(user_identifier, form, google_analytics_client_id) return unless result Rails.logger.info "[10-10EZ] - SubmissionID=#{result[:formSubmissionId]}" @health_care_application.form = form.to_json @health_care_application.set_result_on_success!(result) rescue @health_care_application.update!(state: 'error') raise end private def handle_enrollment_system_validation_error(form, google_analytics_client_id) StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.enrollment_system_validation_error") PersonalInformationLog.create!( data: { form: }, error_class: VALIDATION_ERROR.to_s ) @health_care_application.update!( state: 'failed', form: form.to_json, google_analytics_client_id: ) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/hca/health_facilities_import_job.rb
# frozen_string_literal: true # HealthFacilitiesImportJob # # This Sidekiq job imports and synchronizes VA health facility data from the Lighthouse API # into the HealthFacility table. It ensures that the local database reflects the current # set of health facilities, including removing facilities that no longer exist in the source. # Why: # - Keeps our health facility data up-to-date for downstream services and user-facing features. # - Ensures data integrity by removing stale records. # - Handles edge cases where environments may have missing reference data (see ensure_std_states_populated). # How: # - Fetches all health facilities from Lighthouse, paginating as needed. # - Maps and transforms the data to match our schema. # - Upserts (inserts or updates) all current facilities. # - Deletes any facilities not present in the latest import. # - Logs progress and errors for monitoring and debugging. module HCA class HealthFacilitiesImportJob include Sidekiq::Job PER_PAGE = 1000 # retry for 0d 4h 22m 38s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 10 sidekiq_retries_exhausted do Rails.logger.error("[HCA] - #{HCA::HealthFacilitiesImportJob} failed with no retries left.") StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.health_facilities_import_job_failed_no_retries") end def perform Rails.logger.info("[HCA] - Job started with #{HealthFacility.count} existing health facilities.") ensure_std_states_populated facilities_from_lighthouse = get_facilities_from_lighthouse health_facilities = facilities_with_postal_names(facilities_from_lighthouse) HealthFacility.upsert_all(health_facilities, unique_by: :station_number) # rubocop:disable Rails/SkipsModelValidations delete_old_facilities(health_facilities) Rails.logger.info("[HCA] - Job ended with #{HealthFacility.count} health facilities.") StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.health_facilities_import_job_complete") rescue => e Rails.logger.error("[HCA] - Error occurred in #{self.class.name}: #{e.message}") raise "Failed to import health facilities in #{self.class.name}" end private def get_facilities_from_lighthouse facilities_client = FacilitiesApi::V2::Lighthouse::Client.new all_facilities = [] page = 1 loop do facilities = facilities_client.get_facilities( type: 'health', per_page: PER_PAGE, page:, mobile: false ) all_facilities.concat(facilities.map do |facility| { id: facility.id.sub(/^vha_/, ''), # Transform id by stripping "vha_" prefix name: facility.name } end) break if facilities.size < PER_PAGE # Stop when we get less than per_page results page += 1 end all_facilities.index_by { |facility| facility[:id] } end # Ensure the std_states table is populated. The table is populated in a # daily job, but this ensures the table is populated in any environment # that the table may be empty in (review instances, new environment, locally) def ensure_std_states_populated return if StdState.exists? ::IncomeLimits::StdStateImport.new.perform raise 'StdStates missing – triggered import and retrying job' end # Filter on only health facilities and return hash with # name, station_number (also known as facility_id), # and postal_name (also known as state_code ex OH,MI) def facilities_with_postal_names(facilities_from_lighthouse) StdInstitutionFacility .includes(:street_state) .where(station_number: facilities_from_lighthouse.keys) .pluck(:station_number, 'std_states.postal_name') .map do |station_number, postal_name| { name: facilities_from_lighthouse[station_number][:name], station_number:, postal_name: } end end def delete_old_facilities(health_facilities) imported_station_numbers = health_facilities.pluck(:station_number) deleted_count = HealthFacility.where.not(station_number: imported_station_numbers).delete_all Rails.logger.info("[HCA] - Deleted #{deleted_count} health facilities not present in import.") end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/hca/ezr_submission_job.rb
# frozen_string_literal: true # EzrSubmissionJob # # This Sidekiq job handles the submission of 10-10EZR (health care renewal) forms to the backend service. # # Why: # - Automates and manages the asynchronous submission of renewal forms. # - Handles retries, error logging, and user notification on failure. # # How: # - Decrypts the submitted form data. # - Submits the form via Form1010Ezr::Service. # - Handles validation and parsing errors, logs failures, and sends notification emails if enabled. # - Increments StatsD metrics for monitoring and analytics. # # See also: Form1010Ezr::Service for submission logic, Flipper flag for notification emails. require 'hca/soap_parser' require 'form1010_ezr/service' require 'vets/shared_logging' module HCA class EzrSubmissionJob include Sidekiq::Job extend Vets::SharedLogging FORM_ID = '10-10EZR' VALIDATION_ERROR = HCA::SOAPParser::ValidationError STATSD_KEY_PREFIX = 'api.1010ezr' DD_ZSF_TAGS = { service: 'healthcare-application', function: '10-10EZR async form submission' }.freeze # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 sidekiq_retries_exhausted do |msg, _e| parsed_form = decrypt_form(msg['args'][0]) StatsD.increment("#{STATSD_KEY_PREFIX}.failed_wont_retry") if parsed_form.present? PersonalInformationLog.create!( data: parsed_form, error_class: 'Form1010Ezr FailedWontRetry' ) send_failure_email(parsed_form) if Flipper.enabled?(:ezr_use_va_notify_on_submission_failure) Form1010Ezr::Service.log_submission_failure( parsed_form, '[10-10EZR] total failure' ) end end def self.decrypt_form(encrypted_form) JSON.parse(HealthCareApplication::LOCKBOX.decrypt(encrypted_form)) end def self.send_failure_email(parsed_form) email = parsed_form['email'] return if email.blank? first_name = parsed_form.dig('veteranFullName', 'first') template_id = Settings.vanotify.services.health_apps_1010.template_id.form1010_ezr_failure_email api_key = Settings.vanotify.services.health_apps_1010.api_key salutation = first_name ? "Dear #{first_name}," : '' VANotify::EmailJob.perform_async( email, template_id, { 'salutation' => salutation }, api_key, { callback_metadata: { notification_type: 'error', form_number: FORM_ID, statsd_tags: DD_ZSF_TAGS } } ) StatsD.increment("#{STATSD_KEY_PREFIX}.submission_failure_email_sent") end def perform(encrypted_form, user_uuid) user = User.find(user_uuid) parsed_form = self.class.decrypt_form(encrypted_form) Form1010Ezr::Service.new(user).submit_sync(parsed_form) rescue VALIDATION_ERROR => e StatsD.increment("#{STATSD_KEY_PREFIX}.enrollment_system_validation_error") PersonalInformationLog.create!(data: parsed_form, error_class: 'Form1010Ezr EnrollmentSystemValidationFailure') log_validation_error(parsed_form, e) self.class.send_failure_email(parsed_form) if Flipper.enabled?(:ezr_use_va_notify_on_submission_failure) rescue Ox::ParseError => e log_parse_error(parsed_form, e) self.class.send_failure_email(parsed_form) if Flipper.enabled?(:ezr_use_va_notify_on_submission_failure) # The Sidekiq::JobRetry::Skip error will fail the job and not retry it raise Sidekiq::JobRetry::Skip rescue StatsD.increment("#{STATSD_KEY_PREFIX}.async.retries") raise end private def log_validation_error(parsed_form, e) Form1010Ezr::Service.log_submission_failure(parsed_form, '[10-10EZR] failure') self.class.log_exception_to_rails(e) end def log_parse_error(parsed_form, e) StatsD.increment("#{STATSD_KEY_PREFIX}.failed_did_not_retry") PersonalInformationLog.create!(data: parsed_form, error_class: 'Form1010Ezr FailedDidNotRetry') Rails.logger.info("Form1010Ezr FailedDidNotRetry: #{e.message}") Form1010Ezr::Service.log_submission_failure(parsed_form, '[10-10EZR] failure did not retry') end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/identity/cerner_provisioner_job.rb
# frozen_string_literal: true module Identity class CernerProvisionerJob include Sidekiq::Job sidekiq_options retry: false, unique_for: 5.minutes def perform(icn, source = nil) CernerProvisioner.new(icn:, source:).perform rescue Errors::CernerProvisionerError => e Rails.logger.error('[Identity] [CernerProvisionerJob] error', { icn:, error_message: e.message, source: }) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/identity/user_acceptable_verified_credential_totals_job.rb
# frozen_string_literal: true module Identity class UserAcceptableVerifiedCredentialTotalsJob include Sidekiq::Job STATSD_KEY_PREFIX = 'worker.user_avc_totals' SCOPES = [WITH_AVC = :with_avc, WITH_IVC = :with_ivc, WITHOUT_AVC = :without_avc, WITHOUT_IVC = :without_ivc, WITHOUT_AVC_IVC = :without_avc_ivc].freeze PROVIDERS = [ALL = :all, IDME = :idme, LOGINGOV = :logingov, DSLOGON = :dslogon, MHV = :mhv].freeze def perform set_statsd_gauges end private ## # Set StatsD gauge for all user_avc_totals.[PROVIDERS].[SCOPES].total combinations def set_statsd_gauges base_query = UserAcceptableVerifiedCredential.joins(user_account: :user_verifications).distinct SCOPES.each do |scope| mhv_dslogon_combined_total = 0 scoped_query = base_query.merge(UserAcceptableVerifiedCredential.public_send(scope)) PROVIDERS.each do |provider| count = if provider == ALL scoped_query.count else scoped_query.merge(UserVerification.public_send(provider)).count end StatsD.gauge("#{STATSD_KEY_PREFIX}.#{provider}.#{scope}.total", count) # MHV and DSLOGON combined total mhv_dslogon_combined_total += count if [MHV, DSLOGON].include?(provider) end # MHV_DSLOGON Combined gauge StatsD.gauge("#{STATSD_KEY_PREFIX}.#{MHV}_#{DSLOGON}.#{scope}.total", mhv_dslogon_combined_total) end end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/identity/get_ssoe_traits_by_cspid_job.rb
# frozen_string_literal: true module Identity class GetSSOeTraitsByCspidJob include Sidekiq::Job STATSD_KEY_PREFIX = 'worker.get_ssoe_traits_by_cspid' sidekiq_options retry: 3, queue: :default def perform(cache_key, credential_method, credential_id) attributes = Sidekiq::AttrPackage.find(cache_key) unless attributes log_failure('Missing attributes in Redis for key', credential_method, credential_id) return end user = build_user(attributes) address = build_address(attributes) return unless validate_user(user, credential_method, credential_id) response = SSOe::Service.new.get_traits(credential_method:, credential_id:, user:, address:) log_success_or_failure(cache_key, credential_method, credential_id, response) rescue SSOe::Errors::Error, Sidekiq::AttrPackageError => e log_failure("#{self.class} error: #{e.class} - #{e.message}", credential_method, credential_id) raise end private def validate_user(user, credential_method, credential_id) unless user.valid? log_failure("Invalid user attributes: #{user.errors.full_messages.join(', ')}", credential_method, credential_id) return false end true end def build_user(attrs) SSOe::Models::User.new( first_name: attrs[:first_name], last_name: attrs[:last_name], birth_date: attrs[:birth_date], ssn: attrs[:ssn], email: attrs[:email], phone: attrs[:phone] ) end def build_address(attrs) SSOe::Models::Address.new( street1: attrs[:street1], city: attrs[:city], state: attrs[:state], zipcode: attrs[:zipcode] ) end def log_success_or_failure(cache_key, credential_method, credential_id, response) if response[:success] log_success(response[:icn], credential_method, credential_id) StatsD.increment("#{STATSD_KEY_PREFIX}.success", tags: ["credential_method:#{credential_method}"]) Sidekiq::AttrPackage.delete(cache_key) else log_failure('SSOe::Service.get_traits failed', credential_method, credential_id, response[:error], icn: response[:icn]) raise "SSOe::Service.get_traits failed - #{response[:error].inspect}" end end def log_success(icn, credential_method, credential_id) Rails.logger.info( '[GetSSOeTraitsByCspidJob] SSOe::Service.get_traits success', icn:, credential_method:, credential_id: ) end def log_failure(message, credential_method, credential_id, error = nil, icn = nil) log_payload = { credential_method:, credential_id: } log_payload[:error] = error if error log_payload[:icn] = icn if icn Rails.logger.error("[GetSSOeTraitsByCspidJob] #{message}", log_payload) StatsD.increment("#{STATSD_KEY_PREFIX}.failure", tags: ["credential_method:#{credential_method}"]) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/vre/submit1900_job.rb
# frozen_string_literal: true require 'vets/shared_logging' require 'vre/monitor' module VRE class Submit1900Job include Sidekiq::Job include Vets::SharedLogging STATSD_KEY_PREFIX = 'worker.vre.submit_1900_job' # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling RETRY = 16 sidekiq_options retry: RETRY sidekiq_retries_exhausted do |msg, _ex| VRE::Submit1900Job.trigger_failure_events(msg) StatsD.increment("#{STATSD_KEY_PREFIX}.failure") end def perform(claim_id, encrypted_user) claim = SavedClaim::VeteranReadinessEmploymentClaim.find claim_id user = OpenStruct.new(JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_user))) claim.send_to_vre(user) StatsD.increment("#{STATSD_KEY_PREFIX}.success") rescue => e Rails.logger.warn("VRE::Submit1900Job failed, retrying...: #{e.message}") raise end def self.trigger_failure_events(msg) claim_id = msg['args'][0] claim = SavedClaim.find(claim_id) if Flipper.enabled?(:vre_use_new_vfs_notification_library) VRE::VREMonitor.new.track_submission_exhaustion(msg, claim) else VRE::Monitor.new.track_submission_exhaustion(msg, claim.email) claim.send_failure_email end end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/sign_in/certificate_checker_job.rb
# frozen_string_literal: true class SignIn::CertificateCheckerJob include Sidekiq::Job LOGGER_PREFIX = '[SignIn] [CertificateChecker]' CONFIG_CLASSES = [ SignIn::ClientConfig, SignIn::ServiceAccountConfig ].freeze def perform CONFIG_CLASSES.each do |config_class| config_class.find_each { |config| check_certificates(config) } end end private def check_certificates(config) return if config.certs.expiring_later.any? if config.certs.expiring_soon.any? log_expiring_soon_certs(config) elsif config.certs.expired.any? log_expired_certs(config) end end def log_expired_certs(config) config.certs.expired.each do |cert| log_warning('expired_certificate', config, cert) end end def log_expiring_soon_certs(config) config.certs.expiring_soon.each do |cert| log_warning('expiring_soon_certificate', config, cert) end end def log_warning(type, config, certificate) Rails.logger.warn( "#{LOGGER_PREFIX} #{type}", build_payload(config, certificate) ) end def build_payload(config, certificate) { config_type: config.class.name, config_id: config.id, config_description: config.description, certificate_subject: certificate.subject.to_s, certificate_issuer: certificate.issuer.to_s, certificate_serial: certificate.serial.to_s, certificate_not_before: certificate.not_before.to_s, certificate_not_after: certificate.not_after.to_s } end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/sign_in/delete_expired_sessions_job.rb
# frozen_string_literal: true module SignIn class DeleteExpiredSessionsJob include Sidekiq::Job def perform expired_oauth_sessions.destroy_all end private def time_in_past ...Time.zone.now end def expired_oauth_sessions OAuthSession.where(refresh_expiration: time_in_past) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/bgs/submit_form674_v2_job.rb
# frozen_string_literal: true require 'bgsv2/form674' require 'dependents/monitor' require 'vets/shared_logging' module BGS class SubmitForm674V2Job < Job class Invalid674Claim < StandardError; end FORM_ID = '686C-674-V2' include Sidekiq::Job include Vets::SharedLogging attr_reader :claim, :user, :user_uuid, :saved_claim_id, :vet_info, :icn STATS_KEY = 'worker.submit_674_bgs' # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 sidekiq_retries_exhausted do |msg, _error| user_uuid, saved_claim_id, encrypted_vet_info, encrypted_user_struct_hash = msg['args'] vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) monitor = ::Dependents::Monitor.new(saved_claim_id) monitor.track_event('error', "BGS::SubmitForm674Job failed, retries exhausted! Last error: #{msg['error_message']}", 'worker.submit_674_bgs.exhaustion') BGS::SubmitForm674V2Job.send_backup_submission(encrypted_user_struct_hash, vet_info, saved_claim_id, user_uuid) end def perform(user_uuid, saved_claim_id, encrypted_vet_info, encrypted_user_struct_hash = nil) @monitor = init_monitor(saved_claim_id) @monitor.track_event('info', 'BGS::SubmitForm674Job running!', "#{STATS_KEY}.begin") instance_params(encrypted_vet_info, user_uuid, saved_claim_id, encrypted_user_struct_hash) submit_form send_confirmation_email @monitor.track_event('info', 'BGS::SubmitForm674Job succeeded!', "#{STATS_KEY}.success") InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:) rescue => e handle_filtered_errors!(e:, encrypted_user_struct_hash:, encrypted_vet_info:) @monitor.track_event('warn', 'BGS::SubmitForm674Job received error, retrying...', "#{STATS_KEY}.failure", { error: e.message, nested_error: e.cause&.message }) raise end def handle_filtered_errors!(e:, encrypted_user_struct_hash:, encrypted_vet_info:) filter = FILTERED_ERRORS.any? { |filtered| e.message.include?(filtered) || e.cause&.message&.include?(filtered) } return unless filter @monitor.track_event('warn', 'BGS::SubmitForm674Job received error, skipping retries...', "#{STATS_KEY}.skip_retries", { error: e.message, nested_error: e.cause&.message }) vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) self.class.send_backup_submission(encrypted_user_struct_hash, vet_info, saved_claim_id, user_uuid) raise Sidekiq::JobRetry::Skip end def instance_params(encrypted_vet_info, user_uuid, saved_claim_id, encrypted_user_struct_hash) @vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) @user = BGS::SubmitForm674V2Job.generate_user_struct(encrypted_user_struct_hash, @vet_info) @icn = @user.icn @user_uuid = user_uuid @saved_claim_id = saved_claim_id @claim = SavedClaim::DependencyClaim.find(saved_claim_id) end def self.generate_user_struct(encrypted_user_struct, vet_info) if encrypted_user_struct.present? return OpenStruct.new(JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_user_struct))) end info = vet_info['veteran_information'] full_name = info['full_name'] OpenStruct.new( first_name: full_name['first'], last_name: full_name['last'], middle_name: full_name['middle'], ssn: info['ssn'], email: info['email'], va_profile_email: info['va_profile_email'], participant_id: info['participant_id'], icn: info['icn'], uuid: info['uuid'], common_name: info['common_name'] ) end def self.send_backup_submission(encrypted_user_struct_hash, vet_info, saved_claim_id, user_uuid) user = generate_user_struct(encrypted_user_struct_hash, vet_info) Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.perform_async( saved_claim_id, KmsEncrypted::Box.new.encrypt(vet_info.to_json), KmsEncrypted::Box.new.encrypt(user.to_h.to_json) ) InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:) rescue => e monitor = Dependents::Monitor.new(saved_claim_id) monitor.track_event('error', 'BGS::SubmitForm674Job backup submission failed...', "#{STATS_KEY}.backup_failure", { error: e.message, nested_error: e.cause&.message }) InProgressForm.find_by(form_id: FORM_ID, user_uuid:)&.submission_pending! end private def submit_form claim.add_veteran_info(vet_info) raise Invalid674Claim unless claim.valid?(:run_686_form_jobs) claim_data = normalize_names_and_addresses!(claim.formatted_674_data(vet_info)) BGSV2::Form674.new(user, claim).submit(claim_data) end def send_confirmation_email claim.send_received_email(user) end def init_monitor(saved_claim_id) @monitor ||= ::Dependents::Monitor.new(saved_claim_id) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/bgs/flash_updater.rb
# frozen_string_literal: true require 'logging/third_party_transaction' require 'bgs/monitor' module BGS class FlashUpdater include Sidekiq::Job extend Logging::ThirdPartyTransaction::MethodWrapper attr_accessor :submission_id # Sidekiq has built in exponential back-off functionality for retries # A max retry attempt of 10 will result in a run time of ~8 hours # This job is invoked from 526 background job sidekiq_options retry: 10 STATSD_KEY_PREFIX = 'worker.bgs.flash_updater' wrap_with_logging( :add_flashes, additional_class_logs: { action: 'Begin Flash addition job' }, additional_instance_logs: { submission_id: %i[submission_id] } ) sidekiq_retries_exhausted do |msg, _ex| monitor = BGS::Monitor.new job_id = msg['jid'] error_class = msg['error_class'] error_message = msg['error_message'] timestamp = Time.now.utc form526_submission_id = msg['args'].first form_job_status = Form526JobStatus.find_by(job_id:) bgjob_errors = form_job_status.bgjob_errors || {} new_error = { "#{timestamp.to_i}": { caller_method: __method__.to_s, error_class:, error_message:, timestamp:, form526_submission_id: } } form_job_status.update( status: Form526JobStatus::STATUS[:exhausted], bgjob_errors: bgjob_errors.merge(new_error) ) monitor.warn( 'Flash Updater Retries exhausted', 'exhausted', stats_key: "#{STATSD_KEY_PREFIX}.exhausted", job_id:, error_class:, error: error_message, timestamp:, form526_submission_id: ) rescue => e monitor.error( 'Failure in FlashUpdater#sidekiq_retries_exhausted', 'exhaustion_failure', stats_key: STATSD_KEY_PREFIX, error: e.message, job_id:, submission_id: form526_submission_id, pre_exhaustion_failure: { error_class:, error: error_message } ) raise e end def perform(submission_id) @submission_id = submission_id add_flashes confirm_flash_addition end private def add_flashes flashes.each do |flash_name| # NOTE: Assumption that duplicate flashes are ignored when submitted service.add_flash(file_number: ssn, flash_name:) rescue BGS::ShareError, BGS::PublicError => e monitor.error(e.message, 'add_flashes', source: '526EZ-all-claims', submission_id:) end end def confirm_flash_addition assigned_flashes = service.find_assigned_flashes(ssn)[:flashes] flashes.each do |flash_name| assigned_flash = assigned_flashes.find { |af| af[:flash_name].strip == flash_name } if assigned_flash.blank? monitor.error("Failed to assign '#{flash_name}' to Veteran", 'add_flashes', source: '526EZ-all-claims', submission_id:) end end end def flashes @flashes ||= submission.form[Form526Submission::FLASHES] end def submission @submission ||= Form526Submission.find(submission_id) end def ssn @ssn ||= submission.auth_headers['va_eauth_pnid'] end def service @service ||= bgs_service.claimant end def bgs_service # BGS::Services is in the BGS bgs-ext gem, not to be confused with BGS::Service BGS::Services.new( external_uid: ssn, external_key: ssn ) end def monitor @monitor ||= BGS::Monitor.new(allowlist: %w[timestamp form526_submission_id pre_exhaustion_failure]) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/bgs/submit_form686c_v2_job.rb
# frozen_string_literal: true require 'bgsv2/form686c' require 'dependents/monitor' require 'vets/shared_logging' module BGS class SubmitForm686cV2Job < Job class Invalid686cClaim < StandardError; end FORM_ID = '686C-674-V2' include Sidekiq::Job include Vets::SharedLogging attr_reader :claim, :user, :user_uuid, :saved_claim_id, :vet_info, :icn STATS_KEY = 'worker.submit_686c_bgs' # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 sidekiq_retries_exhausted do |msg, _error| user_uuid, saved_claim_id, encrypted_vet_info = msg['args'] vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) monitor = ::Dependents::Monitor.new(saved_claim_id) monitor.track_event('error', "BGS::SubmitForm686cV2Job failed, retries exhausted! Last error: #{msg['error_message']}", 'worker.submit_686c_bgs.exhaustion') BGS::SubmitForm686cV2Job.send_backup_submission(vet_info, saved_claim_id, user_uuid) end def perform(user_uuid, saved_claim_id, encrypted_vet_info) @monitor = init_monitor(saved_claim_id) @monitor.track_event('info', 'BGS::SubmitForm686cV2Job running!', "#{STATS_KEY}.begin") instance_params(encrypted_vet_info, user_uuid, saved_claim_id) submit_686c @monitor.track_event('info', 'BGS::SubmitForm686cV2Job succeeded!', "#{STATS_KEY}.success") if claim.submittable_674? enqueue_674_job(encrypted_vet_info) else # if no 674, form submission is complete send_686c_confirmation_email InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:) end rescue => e handle_filtered_errors!(e:, encrypted_vet_info:) @monitor.track_event('warn', 'BGS::SubmitForm686cV2Job received error, retrying...', "#{STATS_KEY}.failure", { error: e.message, nested_error: e.cause&.message }) raise end def handle_filtered_errors!(e:, encrypted_vet_info:) # If it's a known error that should reroute to backup path, skip retries and send to backup path filter = FILTERED_ERRORS.any? { |filtered| e.message.include?(filtered) || e.cause&.message&.include?(filtered) } return unless filter @monitor.track_event('warn', 'BGS::SubmitForm686cV2Job received error, skipping retries...', "#{STATS_KEY}.skip_retries", { error: e.message, nested_error: e.cause&.message }) vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) self.class.send_backup_submission(vet_info, saved_claim_id, user_uuid) raise Sidekiq::JobRetry::Skip end def instance_params(encrypted_vet_info, user_uuid, saved_claim_id) @vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) @user = BGS::SubmitForm686cV2Job.generate_user_struct(@vet_info) @icn = @user.icn @user_uuid = user_uuid @saved_claim_id = saved_claim_id @claim = SavedClaim::DependencyClaim.find(saved_claim_id) end def self.generate_user_struct(vet_info) info = vet_info['veteran_information'] full_name = info['full_name'] OpenStruct.new( first_name: full_name['first'], last_name: full_name['last'], middle_name: full_name['middle'], ssn: info['ssn'], email: info['email'], va_profile_email: info['va_profile_email'], participant_id: info['participant_id'], icn: info['icn'], uuid: info['uuid'], common_name: info['common_name'] ) end def self.send_backup_submission(vet_info, saved_claim_id, user_uuid) user = generate_user_struct(vet_info) Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.perform_async( saved_claim_id, KmsEncrypted::Box.new.encrypt(vet_info.to_json), KmsEncrypted::Box.new.encrypt(user.to_h.to_json) ) InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:) rescue => e monitor = ::Dependents::Monitor.new(saved_claim_id) monitor.track_event('error', 'BGS::SubmitForm686cV2Job backup submission failed...', "#{STATS_KEY}.backup_failure", { error: e.message, nested_error: e.cause&.message }) InProgressForm.find_by(form_id: FORM_ID, user_uuid:)&.submission_pending! end private # This is probably dead code and can be removed. def submit_forms(encrypted_vet_info) claim.add_veteran_info(vet_info) raise Invalid686cClaim unless claim.valid?(:run_686_form_jobs) claim_data = normalize_names_and_addresses!(claim.formatted_686_data(vet_info)) BGSV2::Form686c.new(user, claim).submit(claim_data) # If Form 686c job succeeds, then enqueue 674 job. if claim.submittable_674? BGS::SubmitForm674V2Job .perform_async( user_uuid, saved_claim_id, encrypted_vet_info, KmsEncrypted::Box.new.encrypt(user.to_h.to_json) ) end end def submit_686c claim.add_veteran_info(vet_info) raise Invalid686cClaim unless claim.valid?(:run_686_form_jobs) claim_data = normalize_names_and_addresses!(claim.formatted_686_data(vet_info)) BGSV2::Form686c.new(user, claim).submit(claim_data) end def enqueue_674_job(encrypted_vet_info) BGS::SubmitForm674V2Job.perform_async(user_uuid, saved_claim_id, encrypted_vet_info, KmsEncrypted::Box.new.encrypt(user.to_h.to_json)) end def send_686c_confirmation_email claim.send_received_email(user) end # This is probably dead code and can be removed. def send_confirmation_email return if user.va_profile_email.blank? VANotify::ConfirmationEmail.send( email_address: user.va_profile_email, template_id: Settings.vanotify.services.va_gov.template_id.form686c_confirmation_email, first_name: user&.first_name&.upcase, user_uuid_and_form_id: "#{user.uuid}_#{FORM_ID}" ) end def init_monitor(saved_claim_id) @monitor ||= ::Dependents::Monitor.new(saved_claim_id) end end end
0
code_files/vets-api-private/app/sidekiq
code_files/vets-api-private/app/sidekiq/bgs/submit_form674_job.rb
# frozen_string_literal: true require 'bgs/form674' require 'dependents/monitor' require 'vets/shared_logging' module BGS class SubmitForm674Job < Job class Invalid674Claim < StandardError; end FORM_ID = '686C-674' include Sidekiq::Job include Vets::SharedLogging attr_reader :claim, :user, :user_uuid, :saved_claim_id, :vet_info, :icn STATS_KEY = 'worker.submit_674_bgs' # retry for 2d 1h 47m 12s # https://github.com/sidekiq/sidekiq/wiki/Error-Handling sidekiq_options retry: 16 sidekiq_retries_exhausted do |msg, _error| user_uuid, saved_claim_id, encrypted_vet_info, encrypted_user_struct_hash = msg['args'] vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) monitor = ::Dependents::Monitor.new(saved_claim_id) monitor.track_event('error', "BGS::SubmitForm674Job failed, retries exhausted! Last error: #{msg['error_message']}", 'worker.submit_674_bgs.exhaustion') BGS::SubmitForm674Job.send_backup_submission(encrypted_user_struct_hash, vet_info, saved_claim_id, user_uuid) end def perform(user_uuid, saved_claim_id, encrypted_vet_info, encrypted_user_struct_hash = nil) @monitor = init_monitor(saved_claim_id) @monitor.track_event('info', 'BGS::SubmitForm674Job running!', "#{STATS_KEY}.begin") instance_params(encrypted_vet_info, user_uuid, saved_claim_id, encrypted_user_struct_hash) submit_form send_confirmation_email @monitor.track_event('info', 'BGS::SubmitForm674Job succeeded!', "#{STATS_KEY}.success") InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:) rescue => e handle_filtered_errors!(e:, encrypted_user_struct_hash:, encrypted_vet_info:) @monitor.track_event('warn', 'BGS::SubmitForm674Job received error, retrying...', "#{STATS_KEY}.failure", { error: e.message, nested_error: e.cause&.message }) raise end def handle_filtered_errors!(e:, encrypted_user_struct_hash:, encrypted_vet_info:) filter = FILTERED_ERRORS.any? { |filtered| e.message.include?(filtered) || e.cause&.message&.include?(filtered) } return unless filter @monitor.track_event('warn', 'BGS::SubmitForm674Job received error, skipping retries...', "#{STATS_KEY}.skip_retries", { error: e.message, nested_error: e.cause&.message }) vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) self.class.send_backup_submission(encrypted_user_struct_hash, vet_info, saved_claim_id, user_uuid) raise Sidekiq::JobRetry::Skip end def instance_params(encrypted_vet_info, user_uuid, saved_claim_id, encrypted_user_struct_hash) @vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info)) @user = BGS::SubmitForm674Job.generate_user_struct(encrypted_user_struct_hash, @vet_info) @icn = @user.icn @user_uuid = user_uuid @saved_claim_id = saved_claim_id @claim = SavedClaim::DependencyClaim.find(saved_claim_id) end def self.generate_user_struct(encrypted_user_struct, vet_info) if encrypted_user_struct.present? return OpenStruct.new(JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_user_struct))) end info = vet_info['veteran_information'] full_name = info['full_name'] OpenStruct.new( first_name: full_name['first'], last_name: full_name['last'], middle_name: full_name['middle'], ssn: info['ssn'], email: info['email'], va_profile_email: info['va_profile_email'], participant_id: info['participant_id'], icn: info['icn'], uuid: info['uuid'], common_name: info['common_name'] ) end def self.send_backup_submission(encrypted_user_struct_hash, vet_info, saved_claim_id, user_uuid) user = generate_user_struct(encrypted_user_struct_hash, vet_info) Lighthouse::BenefitsIntake::SubmitCentralForm686cJob.perform_async( saved_claim_id, KmsEncrypted::Box.new.encrypt(vet_info.to_json), KmsEncrypted::Box.new.encrypt(user.to_h.to_json) ) InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:) rescue => e monitor = Dependents::Monitor.new(saved_claim_id) monitor.track_event('error', 'BGS::SubmitForm674Job backup submission failed...', "#{STATS_KEY}.backup_failure", { error: e.message, nested_error: e.cause&.message }) InProgressForm.find_by(form_id: FORM_ID, user_uuid:)&.submission_pending! end private def submit_form claim.add_veteran_info(vet_info) raise Invalid674Claim unless claim.valid?(:run_686_form_jobs) claim_data = normalize_names_and_addresses!(claim.formatted_674_data(vet_info)) BGS::Form674.new(user, claim).submit(claim_data) end def send_confirmation_email claim.send_received_email(user) end def init_monitor(saved_claim_id) @monitor ||= ::Dependents::Monitor.new(saved_claim_id) end end end