repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/mailers/application_mailer.rb | app/mailers/application_mailer.rb | # frozen_string_literal: true
class ApplicationMailer < ActionMailer::Base
default from: "#{Postal::Config.smtp.from_name} <#{Postal::Config.smtp.from_address}>"
layout false
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/seeds.rb | db/seeds.rb | # frozen_string_literal: true
# Seeds go here...
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/schema.rb | db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2024_03_11_205229) do
create_table "additional_route_endpoints", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "route_id"
t.string "endpoint_type"
t.integer "endpoint_id"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
end
create_table "address_endpoints", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.string "uuid"
t.string "address"
t.datetime "last_used_at", precision: nil
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
end
create_table "authie_sessions", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "token"
t.string "browser_id"
t.integer "user_id"
t.boolean "active", default: true
t.text "data"
t.datetime "expires_at", precision: nil
t.datetime "login_at", precision: nil
t.string "login_ip"
t.datetime "last_activity_at", precision: nil
t.string "last_activity_ip"
t.string "last_activity_path"
t.string "user_agent"
t.datetime "created_at", precision: nil
t.datetime "updated_at", precision: nil
t.string "user_type"
t.integer "parent_id"
t.datetime "two_factored_at", precision: nil
t.string "two_factored_ip"
t.integer "requests", default: 0
t.datetime "password_seen_at", precision: nil
t.string "token_hash"
t.string "host"
t.boolean "skip_two_factor", default: false
t.string "login_ip_country"
t.string "two_factored_ip_country"
t.string "last_activity_ip_country"
t.index ["browser_id"], name: "index_authie_sessions_on_browser_id", length: 8
t.index ["token"], name: "index_authie_sessions_on_token", length: 8
t.index ["token_hash"], name: "index_authie_sessions_on_token_hash", length: 8
t.index ["user_id"], name: "index_authie_sessions_on_user_id"
end
create_table "credentials", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.string "key"
t.string "type"
t.string "name"
t.text "options"
t.datetime "last_used_at"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "hold", default: false
t.string "uuid"
end
create_table "domains", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "verification_token"
t.string "verification_method"
t.datetime "verified_at", precision: nil
t.text "dkim_private_key"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "dns_checked_at"
t.string "spf_status"
t.string "spf_error"
t.string "dkim_status"
t.string "dkim_error"
t.string "mx_status"
t.string "mx_error"
t.string "return_path_status"
t.string "return_path_error"
t.boolean "outgoing", default: true
t.boolean "incoming", default: true
t.string "owner_type"
t.integer "owner_id"
t.string "dkim_identifier_string"
t.boolean "use_for_any"
t.index ["server_id"], name: "index_domains_on_server_id"
t.index ["uuid"], name: "index_domains_on_uuid", length: 8
end
create_table "http_endpoints", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "url"
t.string "encoding"
t.string "format"
t.boolean "strip_replies", default: false
t.text "error"
t.datetime "disabled_until"
t.datetime "last_used_at"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "include_attachments", default: true
t.integer "timeout"
end
create_table "ip_addresses", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "ip_pool_id"
t.string "ipv4"
t.string "ipv6"
t.datetime "created_at"
t.datetime "updated_at"
t.string "hostname"
t.integer "priority"
end
create_table "ip_pool_rules", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "uuid"
t.string "owner_type"
t.integer "owner_id"
t.integer "ip_pool_id"
t.text "from_text"
t.text "to_text"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
end
create_table "ip_pools", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "name"
t.string "uuid"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "default", default: false
t.index ["uuid"], name: "index_ip_pools_on_uuid", length: 8
end
create_table "organization_ip_pools", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "organization_id"
t.integer "ip_pool_id"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
end
create_table "organization_users", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "organization_id"
t.integer "user_id"
t.datetime "created_at"
t.boolean "admin", default: false
t.boolean "all_servers", default: true
t.string "user_type"
end
create_table "organizations", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "uuid"
t.string "name"
t.string "permalink"
t.string "time_zone"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip_pool_id"
t.integer "owner_id"
t.datetime "deleted_at"
t.datetime "suspended_at"
t.string "suspension_reason"
t.index ["permalink"], name: "index_organizations_on_permalink", length: 8
t.index ["uuid"], name: "index_organizations_on_uuid", length: 8
end
create_table "queued_messages", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.integer "message_id"
t.string "domain"
t.string "locked_by"
t.datetime "locked_at"
t.datetime "retry_after", precision: nil
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip_address_id"
t.integer "attempts", default: 0
t.integer "route_id"
t.boolean "manual", default: false
t.string "batch_key"
t.index ["domain"], name: "index_queued_messages_on_domain", length: 8
t.index ["message_id"], name: "index_queued_messages_on_message_id"
t.index ["server_id"], name: "index_queued_messages_on_server_id"
end
create_table "routes", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "uuid"
t.integer "server_id"
t.integer "domain_id"
t.integer "endpoint_id"
t.string "endpoint_type"
t.string "name"
t.string "spam_mode"
t.datetime "created_at"
t.datetime "updated_at"
t.string "token"
t.string "mode"
t.index ["token"], name: "index_routes_on_token", length: 6
end
create_table "scheduled_tasks", charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "name"
t.datetime "next_run_after", precision: nil
t.index ["name"], name: "index_scheduled_tasks_on_name", unique: true
end
create_table "servers", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "organization_id"
t.string "uuid"
t.string "name"
t.string "mode"
t.integer "ip_pool_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "permalink"
t.integer "send_limit"
t.datetime "deleted_at"
t.integer "message_retention_days"
t.integer "raw_message_retention_days"
t.integer "raw_message_retention_size"
t.boolean "allow_sender", default: false
t.string "token"
t.datetime "send_limit_approaching_at"
t.datetime "send_limit_approaching_notified_at"
t.datetime "send_limit_exceeded_at"
t.datetime "send_limit_exceeded_notified_at"
t.decimal "spam_threshold", precision: 8, scale: 2
t.decimal "spam_failure_threshold", precision: 8, scale: 2
t.string "postmaster_address"
t.datetime "suspended_at"
t.decimal "outbound_spam_threshold", precision: 8, scale: 2
t.text "domains_not_to_click_track"
t.string "suspension_reason"
t.boolean "log_smtp_data", default: false
t.boolean "privacy_mode", default: false
t.index ["organization_id"], name: "index_servers_on_organization_id"
t.index ["permalink"], name: "index_servers_on_permalink", length: 6
t.index ["token"], name: "index_servers_on_token", length: 6
t.index ["uuid"], name: "index_servers_on_uuid", length: 8
end
create_table "smtp_endpoints", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "hostname"
t.string "ssl_mode"
t.integer "port"
t.text "error"
t.datetime "disabled_until"
t.datetime "last_used_at"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "statistics", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.bigint "total_messages", default: 0
t.bigint "total_outgoing", default: 0
t.bigint "total_incoming", default: 0
end
create_table "track_certificates", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "domain"
t.text "certificate"
t.text "intermediaries"
t.text "key"
t.datetime "expires_at", precision: nil
t.datetime "renew_after", precision: nil
t.string "verification_path"
t.string "verification_string"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
t.index ["domain"], name: "index_track_certificates_on_domain", length: 8
end
create_table "track_domains", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "uuid"
t.integer "server_id"
t.integer "domain_id"
t.string "name"
t.datetime "dns_checked_at", precision: nil
t.string "dns_status"
t.string "dns_error"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
t.boolean "ssl_enabled", default: true
t.boolean "track_clicks", default: true
t.boolean "track_loads", default: true
t.text "excluded_click_domains"
end
create_table "user_invites", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "uuid"
t.string "email_address"
t.datetime "expires_at"
t.datetime "created_at"
t.datetime "updated_at"
t.index ["uuid"], name: "index_user_invites_on_uuid", length: 12
end
create_table "users", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "uuid"
t.string "first_name"
t.string "last_name"
t.string "email_address"
t.string "password_digest"
t.string "time_zone"
t.string "email_verification_token"
t.datetime "email_verified_at", precision: nil
t.datetime "created_at"
t.datetime "updated_at"
t.string "password_reset_token"
t.datetime "password_reset_token_valid_until", precision: nil
t.boolean "admin", default: false
t.string "oidc_uid"
t.string "oidc_issuer"
t.index ["email_address"], name: "index_users_on_email_address", length: 8
t.index ["uuid"], name: "index_users_on_uuid", length: 8
end
create_table "webhook_events", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "webhook_id"
t.string "event"
t.datetime "created_at"
t.index ["webhook_id"], name: "index_webhook_events_on_webhook_id"
end
create_table "webhook_requests", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.integer "webhook_id"
t.string "url"
t.string "event"
t.string "uuid"
t.text "payload"
t.integer "attempts", default: 0
t.datetime "retry_after"
t.text "error"
t.datetime "created_at"
t.string "locked_by"
t.datetime "locked_at", precision: nil
t.index ["locked_by"], name: "index_webhook_requests_on_locked_by"
end
create_table "webhooks", id: :integer, charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "url"
t.datetime "last_used_at", precision: nil
t.boolean "all_events", default: false
t.boolean "enabled", default: true
t.boolean "sign", default: true
t.datetime "created_at"
t.datetime "updated_at"
t.index ["server_id"], name: "index_webhooks_on_server_id"
end
create_table "worker_roles", charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "role"
t.string "worker"
t.datetime "acquired_at", precision: nil
t.index ["role"], name: "index_worker_roles_on_role", unique: true
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240311205229_add_oidc_fields_to_user.rb | db/migrate/20240311205229_add_oidc_fields_to_user.rb | # frozen_string_literal: true
class AddOIDCFieldsToUser < ActiveRecord::Migration[7.0]
def change
add_column :users, :oidc_uid, :string
add_column :users, :oidc_issuer, :string
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240213165450_create_worker_roles.rb | db/migrate/20240213165450_create_worker_roles.rb | # frozen_string_literal: true
class CreateWorkerRoles < ActiveRecord::Migration[6.1]
def change
create_table :worker_roles do |t|
t.string :role
t.string :worker
t.datetime :acquired_at
t.index :role, unique: true
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20161003195211_add_parent_id_to_authie_sessions.authie.rb | db/migrate/20161003195211_add_parent_id_to_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20150109144120)
class AddParentIdToAuthieSessions < ActiveRecord::Migration
def change
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20210727210551_add_priority_to_ip_addresses.rb | db/migrate/20210727210551_add_priority_to_ip_addresses.rb | # frozen_string_literal: true
class AddPriorityToIPAddresses < ActiveRecord::Migration[5.2]
def change
add_column :ip_addresses, :priority, :integer
IPAddress.where(priority: nil).update_all(priority: 100)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240223141501_add_countries_to_authie_sessions.authie.rb | db/migrate/20240223141501_add_countries_to_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20230627165500)
class AddCountriesToAuthieSessions < ActiveRecord::Migration[6.1]
def change
add_column :authie_sessions, :login_ip_country, :string
add_column :authie_sessions, :two_factored_ip_country, :string
add_column :authie_sessions, :last_activity_ip_country, :string
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240213171830_create_scheduled_tasks.rb | db/migrate/20240213171830_create_scheduled_tasks.rb | # frozen_string_literal: true
class CreateScheduledTasks < ActiveRecord::Migration[6.1]
def change
create_table :scheduled_tasks do |t|
t.string :name
t.datetime :next_run_after
t.index :name, unique: true
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240223141500_add_two_factor_required_to_sessions.authie.rb | db/migrate/20240223141500_add_two_factor_required_to_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20220502180100)
class AddTwoFactorRequiredToSessions < ActiveRecord::Migration[6.1]
def change
add_column :authie_sessions, :skip_two_factor, :boolean, default: false
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20200717083943_add_uuid_to_credentials.rb | db/migrate/20200717083943_add_uuid_to_credentials.rb | # frozen_string_literal: true
class AddUUIDToCredentials < ActiveRecord::Migration[5.2]
def change
add_column :credentials, :uuid, :string
Credential.find_each do |c|
c.update_column(:uuid, SecureRandom.uuid)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20161003195209_create_authie_sessions.authie.rb | db/migrate/20161003195209_create_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20141012174250)
class CreateAuthieSessions < ActiveRecord::Migration
def change
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20161003195212_add_two_factor_auth_fields_to_authie.authie.rb | db/migrate/20161003195212_add_two_factor_auth_fields_to_authie.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20150305135400)
class AddTwoFactorAuthFieldsToAuthie < ActiveRecord::Migration
def change
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20170421195415_add_index_to_token_hashes_on_authie_sessions.authie.rb | db/migrate/20170421195415_add_index_to_token_hashes_on_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20170421174100)
class AddIndexToTokenHashesOnAuthieSessions < ActiveRecord::Migration
def change
add_index :authie_sessions, :token_hash, length: 8
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20170428153353_remove_type_from_ip_pools.rb | db/migrate/20170428153353_remove_type_from_ip_pools.rb | # frozen_string_literal: true
class RemoveTypeFromIPPools < ActiveRecord::Migration[5.0]
def change
remove_column :ip_pools, :type, :string
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20161003195210_add_indexes_to_authie_sessions.authie.rb | db/migrate/20161003195210_add_indexes_to_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20141013115205)
class AddIndexesToAuthieSessions < ActiveRecord::Migration
def change
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20180216114344_add_host_to_authie_sessions.authie.rb | db/migrate/20180216114344_add_host_to_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20180215152200)
class AddHostToAuthieSessions < ActiveRecord::Migration[4.2]
def change
add_column :authie_sessions, :host, :string
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20170418200606_initial_schema.rb | db/migrate/20170418200606_initial_schema.rb | # frozen_string_literal: true
class InitialSchema < ActiveRecord::Migration
def up
create_table "additional_route_endpoints", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "route_id"
t.string "endpoint_type"
t.integer "endpoint_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "address_endpoints", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.string "uuid"
t.string "address"
t.datetime "last_used_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "authie_sessions", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "token"
t.string "browser_id"
t.integer "user_id"
t.boolean "active", default: true
t.text "data", limit: 65_535
t.datetime "expires_at"
t.datetime "login_at"
t.string "login_ip"
t.datetime "last_activity_at"
t.string "last_activity_ip"
t.string "last_activity_path"
t.string "user_agent"
t.datetime "created_at"
t.datetime "updated_at"
t.string "user_type"
t.integer "parent_id"
t.datetime "two_factored_at"
t.string "two_factored_ip"
t.integer "requests", default: 0
t.datetime "password_seen_at"
t.string "token_hash"
t.index ["browser_id"], name: "index_authie_sessions_on_browser_id", length: { browser_id: 8 }, using: :btree
t.index ["token"], name: "index_authie_sessions_on_token", length: { token: 8 }, using: :btree
t.index ["user_id"], name: "index_authie_sessions_on_user_id", using: :btree
end
create_table "credentials", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.string "key"
t.string "type"
t.string "name"
t.text "options", limit: 65_535
t.datetime "last_used_at", precision: 6
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.boolean "hold", default: false
end
create_table "domains", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "verification_token"
t.string "verification_method"
t.datetime "verified_at"
t.text "dkim_private_key", limit: 65_535
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.datetime "dns_checked_at", precision: 6
t.string "spf_status"
t.string "spf_error"
t.string "dkim_status"
t.string "dkim_error"
t.string "mx_status"
t.string "mx_error"
t.string "return_path_status"
t.string "return_path_error"
t.boolean "outgoing", default: true
t.boolean "incoming", default: true
t.string "owner_type"
t.integer "owner_id"
t.string "dkim_identifier_string"
t.boolean "use_for_any"
t.index ["server_id"], name: "index_domains_on_server_id", using: :btree
t.index ["uuid"], name: "index_domains_on_uuid", length: { uuid: 8 }, using: :btree
end
create_table "http_endpoints", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "url"
t.string "encoding"
t.string "format"
t.boolean "strip_replies", default: false
t.text "error", limit: 65_535
t.datetime "disabled_until", precision: 6
t.datetime "last_used_at", precision: 6
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.boolean "include_attachments", default: true
t.integer "timeout"
end
create_table "ip_addresses", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "ip_pool_id"
t.string "ipv4"
t.string "ipv6"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.string "hostname"
end
create_table "ip_pool_rules", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "uuid"
t.string "owner_type"
t.integer "owner_id"
t.integer "ip_pool_id"
t.text "from_text", limit: 65_535
t.text "to_text", limit: 65_535
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "ip_pools", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "name"
t.string "uuid"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.boolean "default", default: false
t.string "type"
t.index ["uuid"], name: "index_ip_pools_on_uuid", length: { uuid: 8 }, using: :btree
end
create_table "organization_ip_pools", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "organization_id"
t.integer "ip_pool_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "organization_users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "organization_id"
t.integer "user_id"
t.datetime "created_at", precision: 6
t.boolean "admin", default: false
t.boolean "all_servers", default: true
t.string "user_type"
end
create_table "organizations", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "uuid"
t.string "name"
t.string "permalink"
t.string "time_zone"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.integer "ip_pool_id"
t.integer "owner_id"
t.datetime "deleted_at", precision: 6
t.datetime "suspended_at", precision: 6
t.string "suspension_reason"
t.index ["permalink"], name: "index_organizations_on_permalink", length: { permalink: 8 }, using: :btree
t.index ["uuid"], name: "index_organizations_on_uuid", length: { uuid: 8 }, using: :btree
end
create_table "queued_messages", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.integer "message_id"
t.string "domain"
t.string "locked_by"
t.datetime "locked_at", precision: 6
t.datetime "retry_after"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.integer "ip_address_id"
t.integer "attempts", default: 0
t.integer "route_id"
t.boolean "manual", default: false
t.string "batch_key"
t.index ["domain"], name: "index_queued_messages_on_domain", length: { domain: 8 }, using: :btree
t.index ["message_id"], name: "index_queued_messages_on_message_id", using: :btree
t.index ["server_id"], name: "index_queued_messages_on_server_id", using: :btree
end
create_table "routes", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "uuid"
t.integer "server_id"
t.integer "domain_id"
t.integer "endpoint_id"
t.string "endpoint_type"
t.string "name"
t.string "spam_mode"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.string "token"
t.string "mode"
t.index ["token"], name: "index_routes_on_token", length: { token: 6 }, using: :btree
end
create_table "servers", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "organization_id"
t.string "uuid"
t.string "name"
t.string "mode"
t.integer "ip_pool_id"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.string "permalink"
t.integer "send_limit"
t.datetime "deleted_at", precision: 6
t.integer "message_retention_days"
t.integer "raw_message_retention_days"
t.integer "raw_message_retention_size"
t.boolean "allow_sender", default: false
t.string "token"
t.datetime "send_limit_approaching_at", precision: 6
t.datetime "send_limit_approaching_notified_at", precision: 6
t.datetime "send_limit_exceeded_at", precision: 6
t.datetime "send_limit_exceeded_notified_at", precision: 6
t.decimal "spam_threshold", precision: 8, scale: 2
t.decimal "spam_failure_threshold", precision: 8, scale: 2
t.string "postmaster_address"
t.datetime "suspended_at", precision: 6
t.decimal "outbound_spam_threshold", precision: 8, scale: 2
t.text "domains_not_to_click_track", limit: 65_535
t.string "suspension_reason"
t.boolean "log_smtp_data", default: false
t.index ["organization_id"], name: "index_servers_on_organization_id", using: :btree
t.index ["permalink"], name: "index_servers_on_permalink", length: { permalink: 6 }, using: :btree
t.index ["token"], name: "index_servers_on_token", length: { token: 6 }, using: :btree
t.index ["uuid"], name: "index_servers_on_uuid", length: { uuid: 8 }, using: :btree
end
create_table "smtp_endpoints", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "hostname"
t.string "ssl_mode"
t.integer "port"
t.text "error", limit: 65_535
t.datetime "disabled_until", precision: 6
t.datetime "last_used_at", precision: 6
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
end
create_table "statistics", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.bigint "total_messages", default: 0
t.bigint "total_outgoing", default: 0
t.bigint "total_incoming", default: 0
end
create_table "track_certificates", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "domain"
t.text "certificate", limit: 65_535
t.text "intermediaries", limit: 65_535
t.text "key", limit: 65_535
t.datetime "expires_at"
t.datetime "renew_after"
t.string "verification_path"
t.string "verification_string"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["domain"], name: "index_track_certificates_on_domain", length: { domain: 8 }, using: :btree
end
create_table "track_domains", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "uuid"
t.integer "server_id"
t.integer "domain_id"
t.string "name"
t.datetime "dns_checked_at"
t.string "dns_status"
t.string "dns_error"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "ssl_enabled", default: true
t.boolean "track_clicks", default: true
t.boolean "track_loads", default: true
t.text "excluded_click_domains", limit: 65_535
end
create_table "user_invites", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "uuid"
t.string "email_address"
t.datetime "expires_at", precision: 6
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.index ["uuid"], name: "index_user_invites_on_uuid", length: { uuid: 12 }, using: :btree
end
create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "uuid"
t.string "first_name"
t.string "last_name"
t.string "email_address"
t.string "password_digest"
t.string "time_zone"
t.string "email_verification_token"
t.datetime "email_verified_at"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.string "password_reset_token"
t.datetime "password_reset_token_valid_until"
t.boolean "admin", default: false
t.index ["email_address"], name: "index_users_on_email_address", length: { email_address: 8 }, using: :btree
t.index ["uuid"], name: "index_users_on_uuid", length: { uuid: 8 }, using: :btree
end
create_table "webhook_events", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "webhook_id"
t.string "event"
t.datetime "created_at", precision: 6
t.index ["webhook_id"], name: "index_webhook_events_on_webhook_id", using: :btree
end
create_table "webhook_requests", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.integer "webhook_id"
t.string "url"
t.string "event"
t.string "uuid"
t.text "payload", limit: 65_535
t.integer "attempts", default: 0
t.datetime "retry_after", precision: 6
t.text "error", limit: 65_535
t.datetime "created_at", precision: 6
end
create_table "webhooks", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.integer "server_id"
t.string "uuid"
t.string "name"
t.string "url"
t.datetime "last_used_at"
t.boolean "all_events", default: false
t.boolean "enabled", default: true
t.boolean "sign", default: true
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6
t.index ["server_id"], name: "index_webhooks_on_server_id", using: :btree
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20170421195414_add_token_hashes_to_authie_sessions.authie.rb | db/migrate/20170421195414_add_token_hashes_to_authie_sessions.authie.rb | # frozen_string_literal: true
# This migration comes from authie (originally 20170417170000)
class AddTokenHashesToAuthieSessions < ActiveRecord::Migration
def change
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240206173036_add_privacy_mode_to_servers.rb | db/migrate/20240206173036_add_privacy_mode_to_servers.rb | # frozen_string_literal: true
class AddPrivacyModeToServers < ActiveRecord::Migration[6.1]
def change
add_column :servers, :privacy_mode, :boolean, default: false
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/db/migrate/20240214132253_add_lock_fields_to_webhook_requests.rb | db/migrate/20240214132253_add_lock_fields_to_webhook_requests.rb | # frozen_string_literal: true
class AddLockFieldsToWebhookRequests < ActiveRecord::Migration[6.1]
def change
add_column :webhook_requests, :locked_by, :string
add_column :webhook_requests, :locked_at, :datetime
add_index :webhook_requests, :locked_by
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/rails_helper.rb | spec/rails_helper.rb | # frozen_string_literal: true
ENV["POSTAL_CONFIG_FILE_PATH"] ||= "config/postal/postal.test.yml"
require "dotenv"
Dotenv.load(".env.test")
require File.expand_path("../config/environment", __dir__)
require "rspec/rails"
require "spec_helper"
require "factory_bot"
require "timecop"
require "webmock/rspec"
require "shoulda-matchers"
DatabaseCleaner.allow_remote_database_url = true
ActiveRecord::Base.logger = Logger.new("/dev/null")
Dir[File.expand_path("helpers/**/*.rb", __dir__)].each { |f| require f }
ActionMailer::Base.delivery_method = :test
ActiveRecord::Migration.maintain_test_schema!
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.include FactoryBot::Syntax::Methods
config.include GeneralHelpers
# Before all request specs, set the hostname to the web hostname for
# Postal otherwise it'll be www.example.com which will fail host
# authorization checks.
config.before(:each, type: :request) do
host! Postal::Config.postal.web_hostname
end
# Test that the factories are working as they should and then clean up before getting started on
# the rest of the suite.
config.before(:suite) do
DatabaseCleaner.start
FactoryBot.lint
ensure
DatabaseCleaner.clean
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.color = true
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/senders/smtp_sender_spec.rb | spec/senders/smtp_sender_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe SMTPSender do
subject(:sender) { described_class.new("example.com") }
let(:smtp_start_error) { nil }
let(:smtp_send_message_error) { nil }
let(:smtp_send_message_result) { double("Result", string: "accepted") }
before do
# Mock the SMTP client endpoint so that we can avoid making any actual
# SMTP connections but still mock things as appropriate.
allow(SMTPClient::Endpoint).to receive(:new).and_wrap_original do |original, *args, **kwargs|
endpoint = original.call(*args, **kwargs)
allow(endpoint).to receive(:start_smtp_session) do |**ikwargs|
if error = smtp_start_error&.call(endpoint, ikwargs[:allow_ssl])
raise error
end
end
allow(endpoint).to receive(:send_message) do |message|
if error = smtp_send_message_error&.call(endpoint, message)
raise error
end
smtp_send_message_result
end
allow(endpoint).to receive(:finish_smtp_session)
allow(endpoint).to receive(:reset_smtp_session)
allow(endpoint).to receive(:smtp_client) do
Net::SMTP.new(endpoint.ip_address, endpoint.server.port)
end
endpoint
end
end
before do
# Override the DNS resolver to return empty arrays by default for A and AAAA
# DNS lookups to avoid making requests to public servers.
allow(DNSResolver.local).to receive(:aaaa).and_return([])
allow(DNSResolver.local).to receive(:a).and_return([])
end
describe "#start" do
context "when no servers are provided to the class and there are no SMTP relays" do
context "when there are MX records" do
before do
allow(DNSResolver.local).to receive(:mx).and_return([[5, "mx1.example.com"], [10, "mx2.example.com"]])
allow(DNSResolver.local).to receive(:a).with("mx1.example.com").and_return(["1.2.3.4"])
allow(DNSResolver.local).to receive(:a).with("mx2.example.com").and_return(["6.7.8.9"])
end
it "attempts to create an SMTP connection for each endpoint for each MX server for them" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(
ip_address: "1.2.3.4",
server: have_attributes(hostname: "mx1.example.com", port: 25, ssl_mode: SMTPClient::SSLModes::AUTO)
)
end
end
context "when there are no MX records" do
before do
allow(DNSResolver.local).to receive(:mx).and_return([])
allow(DNSResolver.local).to receive(:a).with("example.com").and_return(["1.2.3.4"])
end
it "attempts to create an SMTP connection for the domain itself" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(
ip_address: "1.2.3.4",
server: have_attributes(hostname: "example.com", port: 25, ssl_mode: SMTPClient::SSLModes::AUTO)
)
end
end
context "when the MX lookup times out" do
before do
allow(DNSResolver.local).to receive(:mx).and_raise(Resolv::ResolvError.new("DNS resolv timeout: example.com"))
allow(DNSResolver.local).to receive(:a).with("example.com").and_return(["1.2.3.4"])
end
it "raises an error" do
expect { sender.start }.to raise_error Resolv::ResolvError
end
end
end
context "when there are no servers provided to the class but there are SMTP relays" do
before do
allow(SMTPSender).to receive(:smtp_relays).and_return([SMTPClient::Server.new("relay.example.com", port: 2525, ssl_mode: SMTPClient::SSLModes::TLS)])
allow(DNSResolver.local).to receive(:a).with("relay.example.com").and_return(["1.2.3.4"])
end
it "attempts to use the relays" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(
ip_address: "1.2.3.4",
server: have_attributes(hostname: "relay.example.com", port: 2525, ssl_mode: SMTPClient::SSLModes::TLS)
)
end
end
context "when there are servers provided to the class" do
let(:server) { SMTPClient::Server.new("custom.example.com") }
subject(:sender) { described_class.new("example.com", servers: [server]) }
before do
allow(DNSResolver.local).to receive(:a).with("custom.example.com").and_return(["1.2.3.4"])
end
it "uses the provided servers" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(
ip_address: "1.2.3.4",
server: server
)
end
end
context "when a source IP is given without IPv6 and an endpoint is IPv6 enabled" do
let(:source_ip_address) { create(:ip_address, ipv6: nil) }
let(:server) { SMTPClient::Server.new("custom.example.com") }
subject(:sender) { described_class.new("example.com", source_ip_address, servers: [server]) }
before do
allow(DNSResolver.local).to receive(:aaaa).with("custom.example.com").and_return(["2a00:67a0:a::1"])
allow(DNSResolver.local).to receive(:a).with("custom.example.com").and_return(["1.2.3.4"])
end
it "returns the IPv4 version" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(
ip_address: "1.2.3.4",
server: server
)
end
end
context "when there are no servers to connect to" do
it "returns false" do
expect(sender.start).to be false
end
end
context "when the first server tried cannot be connected to" do
let(:server1) { SMTPClient::Server.new("custom1.example.com") }
let(:server2) { SMTPClient::Server.new("custom2.example.com") }
let(:smtp_start_error) do
proc do |endpoint|
Errno::ECONNREFUSED if endpoint.ip_address == "1.2.3.4"
end
end
before do
allow(DNSResolver.local).to receive(:a).with("custom1.example.com").and_return(["1.2.3.4"])
allow(DNSResolver.local).to receive(:a).with("custom2.example.com").and_return(["2.3.4.5"])
end
subject(:sender) { described_class.new("example.com", servers: [server1, server2]) }
it "tries the second" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(
ip_address: "2.3.4.5",
server: have_attributes(hostname: "custom2.example.com")
)
end
it "includes both endpoints in the array of endpoints tried" do
sender.start
expect(sender.endpoints).to match([
have_attributes(ip_address: "1.2.3.4"),
have_attributes(ip_address: "2.3.4.5"),
])
end
end
context "when the server returns an SSL error and SSL mode is Auto" do
let(:server) { SMTPClient::Server.new("custom.example.com") }
let(:smtp_start_error) do
proc do |endpoint, allow_ssl|
OpenSSL::SSL::SSLError if allow_ssl && endpoint.server.ssl_mode == "Auto"
end
end
before do
allow(DNSResolver.local).to receive(:aaaa).with("custom.example.com").and_return([])
allow(DNSResolver.local).to receive(:a).with("custom.example.com").and_return(["1.2.3.4"])
end
subject(:sender) { described_class.new("example.com", servers: [server]) }
it "attempts to reconnect without SSL" do
endpoint = sender.start
expect(endpoint).to be_a SMTPClient::Endpoint
expect(endpoint).to have_attributes(ip_address: "1.2.3.4")
end
end
end
describe "#send_message" do
let(:server) { create(:server) }
let(:domain) { create(:domain, server: server) }
let(:dns_result) { [] }
let(:message) { MessageFactory.outgoing(server, domain: domain) }
let(:smtp_client_server) { SMTPClient::Server.new("mx1.example.com") }
subject(:sender) { described_class.new("example.com", servers: [smtp_client_server]) }
before do
allow(DNSResolver.local).to receive(:a).with("mx1.example.com").and_return(dns_result)
sender.start
end
context "when there is no current endpoint to use" do
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
retry: true,
output: "",
details: /No SMTP servers were available for example.com. No hosts to try./,
connect_error: true
)
end
end
context "when there is an endpoint" do
let(:dns_result) { ["1.2.3.4"] }
context "it sends the message to the endpoint" do
context "if the message is a bounce" do
let(:message) { MessageFactory.outgoing(server, domain: domain) { |m| m.bounce = true } }
it "sends an empty MAIL FROM" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
kind_of(String),
"",
["john@example.com"]
)
end
end
context "if the domain has a valid custom return path" do
let(:domain) { create(:domain, return_path_status: "OK") }
it "sends the custom return path as MAIL FROM" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
kind_of(String),
"#{server.token}@#{domain.return_path_domain}",
["john@example.com"]
)
end
end
context "if the domain has no valid custom return path" do
it "sends the server default return path as MAIL FROM" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
kind_of(String),
"#{server.token}@#{Postal::Config.dns.return_path_domain}",
["john@example.com"]
)
end
end
context "if the sender has specified an RCPT TO" do
subject(:sender) { described_class.new("example.com", servers: [smtp_client_server], rcpt_to: "custom@example.com") }
it "sends the specified RCPT TO" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
kind_of(String),
kind_of(String),
["custom@example.com"]
)
end
end
context "if the sender has not specified an RCPT TO" do
it "uses the RCPT TO from the message" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
kind_of(String),
kind_of(String),
["john@example.com"]
)
end
end
context "if the configuration says to add the Resent-Sender header" do
it "adds the resent-sender header" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
"Resent-Sender: #{server.token}@#{Postal::Config.dns.return_path_domain}\r\n#{message.raw_message}",
kind_of(String),
kind_of(Array)
)
end
end
context "if the configuration says to not add the Resent-From header" do
before do
allow(Postal::Config.postal).to receive(:use_resent_sender_header?).and_return(false)
end
it "does not add the resent-from header" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:send_message).with(
message.raw_message,
kind_of(String),
kind_of(Array)
)
end
end
end
context "when the message is accepted" do
it "returns a Sent result" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "Sent",
details: "Message for john@example.com accepted by 1.2.3.4:25 (mx1.example.com)",
output: "accepted"
)
end
end
context "when SMTP server is busy" do
let(:smtp_send_message_error) { proc { Net::SMTPServerBusy.new("SMTP server was busy") } }
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
retry: true,
details: /Temporary SMTP delivery error when sending/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
context "when the SMTP server returns an error if a retry time in seconds" do
let(:smtp_send_message_error) { proc { Net::SMTPServerBusy.new("Try again in 30 seconds") } }
it "returns a SoftFail with the retry time from the error" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
retry: 40
)
end
end
context "when the SMTP server returns an error if a retry time in minutes" do
let(:smtp_send_message_error) { proc { Net::SMTPServerBusy.new("Try again in 5 minutes") } }
it "returns a SoftFail with the retry time from the error" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
retry: 310
)
end
end
context "when there is an SMTP authentication error" do
let(:smtp_send_message_error) { proc { Net::SMTPAuthenticationError.new("Denied") } }
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
details: /Temporary SMTP delivery error when sending/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
context "when there is a timeout" do
let(:smtp_send_message_error) { proc { Net::ReadTimeout.new } }
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
details: /Temporary SMTP delivery error when sending/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
context "when there is an SMTP syntax error" do
let(:smtp_send_message_error) { proc { Net::SMTPSyntaxError.new("Syntax error") } }
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
output: "Syntax error",
details: /Temporary SMTP delivery error when sending/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
context "when there is an unknown SMTP error" do
let(:smtp_send_message_error) { proc { Net::SMTPUnknownError.new("unknown error") } }
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
output: "unknown error",
details: /Temporary SMTP delivery error when sending/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
context "when there is an fatal SMTP error" do
let(:smtp_send_message_error) { proc { Net::SMTPFatalError.new("fatal error") } }
it "returns a HardFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "HardFail",
output: "fatal error",
details: /Permanent SMTP delivery error when sending/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
context "when there is an unexpected error" do
let(:smtp_send_message_error) { proc { ZeroDivisionError.new("divided by 0") } }
it "returns a SoftFail" do
result = sender.send_message(message)
expect(result).to be_a SendResult
expect(result).to have_attributes(
type: "SoftFail",
output: "divided by 0",
details: /An error occurred while sending the message/
)
end
it "resets the endpoint SMTP sesssion" do
sender.send_message(message)
expect(sender.endpoints.last).to have_received(:reset_smtp_session)
end
end
end
end
describe "#finish" do
let(:server) { SMTPClient::Server.new("custom.example.com") }
subject(:sender) { described_class.new("example.com", servers: [server]) }
let(:smtp_start_error) do
proc do |endpoint|
Errno::ECONNREFUSED if endpoint.ip_address == "1.2.3.4"
end
end
before do
allow(DNSResolver.local).to receive(:a).with("custom.example.com").and_return(["1.2.3.4", "2.3.4.5"])
sender.start
end
it "calls finish_smtp_session on all endpoints" do
sender.finish
expect(sender.endpoints.size).to eq 2
expect(sender.endpoints).to all have_received(:finish_smtp_session).at_least(:once)
end
end
describe ".smtp_relays" do
before do
if described_class.instance_variable_defined?("@smtp_relays")
described_class.remove_instance_variable("@smtp_relays")
end
end
it "returns nil if smtp relays is nil" do
allow(Postal::Config.postal).to receive(:smtp_relays).and_return(nil)
expect(described_class.smtp_relays).to be nil
end
it "returns nil if there are no smtp relays" do
allow(Postal::Config.postal).to receive(:smtp_relays).and_return([])
expect(described_class.smtp_relays).to be nil
end
it "does not return relays where the host is nil" do
allow(Postal::Config.postal).to receive(:smtp_relays).and_return([
Hashie::Mash.new(host: nil, port: 25, ssl_mode: "Auto"),
Hashie::Mash.new(host: "test.example.com", port: 25, ssl_mode: "Auto"),
])
expect(described_class.smtp_relays).to match [kind_of(SMTPClient::Server)]
end
it "returns relays with options" do
allow(Postal::Config.postal).to receive(:smtp_relays).and_return([
Hashie::Mash.new(host: "test.example.com", port: 25, ssl_mode: "Auto"),
Hashie::Mash.new(host: "test2.example.com", port: 2525, ssl_mode: "TLS"),
])
expect(described_class.smtp_relays).to match [
have_attributes(hostname: "test.example.com", port: 25, ssl_mode: "Auto"),
have_attributes(hostname: "test2.example.com", port: 2525, ssl_mode: "TLS"),
]
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/services/webhook_delivery_service_spec.rb | spec/services/webhook_delivery_service_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe WebhookDeliveryService do
let(:server) { create(:server) }
let(:webhook) { create(:webhook, server: server) }
let(:webhook_request) { create(:webhook_request, :locked, webhook: webhook) }
subject(:service) { described_class.new(webhook_request: webhook_request) }
let(:response_status) { 200 }
let(:response_body) { "OK" }
before do
stub_request(:post, webhook.url).to_return(status: response_status, body: response_body)
end
describe "#call" do
it "sends a request to the webhook's url" do
service.call
expect(WebMock).to have_requested(:post, webhook.url).with({
body: {
event: webhook_request.event,
timestamp: webhook_request.created_at.to_f,
payload: webhook_request.payload,
uuid: webhook_request.uuid
}.to_json,
headers: {
"Content-Type" => "application/json",
"X-Postal-Signature" => /\A[a-z0-9\/+]+=*\z/i,
"X-Postal-Signature-256" => /\A[a-z0-9\/+]+=*\z/i,
"X-Postal-Signature-KID" => /\A[a-f0-9\/+]{64}\z/i
}
})
end
context "when the endpoint returns a 200 OK" do
it "creates a webhook request for the server" do
service.call
expect(server.message_db.webhooks.list(1)[:total]).to eq(1)
webhook_request = server.message_db.webhooks.list(1)[:records].first
expect(webhook_request).to have_attributes(
event: webhook_request.event,
url: webhook_request.url,
status_code: 200,
body: "OK",
uuid: webhook_request.uuid,
will_retry?: false,
payload: webhook_request.payload,
attempt: 1,
timestamp: webhook_request.timestamp
)
end
it "deletes the webhook request" do
service.call
expect { webhook_request.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it "updates the last used at time on the webhook" do
frozen_time = Time.current.change(usec: 0)
Timecop.freeze(frozen_time) do
service.call
expect(webhook.reload.last_used_at).to eq(frozen_time)
end
end
end
context "when the request returns a 500 Internal Server Error for the first time" do
let(:response_status) { 500 }
let(:response_body) { "internal server error!" }
it "unlocks the webhook request if locked" do
expect { service.call }.to change { webhook_request.reload.locked? }.from(true).to(false)
end
it "updates the retry time and attempt counter" do
service.call
expect(webhook_request.reload.attempts).to eq(1)
expect(webhook_request.retry_after).to be_within(1.second).of(2.minutes.from_now)
end
end
context "when the request returns a 500 Internal Server Error for the second time" do
let(:webhook_request) { create(:webhook_request, :locked, webhook: webhook, attempts: 1) }
let(:response_status) { 500 }
let(:response_body) { "internal server error!" }
it "updates the retry time and attempt counter" do
service.call
expect(webhook_request.reload.attempts).to eq(2)
expect(webhook_request.retry_after).to be_within(1.second).of(3.minutes.from_now)
end
end
context "when the request returns a 500 Internal Server Error for the sixth time" do
let(:webhook_request) { create(:webhook_request, :locked, webhook: webhook, attempts: 5) }
let(:response_status) { 500 }
let(:response_body) { "internal server error!" }
it "creates a webhook request for the server" do
service.call
expect(server.message_db.webhooks.list(1)[:total]).to eq(1)
webhook_request = server.message_db.webhooks.list(1)[:records].first
expect(webhook_request).to have_attributes(
status_code: 500,
body: "internal server error!",
will_retry?: false,
attempt: 6
)
end
it "deletes the webhook request" do
service.call
expect { webhook_request.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/helpers/message_factory.rb | spec/helpers/message_factory.rb | # frozen_string_literal: true
# This class can be used to generate a message which can be used for the purposes of
# testing within the given server.
class MessageFactory
def initialize(server)
@server = server
end
def incoming(route: nil, &block)
@message = @server.message_db.new_message
@message.scope = "incoming"
@message.rcpt_to = "test@example.com"
@message.mail_from = "john@example.com"
if route
@message.rcpt_to = route.description
@message.route_id = route.id
end
create_message(&block)
end
def outgoing(domain: nil, credential: nil, &block)
@message = @server.message_db.new_message
@message.scope = "outgoing"
@message.rcpt_to = "john@example.com"
@message.mail_from = "test@example.com"
if domain
@message.mail_from = "test@#{domain.name}"
@message.domain_id = domain.id
end
if credential
@message.credential_id = credential.id
end
create_message(&block)
end
class << self
def incoming(server, **kwargs, &block)
new(server).incoming(**kwargs, &block)
end
def outgoing(server, **kwargs, &block)
new(server).outgoing(**kwargs, &block)
end
end
private
def create_message
mail = create_mail(@message.rcpt_to, @message.mail_from)
if block_given?
yield @message, mail
end
@message.raw_message = mail.to_s
@message.save(queue_on_create: false)
@message
end
def create_mail(to, from)
mail = Mail.new
mail.to = to
mail.from = from
mail.subject = "An example message"
mail.body = "Hello world!"
mail
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/helpers/message_db_mocking.rb | spec/helpers/message_db_mocking.rb | # frozen_string_literal: true
module GlobalMessageDB
class << self
def find_or_create
return @db if @db
@db = Postal::MessageDB::Database.new(1, 1, database_name: "postal-test-message-db")
@db.provisioner.provision
end
def exists?
!@db.nil?
end
end
end
RSpec.configure do |config|
config.before(:example) do
@mocked_message_dbs = []
allow_any_instance_of(Server).to receive(:message_db).and_wrap_original do |m|
GlobalMessageDB.find_or_create
message_db = m.call
@mocked_message_dbs << message_db
allow(message_db).to receive(:database_name).and_return("postal-test-message-db")
message_db
end
end
config.after(:example) do
if GlobalMessageDB.exists? && @mocked_message_dbs.present?
GlobalMessageDB.find_or_create.provisioner.clean
@mocked_message_dbs = []
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/helpers/general_helpers.rb | spec/helpers/general_helpers.rb | # frozen_string_literal: true
module GeneralHelpers
def create_plain_text_message(server, text, to = "test@example.com", override_attributes = {})
domain = create(:domain, owner: server)
attributes = { from: "test@#{domain.name}", subject: "Test Plain Text Message" }.merge(override_attributes)
attributes[:to] = to
attributes[:plain_body] = text
message = OutgoingMessagePrototype.new(server, "127.0.0.1", "testsuite", attributes)
result = message.create_message(to)
server.message_db.message(result[:id])
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/helpers/test_logger.rb | spec/helpers/test_logger.rb | # frozen_string_literal: true
class TestLogger
def initialize
@log_lines = []
@group_set = Klogger::GroupSet.new
@print = false
end
def print!
@print = true
end
def add(level, message, **tags)
@group_set.groups.each do |group|
tags = group[:tags].merge(tags)
end
@log_lines << { level: level, message: message, tags: tags }
puts message if @print
true
end
[:info, :debug, :warn, :error].each do |level|
define_method(level) do |message, **tags|
add(level, message, **tags)
end
end
def tagged(**tags, &block)
@group_set.call_without_id(**tags, &block)
end
def log_line(match)
@log_lines.reverse.each do |log_line|
return log_line if match.is_a?(String) && log_line[:message] == match
return log_line if match.is_a?(Regexp) && log_line[:message] =~ match
end
nil
end
def has_logged?(match)
!!log_line(match)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/scheduled_tasks/tidy_queued_messages_task_spec.rb | spec/scheduled_tasks/tidy_queued_messages_task_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe TidyQueuedMessagesTask do
let(:logger) { TestLogger.new }
subject(:task) { described_class.new(logger: logger) }
describe "#call" do
it "destroys queued messages with stale locks" do
stale_message = create(:queued_message, locked_at: 2.days.ago, locked_by: "test")
task.call
expect { stale_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect(logger).to have_logged(/removing queued message \d+/)
end
it "does not destroy messages which are not locked" do
message = create(:queued_message)
task.call
expect { message.reload }.not_to raise_error
end
it "does not destroy messages which where were locked less then the number of stale days" do
message = create(:queued_message, locked_at: 10.minutes.ago, locked_by: "test")
task.call
expect { message.reload }.not_to raise_error
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/track_domain_factory.rb | spec/factories/track_domain_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: track_domains
#
# id :integer not null, primary key
# uuid :string(255)
# server_id :integer
# domain_id :integer
# name :string(255)
# dns_checked_at :datetime
# dns_status :string(255)
# dns_error :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# ssl_enabled :boolean default(TRUE)
# track_clicks :boolean default(TRUE)
# track_loads :boolean default(TRUE)
# excluded_click_domains :text(65535)
#
FactoryBot.define do
factory :track_domain do
name { "click" }
dns_status { "OK" }
association :server
after(:build) do |track_domain|
track_domain.domain ||= create(:domain, owner: track_domain.server)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/credential_factory.rb | spec/factories/credential_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: credentials
#
# id :integer not null, primary key
# hold :boolean default(FALSE)
# key :string(255)
# last_used_at :datetime
# name :string(255)
# options :text(65535)
# type :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# server_id :integer
#
FactoryBot.define do
factory :credential do
server
name { "Example Credential" }
type { "API" }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/ip_pool_factory.rb | spec/factories/ip_pool_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: ip_pools
#
# id :integer not null, primary key
# default :boolean default(FALSE)
# name :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_ip_pools_on_uuid (uuid)
#
FactoryBot.define do
factory :ip_pool do
name { "Default Pool" }
default { true }
trait :with_ip_address do
after(:create) do |ip_pool|
ip_pool.ip_addresses << create(:ip_address, ip_pool: ip_pool)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/user_factory.rb | spec/factories/user_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# admin :boolean default(FALSE)
# email_address :string(255)
# email_verification_token :string(255)
# email_verified_at :datetime
# first_name :string(255)
# last_name :string(255)
# oidc_issuer :string(255)
# oidc_uid :string(255)
# password_digest :string(255)
# password_reset_token :string(255)
# password_reset_token_valid_until :datetime
# time_zone :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_users_on_email_address (email_address)
# index_users_on_uuid (uuid)
#
FactoryBot.define do
factory :user do
first_name { "John" }
last_name { "Doe" }
password { "passw0rd" }
email_verified_at { Time.now }
sequence(:email_address) { |n| "user#{n}@example.com" }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/route_factory.rb | spec/factories/route_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: routes
#
# id :integer not null, primary key
# endpoint_type :string(255)
# mode :string(255)
# name :string(255)
# spam_mode :string(255)
# token :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# domain_id :integer
# endpoint_id :integer
# server_id :integer
#
# Indexes
#
# index_routes_on_token (token)
#
FactoryBot.define do
factory :route do
name { "test" }
mode { "Accept" }
spam_mode { "Mark" }
before(:create) do |route|
route.server ||= create(:server)
route.domain ||= create(:domain, owner: route.server)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/organization_factory.rb | spec/factories/organization_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: organizations
#
# id :integer not null, primary key
# uuid :string(255)
# name :string(255)
# permalink :string(255)
# time_zone :string(255)
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
# owner_id :integer
# deleted_at :datetime
# suspended_at :datetime
# suspension_reason :string(255)
#
# Indexes
#
# index_organizations_on_permalink (permalink)
# index_organizations_on_uuid (uuid)
#
FactoryBot.define do
factory :organization do
name { "Acme Inc" }
sequence(:permalink) { |n| "org#{n}" }
association :owner, factory: :user
trait :suspended do
suspended_at { 1.day.ago }
suspension_reason { "test" }
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/webhook_request_factory.rb | spec/factories/webhook_request_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: webhook_requests
#
# id :integer not null, primary key
# attempts :integer default(0)
# error :text(65535)
# event :string(255)
# locked_at :datetime
# locked_by :string(255)
# payload :text(65535)
# retry_after :datetime
# url :string(255)
# uuid :string(255)
# created_at :datetime
# server_id :integer
# webhook_id :integer
#
# Indexes
#
# index_webhook_requests_on_locked_by (locked_by)
#
FactoryBot.define do
factory :webhook_request do
webhook
url { "https://example.com" }
event { "ExampleEvent" }
payload { { "hello" => "world" } }
before(:create) do |webhook_request|
webhook_request.server = webhook_request.webhook&.server
end
trait :locked do
locked_by { "test" }
locked_at { 5.minutes.ago }
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/server_factory.rb | spec/factories/server_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: servers
#
# id :integer not null, primary key
# allow_sender :boolean default(FALSE)
# deleted_at :datetime
# domains_not_to_click_track :text(65535)
# log_smtp_data :boolean default(FALSE)
# message_retention_days :integer
# mode :string(255)
# name :string(255)
# outbound_spam_threshold :decimal(8, 2)
# permalink :string(255)
# postmaster_address :string(255)
# privacy_mode :boolean default(FALSE)
# raw_message_retention_days :integer
# raw_message_retention_size :integer
# send_limit :integer
# send_limit_approaching_at :datetime
# send_limit_approaching_notified_at :datetime
# send_limit_exceeded_at :datetime
# send_limit_exceeded_notified_at :datetime
# spam_failure_threshold :decimal(8, 2)
# spam_threshold :decimal(8, 2)
# suspended_at :datetime
# suspension_reason :string(255)
# token :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
# organization_id :integer
#
# Indexes
#
# index_servers_on_organization_id (organization_id)
# index_servers_on_permalink (permalink)
# index_servers_on_token (token)
# index_servers_on_uuid (uuid)
#
FactoryBot.define do
factory :server do
association :organization
name { "Mail Server" }
mode { "Live" }
provision_database { false }
sequence(:permalink) { |n| "server#{n}" }
trait :suspended do
suspended_at { Time.current }
suspension_reason { "Test Reason" }
end
trait :exceeded_send_limit do
send_limit_approaching_at { 5.minutes.ago }
send_limit_exceeded_at { 1.minute.ago }
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/webhook_factory.rb | spec/factories/webhook_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: webhooks
#
# id :integer not null, primary key
# all_events :boolean default(FALSE)
# enabled :boolean default(TRUE)
# last_used_at :datetime
# name :string(255)
# sign :boolean default(TRUE)
# url :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# server_id :integer
#
# Indexes
#
# index_webhooks_on_server_id (server_id)
#
FactoryBot.define do
factory :webhook do
server
name { "Example Webhook" }
url { "https://example.com" }
all_events { true }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/ip_pool_rule_factory.rb | spec/factories/ip_pool_rule_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: ip_pool_rules
#
# id :integer not null, primary key
# from_text :text(65535)
# owner_type :string(255)
# to_text :text(65535)
# uuid :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# ip_pool_id :integer
# owner_id :integer
#
FactoryBot.define do
factory :ip_pool_rule do
owner factory: :organization
ip_pool
to_text { "google.com" }
after(:build) do |ip_pool_rule|
if ip_pool_rule.ip_pool.organizations.empty? && ip_pool_rule.owner.is_a?(Organization)
ip_pool_rule.ip_pool.organizations << ip_pool_rule.owner
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/domain_factory.rb | spec/factories/domain_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: domains
#
# id :integer not null, primary key
# server_id :integer
# uuid :string(255)
# name :string(255)
# verification_token :string(255)
# verification_method :string(255)
# verified_at :datetime
# dkim_private_key :text(65535)
# created_at :datetime
# updated_at :datetime
# dns_checked_at :datetime
# spf_status :string(255)
# spf_error :string(255)
# dkim_status :string(255)
# dkim_error :string(255)
# mx_status :string(255)
# mx_error :string(255)
# return_path_status :string(255)
# return_path_error :string(255)
# outgoing :boolean default(TRUE)
# incoming :boolean default(TRUE)
# owner_type :string(255)
# owner_id :integer
# dkim_identifier_string :string(255)
# use_for_any :boolean
#
# Indexes
#
# index_domains_on_server_id (server_id)
# index_domains_on_uuid (uuid)
#
FactoryBot.define do
factory :domain do
association :owner, factory: :organization
sequence(:name) { |n| "example#{n}.com" }
verification_method { "DNS" }
verified_at { Time.now }
trait :unverified do
verified_at { nil }
end
trait :dns_all_ok do
spf_status { "OK" }
dkim_status { "OK" }
mx_status { "OK" }
return_path_status { "OK" }
end
end
factory :organization_domain, parent: :domain do
association :owner, factory: :organization
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/http_endpoint_factory.rb | spec/factories/http_endpoint_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: http_endpoints
#
# id :integer not null, primary key
# disabled_until :datetime
# encoding :string(255)
# error :text(65535)
# format :string(255)
# include_attachments :boolean default(TRUE)
# last_used_at :datetime
# name :string(255)
# strip_replies :boolean default(FALSE)
# timeout :integer
# url :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# server_id :integer
#
FactoryBot.define do
factory :http_endpoint do
server
name { "HTTP endpoint" }
url { "https://example.com/endpoint" }
encoding { "BodyAsJSON" }
format { "Hash" }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/queued_message_factory.rb | spec/factories/queued_message_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: queued_messages
#
# id :integer not null, primary key
# attempts :integer default(0)
# batch_key :string(255)
# domain :string(255)
# locked_at :datetime
# locked_by :string(255)
# manual :boolean default(FALSE)
# retry_after :datetime
# created_at :datetime
# updated_at :datetime
# ip_address_id :integer
# message_id :integer
# route_id :integer
# server_id :integer
#
# Indexes
#
# index_queued_messages_on_domain (domain)
# index_queued_messages_on_message_id (message_id)
# index_queued_messages_on_server_id (server_id)
#
FactoryBot.define do
factory :queued_message do
domain { "example.com" }
transient do
message { nil }
end
after(:build) do |message, evaluator|
if evaluator.message
message.server = evaluator.message.server
message.message_id = evaluator.message.id
message.batch_key = evaluator.message.batch_key
message.domain = evaluator.message.recipient_domain
message.route_id = evaluator.message.route_id
else
message.server ||= create(:server)
message.message_id ||= 0
end
end
trait :locked do
locked_by { "worker1" }
locked_at { 5.minutes.ago }
end
trait :retry_in_future do
attempts { 2 }
retry_after { 1.hour.from_now }
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/smtp_endpoint_factory.rb | spec/factories/smtp_endpoint_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: smtp_endpoints
#
# id :integer not null, primary key
# disabled_until :datetime
# error :text(65535)
# hostname :string(255)
# last_used_at :datetime
# name :string(255)
# port :integer
# ssl_mode :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# server_id :integer
#
FactoryBot.define do
factory :smtp_endpoint do
server
name { "Example SMTP Endpoint" }
hostname { "example.com" }
ssl_mode { "None" }
port { 25 }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/worker_role_factory.rb | spec/factories/worker_role_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: worker_roles
#
# id :bigint not null, primary key
# acquired_at :datetime
# role :string(255)
# worker :string(255)
#
# Indexes
#
# index_worker_roles_on_role (role) UNIQUE
#
FactoryBot.define do
factory :worker_role do
role { "test" }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/ip_address_factory.rb | spec/factories/ip_address_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: ip_addresses
#
# id :integer not null, primary key
# hostname :string(255)
# ipv4 :string(255)
# ipv6 :string(255)
# priority :integer
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
#
FactoryBot.define do
factory :ip_address do
ip_pool
ipv4 { "10.0.0.1" }
ipv6 { "2001:0db8:85a3:0000:0000:8a2e:0370:7334" }
hostname { "ip.example.com" }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/factories/address_endpoint_factory.rb | spec/factories/address_endpoint_factory.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: address_endpoints
#
# id :integer not null, primary key
# address :string(255)
# last_used_at :datetime
# uuid :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# server_id :integer
#
FactoryBot.define do
factory :address_endpoint do
server
sequence(:address) { |n| "test#{n}@example.com" }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/worker_role_spec.rb | spec/models/worker_role_spec.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: worker_roles
#
# id :bigint not null, primary key
# acquired_at :datetime
# role :string(255)
# worker :string(255)
#
# Indexes
#
# index_worker_roles_on_role (role) UNIQUE
#
require "rails_helper"
RSpec.describe WorkerRole do
let(:locker_name) { "test" }
before do
allow(Postal).to receive(:locker_name).and_return(locker_name)
end
describe ".acquire" do
context "when there are no existing roles" do
it "returns :created" do
expect(WorkerRole.acquire("test")).to eq(:created)
end
end
context "when the current process holds a lock for a role" do
it "returns :renewed" do
create(:worker_role, role: "test", worker: "test", acquired_at: 1.minute.ago)
expect(WorkerRole.acquire("test")).to eq(:renewed)
end
end
context "when the role has become stale" do
it "returns :stolen" do
create(:worker_role, role: "test", worker: "another", acquired_at: 10.minute.ago)
expect(WorkerRole.acquire("test")).to eq(:stolen)
end
end
context "when the role is already locked by another worker" do
it "returns false" do
create(:worker_role, role: "test", worker: "another", acquired_at: 1.minute.ago)
expect(WorkerRole.acquire("test")).to eq(false)
end
end
end
describe ".release" do
context "when the role is locked by the current worker" do
it "deletes the role and returns true" do
role = create(:worker_role, role: "test", worker: "test")
expect(WorkerRole.release("test")).to eq(true)
expect(WorkerRole.find_by(id: role.id)).to be_nil
end
end
context "when the role is locked by another worker" do
it "does not delete the role and returns false" do
role = create(:worker_role, role: "test", worker: "another")
expect(WorkerRole.release("test")).to eq(false)
expect(WorkerRole.find_by(id: role.id)).to be_present
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/domain_spec.rb | spec/models/domain_spec.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: domains
#
# id :integer not null, primary key
# dkim_error :string(255)
# dkim_identifier_string :string(255)
# dkim_private_key :text(65535)
# dkim_status :string(255)
# dns_checked_at :datetime
# incoming :boolean default(TRUE)
# mx_error :string(255)
# mx_status :string(255)
# name :string(255)
# outgoing :boolean default(TRUE)
# owner_type :string(255)
# return_path_error :string(255)
# return_path_status :string(255)
# spf_error :string(255)
# spf_status :string(255)
# use_for_any :boolean
# uuid :string(255)
# verification_method :string(255)
# verification_token :string(255)
# verified_at :datetime
# created_at :datetime
# updated_at :datetime
# owner_id :integer
# server_id :integer
#
# Indexes
#
# index_domains_on_server_id (server_id)
# index_domains_on_uuid (uuid)
#
require "rails_helper"
describe Domain do
subject(:domain) { build(:domain) }
describe "relationships" do
it { is_expected.to belong_to(:server).optional }
it { is_expected.to belong_to(:owner).optional }
it { is_expected.to have_many(:routes) }
it { is_expected.to have_many(:track_domains) }
end
describe "validations" do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name).scoped_to([:owner_type, :owner_id]).case_insensitive.with_message("is already added") }
it { is_expected.to allow_value("example.com").for(:name) }
it { is_expected.to allow_value("example.co.uk").for(:name) }
it { is_expected.to_not allow_value("EXAMPLE.COM").for(:name) }
it { is_expected.to_not allow_value("example.com ").for(:name) }
it { is_expected.to_not allow_value("example com").for(:name) }
it { is_expected.to validate_inclusion_of(:verification_method).in_array(Domain::VERIFICATION_METHODS) }
end
describe "creation" do
it "creates a new dkim identifier string" do
expect { domain.save }.to change { domain.dkim_identifier_string }.from(nil).to(match(/\A[a-zA-Z0-9]{6}\z/))
end
it "generates a new dkim key" do
expect { domain.save }.to change { domain.dkim_private_key }.from(nil).to(match(/\A-+BEGIN RSA PRIVATE KEY-+/))
end
it "generates a UUID" do
expect { domain.save }.to change { domain.uuid }.from(nil).to(/[a-f0-9-]{36}/)
end
end
describe ".verified" do
it "returns verified domains only" do
verified_domain = create(:domain)
create(:domain, :unverified)
expect(described_class.verified).to eq [verified_domain]
end
end
context "when verification method changes" do
context "to DNS" do
let(:domain) { create(:domain, :unverified, verification_method: "Email") }
it "generates a DNS suitable verification token" do
domain.verification_method = "DNS"
expect { domain.save }.to change { domain.verification_token }.from(match(/\A\d{6}\z/)).to(match(/\A[A-Za-z0-9+]{32}\z/))
end
end
context "to Email" do
let(:domain) { create(:domain, :unverified, verification_method: "DNS") }
it "generates an email suitable verification token" do
domain.verification_method = "Email"
expect { domain.save }.to change { domain.verification_token }.from(match(/\A[A-Za-z0-9+]{32}\z/)).to(match(/\A\d{6}\z/))
end
end
end
describe "#verified?" do
context "when the domain is verified" do
it "returns true" do
expect(domain.verified?).to be true
end
end
context "when the domain is not verified" do
let(:domain) { build(:domain, :unverified) }
it "returns false" do
expect(domain.verified?).to be false
end
end
end
describe "#mark_as_verified" do
context "when already verified" do
it "returns false" do
expect(domain.mark_as_verified).to be false
end
end
context "when unverified" do
let(:domain) { create(:domain, :unverified) }
it "sets the verification time" do
expect { domain.mark_as_verified }.to change { domain.verified_at }.from(nil).to(kind_of(Time))
end
end
end
describe "#parent_domains" do
context "at level 1" do
let(:domain) { build(:domain, name: "example.com") }
it "returns the current domain only" do
expect(domain.parent_domains).to eq ["example.com"]
end
end
context "at level 2" do
let(:domain) { build(:domain, name: "test.example.com") }
it "returns the current domain plus its parent" do
expect(domain.parent_domains).to eq ["test.example.com", "example.com"]
end
end
context "at level 3 (and higher)" do
let(:domain) { build(:domain, name: "sub.test.example.com") }
it "returns the current domain plus its parents" do
expect(domain.parent_domains).to eq ["sub.test.example.com", "test.example.com", "example.com"]
end
end
end
describe "#generate_dkim_key" do
it "generates a new dkim key" do
expect { domain.generate_dkim_key }.to change { domain.dkim_private_key }.from(nil).to(match(/\A-+BEGIN RSA PRIVATE KEY-+/))
end
end
describe "#dkim_key" do
context "when the domain has a DKIM key" do
let(:domain) { create(:domain) }
it "returns the dkim key as a OpenSSL::PKey::RSA" do
expect(domain.dkim_key).to be_a OpenSSL::PKey::RSA
expect(domain.dkim_key.to_s).to eq domain.dkim_private_key
end
end
context "when the domain has no DKIM key" do
let(:domain) { build(:domain) }
it "returns nil" do
expect(domain.dkim_key).to be_nil
end
end
end
describe "#to_param" do
context "when the domain has not been saved" do
it "returns nil" do
expect(domain.to_param).to be_nil
end
end
context "when the domain has been saved" do
before do
domain.save
end
it "returns the UUID" do
expect(domain.to_param).to eq domain.uuid
end
end
end
describe "#verification_email_addresses" do
let(:domain) { build(:domain, name: "example.com") }
it "returns the verification email addresses" do
expect(domain.verification_email_addresses).to eq [
"webmaster@example.com",
"postmaster@example.com",
"admin@example.com",
"administrator@example.com",
"hostmaster@example.com",
]
end
end
describe "#spf_record" do
it "returns the SPF record" do
expect(domain.spf_record).to eq "v=spf1 a mx include:#{Postal::Config.dns.spf_include} ~all"
end
end
describe "#dkim_record" do
context "when the domain has no DKIM key" do
it "returns nil" do
expect(domain.dkim_record).to be_nil
end
end
context "when the domain has a DKIM key" do
before do
domain.save
end
it "returns the DKIM record" do
expect(domain.dkim_record).to match(/\Av=DKIM1; t=s; h=sha256; p=.*;\z/)
end
end
end
describe "#dkim_identifier" do
context "when the domain has no dkim identifier string" do
it "returns nil" do
expect(domain.dkim_identifier).to be_nil
end
end
context "when the domain has a dkim identifier string" do
before do
domain.save
end
it "returns the DKIM identifier" do
expect(domain.dkim_identifier).to eq "#{Postal::Config.dns.dkim_identifier}-#{domain.dkim_identifier_string}"
end
end
end
describe "#dkim_record_name" do
context "when the domain has no dkim identifier string" do
it "returns nil" do
expect(domain.dkim_record_name).to be_nil
end
end
context "when the domain has a dkim identifier string" do
before do
domain.save
end
it "returns the DKIM identifier" do
expect(domain.dkim_record_name).to eq "#{Postal::Config.dns.dkim_identifier}-#{domain.dkim_identifier_string}._domainkey"
end
end
end
describe "#return_path_domain" do
it "returns the return path domain" do
expect(domain.return_path_domain).to eq "#{Postal::Config.dns.custom_return_path_prefix}.#{domain.name}"
end
end
describe "#dns_verification_string" do
let(:domain) { create(:domain, verification_method: "DNS") }
it "returns the DNS verification string" do
expect(domain.dns_verification_string).to eq "#{Postal::Config.dns.domain_verify_prefix} #{domain.verification_token}"
end
end
describe "#resolver" do
context "when the local nameservers should be used" do
before do
allow(Postal::Config.postal).to receive(:use_local_ns_for_domain_verification?).and_return(true)
end
it "uses the local DNS" do
expect(domain.resolver).to eq DNSResolver.local
end
end
context "when local nameservers should not be used" do
it "uses the a resolver for this domain" do
allow(DNSResolver).to receive(:for_domain).with(domain.name).and_return(DNSResolver.new(["1.2.3.4"]))
expect(domain.resolver).to be_a DNSResolver
expect(domain.resolver.nameservers).to eq ["1.2.3.4"]
end
end
end
describe "#verify_with_dns" do
context "when the verification method is not DNS" do
let(:domain) { build(:domain, verification_method: "Email") }
it "returns false" do
expect(domain.verify_with_dns).to be false
end
end
context "when a TXT record is found that matches" do
let(:domain) { create(:domain, :unverified) }
before do
allow(domain.resolver).to receive(:txt).with(domain.name).and_return([domain.dns_verification_string])
end
it "returns true" do
expect(domain.verify_with_dns).to be true
end
it "sets the verification time" do
expect { domain.verify_with_dns }.to change { domain.verified_at }.from(nil).to(kind_of(Time))
end
end
context "when no TXT record is found" do
let(:domain) { create(:domain, :unverified) }
before do
allow(domain.resolver).to receive(:txt).with(domain.name).and_return(["something", "something else"])
end
it "returns false" do
expect(domain.verify_with_dns).to be false
end
it "does not set the verification time" do
expect { domain.verify_with_dns }.to_not change { domain.verified_at } # rubocop:disable Lint/AmbiguousBlockAssociation
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/outgoing_message_prototype_spec.rb | spec/models/outgoing_message_prototype_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe OutgoingMessagePrototype do
let(:server) { create(:server) }
it "should create a new message" do
domain = create(:domain, owner: server)
prototype = OutgoingMessagePrototype.new(server, "127.0.0.1", "TestSuite", {
from: "test@#{domain.name}",
to: "test@example.com",
subject: "Test Message",
plain_body: "A plain body!"
})
expect(prototype.valid?).to be true
message = prototype.create_message("test@example.com")
expect(message).to be_a Hash
expect(message[:id]).to be_a Integer
expect(message[:token]).to be_a String
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/server_spec.rb | spec/models/server_spec.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: servers
#
# id :integer not null, primary key
# allow_sender :boolean default(FALSE)
# deleted_at :datetime
# domains_not_to_click_track :text(65535)
# log_smtp_data :boolean default(FALSE)
# message_retention_days :integer
# mode :string(255)
# name :string(255)
# outbound_spam_threshold :decimal(8, 2)
# permalink :string(255)
# postmaster_address :string(255)
# privacy_mode :boolean default(FALSE)
# raw_message_retention_days :integer
# raw_message_retention_size :integer
# send_limit :integer
# send_limit_approaching_at :datetime
# send_limit_approaching_notified_at :datetime
# send_limit_exceeded_at :datetime
# send_limit_exceeded_notified_at :datetime
# spam_failure_threshold :decimal(8, 2)
# spam_threshold :decimal(8, 2)
# suspended_at :datetime
# suspension_reason :string(255)
# token :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
# organization_id :integer
#
# Indexes
#
# index_servers_on_organization_id (organization_id)
# index_servers_on_permalink (permalink)
# index_servers_on_token (token)
# index_servers_on_uuid (uuid)
#
require "rails_helper"
describe Server do
subject(:server) { build(:server) }
describe "relationships" do
it { is_expected.to belong_to(:organization) }
it { is_expected.to belong_to(:ip_pool).optional }
it { is_expected.to have_many(:domains) }
it { is_expected.to have_many(:credentials) }
it { is_expected.to have_many(:smtp_endpoints) }
it { is_expected.to have_many(:http_endpoints) }
it { is_expected.to have_many(:address_endpoints) }
it { is_expected.to have_many(:routes) }
it { is_expected.to have_many(:queued_messages) }
it { is_expected.to have_many(:webhooks) }
it { is_expected.to have_many(:webhook_requests) }
it { is_expected.to have_many(:track_domains) }
it { is_expected.to have_many(:ip_pool_rules) }
end
describe "validations" do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:organization_id).case_insensitive }
it { is_expected.to validate_inclusion_of(:mode).in_array(Server::MODES) }
it { is_expected.to validate_uniqueness_of(:permalink).scoped_to(:organization_id).case_insensitive }
it { is_expected.to validate_exclusion_of(:permalink).in_array(Server::RESERVED_PERMALINKS) }
it { is_expected.to allow_value("hello").for(:permalink) }
it { is_expected.to allow_value("hello-world").for(:permalink) }
it { is_expected.to allow_value("hello1234").for(:permalink) }
it { is_expected.not_to allow_value("LARGE").for(:permalink) }
it { is_expected.not_to allow_value(" lots of spaces ").for(:permalink) }
it { is_expected.not_to allow_value("hello+").for(:permalink) }
it { is_expected.not_to allow_value("!!!").for(:permalink) }
it { is_expected.not_to allow_value("[hello]").for(:permalink) }
describe "ip pool validation" do
let(:org) { create(:organization) }
let(:ip_pool) { create(:ip_pool) }
let(:server) { build(:server, organization: org, ip_pool: ip_pool) }
context "when the IP pool does not belong to the same organization" do
it "adds an error" do
expect(server.save).to be false
expect(server.errors[:ip_pool_id]).to include(/must belong to the organization/)
end
end
context "whent he IP pool does belong to the the same organization" do
before do
org.ip_pools << ip_pool
end
it "does not add an error" do
expect(server.save).to be true
end
end
end
end
describe "creation" do
let(:server) { build(:server) }
it "generates a uuid" do
expect { server.save }.to change { server.uuid }.from(nil).to(/[a-f0-9-]{36}/)
end
it "generates a token" do
expect { server.save }.to change { server.token }.from(nil).to(/[a-z0-9]{6}/)
end
it "provisions a database" do
expect(server.message_db.provisioner).to receive(:provision).once
server.provision_database = true
server.save
end
end
describe "deletion" do
let(:server) { create(:server) }
it "removes the database" do
expect(server.message_db.provisioner).to receive(:drop).once
server.provision_database = true
server.destroy
end
end
describe "#status" do
context "when the server is suspended" do
let(:server) { build(:server, :suspended) }
it "returns Suspended" do
expect(server.status).to eq("Suspended")
end
end
context "when the server is not suspended" do
it "returns the mode" do
expect(server.status).to eq "Live"
end
end
end
describe "#full_permalink" do
it "returns the org and server permalinks concatenated" do
expect(server.full_permalink).to eq "#{server.organization.permalink}/#{server.permalink}"
end
end
describe "#suspended?" do
context "when the server is suspended" do
let(:server) { build(:server, :suspended) }
it "returns true" do
expect(server).to be_suspended
end
end
context "when the server is not suspended" do
it "returns false" do
expect(server).not_to be_suspended
end
end
end
describe "#actual_suspension_reason" do
context "when the server is not suspended" do
it "returns nil" do
expect(server.actual_suspension_reason).to be_nil
end
end
context "when the server is not suspended by the organization is" do
let(:org) { build(:organization, :suspended, suspension_reason: "org test") }
let(:server) { build(:server, organization: org) }
it "returns the organization suspension reason" do
expect(server.actual_suspension_reason).to eq "org test"
end
end
context "when the server is suspended" do
let(:server) { build(:server, :suspended, suspension_reason: "server test") }
it "returns the suspension reason" do
expect(server.actual_suspension_reason).to eq "server test"
end
end
end
describe "#to_param" do
it "returns the permalink" do
expect(server.to_param).to eq server.permalink
end
end
describe "#message_db" do
it "returns a message DB instance" do
expect(server.message_db).to be_a Postal::MessageDB::Database
expect(server.message_db).to have_attributes(server_id: server.id, organization_id: server.organization.id)
end
it "caches the value" do
call1 = server.message_db
call2 = server.message_db
expect(call1.object_id).to eq(call2.object_id)
end
end
describe "#message" do
it "delegates to the message db" do
expect(server.message_db).to receive(:message).with(1)
server.message(1)
end
end
describe "#message_rate" do
it "returns the live stats for the last hour per minute" do
allow(server.message_db.live_stats).to receive(:total).and_return(600)
expect(server.message_rate).to eq 10
expect(server.message_db.live_stats).to have_received(:total).with(60, types: [:incoming, :outgoing])
end
end
describe "#held_messages" do
it "returns the number of held messages" do
expect(server.message_db).to receive(:messages).with(count: true, where: { held: true }).and_return(50)
expect(server.held_messages).to eq 50
end
end
describe "#throughput_stats" do
before do
allow(server.message_db.live_stats).to receive(:total).with(60, types: [:incoming]).and_return(50)
allow(server.message_db.live_stats).to receive(:total).with(60, types: [:outgoing]).and_return(100)
end
context "when the server has a sent limit" do
let(:server) { build(:server, send_limit: 500) }
it "returns the stats with an outgoing usage percentage" do
expect(server.throughput_stats).to eq({
incoming: 50,
outgoing: 100,
outgoing_usage: 20.0
})
end
end
context "when the server does not have a sent limit" do
it "returns the stats with no outgoing usage percentage" do
expect(server.throughput_stats).to eq({
incoming: 50,
outgoing: 100,
outgoing_usage: 0
})
end
end
end
describe "#bounce_rate" do
context "when there are no outgoing emails" do
it "returns zero" do
expect(server.bounce_rate).to eq 0
end
end
context "when there are outgoing emails with some bounces" do
it "returns the rate" do
allow(server.message_db.statistics).to receive(:get).with(:daily, [:outgoing, :bounces], kind_of(Time), 30)
.and_return({
10.minutes.ago => { outgoing: 150, bounces: 50 },
5.minutes.ago => { outgoing: 350, bounces: 30 },
1.minutes.ago => { outgoing: 500, bounces: 20 }
})
expect(server.bounce_rate).to eq 10.0
end
end
end
describe "#domain_stats" do
it "returns stats about the domains associated with the server" do
create(:domain, owner: server) # verified, bad dns
create(:domain, :unverified, owner: server) # unverified
create(:domain, :dns_all_ok, owner: server) # verified good dns
expect(server.domain_stats).to eq [3, 1, 1]
end
end
describe "#webhook_hash" do
it "returns a hash to represent the server" do
expect(server.webhook_hash).to eq({
uuid: server.uuid,
name: server.name,
permalink: server.permalink,
organization: server.organization.permalink
})
end
end
describe "#send_volume" do
it "returns the number of outgoing messages sent in the last hour" do
allow(server.message_db.live_stats).to receive(:total).with(60, types: [:outgoing]).and_return(50)
expect(server.send_volume).to eq 50
end
end
describe "#send_limit_approaching?" do
context "when the server has no send limit" do
it "returns false" do
expect(server.send_limit_approaching?).to be false
end
end
context "when the server has a send limit" do
let(:server) { build(:server, send_limit: 1000) }
context "when the server's send volume is less 90% of the limit" do
it "return false" do
allow(server).to receive(:send_volume).and_return(800)
expect(server.send_limit_approaching?).to be false
end
end
context "when the server's send volume is more than 90% of the limit" do
it "returns true" do
allow(server).to receive(:send_volume).and_return(901)
expect(server.send_limit_approaching?).to be true
end
end
end
end
describe "#send_limit_warning" do
let(:server) { create(:server, send_limit: 1000) }
before do
allow(server).to receive(:send_volume).and_return(500)
end
context "when given the :approaching argument" do
it "sends an email to the org notification addresses" do
server.organization.users << create(:user)
server.send_limit_warning(:approaching)
delivery = ActionMailer::Base.deliveries.last
expect(delivery).to have_attributes(subject: /mail server is approaching its send limit/i)
end
it "sets the notification time" do
expect { server.send_limit_warning(:approaching) }.to change { server.send_limit_approaching_notified_at }
.from(nil).to(kind_of(Time))
end
it "triggers a webhook" do
expect(WebhookRequest).to receive(:trigger).with(server, "SendLimitApproaching", server: server.webhook_hash, volume: 500, limit: 1000)
server.send_limit_warning(:approaching)
end
end
context "when given the :exceeded argument" do
it "sends an email to the org notification addresses" do
server.organization.users << create(:user)
server.send_limit_warning(:exceeded)
delivery = ActionMailer::Base.deliveries.last
expect(delivery).to have_attributes(subject: /mail server has exceeded its send limit/i)
end
it "sets the notification time" do
expect { server.send_limit_warning(:exceeded) }.to change { server.send_limit_exceeded_notified_at }
.from(nil).to(kind_of(Time))
end
it "triggers a webhook" do
expect(WebhookRequest).to receive(:trigger).with(server, "SendLimitExceeded", server: server.webhook_hash, volume: 500, limit: 1000)
server.send_limit_warning(:exceeded)
end
end
end
describe "#queue_size" do
it "returns the number of queued messages that are ready" do
create(:queued_message, server: server, retry_after: nil)
create(:queued_message, server: server, retry_after: 1.minute.ago)
expect(server.queue_size).to eq 2
end
end
describe "#authenticated_domain_for_address" do
context "when the address given is blank" do
it "returns nil" do
expect(server.authenticated_domain_for_address("")).to be nil
expect(server.authenticated_domain_for_address(nil)).to be nil
end
end
context "when the address given does not have a username & domain component" do
it "returns nil" do
expect(server.authenticated_domain_for_address("blah")).to be nil
end
end
context "when there is a verified org-level domain matching the address provided" do
it "returns that domain" do
server = create(:server)
domain = create(:domain, owner: server.organization, name: "mangos.io")
expect(server.authenticated_domain_for_address("hello@mangos.io")).to eq domain
end
end
context "when there is a verified server-level domain matching the address provided" do
it "returns that domain" do
domain = create(:domain, owner: server, name: "oranges.io")
expect(server.authenticated_domain_for_address("hello@oranges.io")).to eq domain
end
end
context "when there is a verified server-level domain matching the address and a use_for_any" do
it "returns the matching domain" do
domain = create(:domain, owner: server, name: "oranges.io")
create(:domain, owner: server, name: "pears.com", use_for_any: true)
expect(server.authenticated_domain_for_address("hello@oranges.io")).to eq domain
end
end
context "when there is a verified server-level and org-level domain with the same name" do
it "returns the server-level domain" do
domain = create(:domain, owner: server, name: "lemons.com")
create(:domain, owner: server.organization, name: "lemons.com")
expect(server.authenticated_domain_for_address("hello@lemons.com")).to eq domain
end
end
context "when there is a verified server-level domain with the 'use_for_any' boolean set with a different name" do
it "returns that domain" do
create(:domain, owner: server, name: "pears.com")
domain = create(:domain, owner: server, name: "apples.io", use_for_any: true)
expect(server.authenticated_domain_for_address("hello@bananas.com")).to eq domain
end
end
context "when there is no suitable domain" do
it "returns nil" do
server = create(:server)
create(:domain, owner: server, name: "pears.com")
create(:domain, owner: server.organization, name: "pineapples.com")
expect(server.authenticated_domain_for_address("hello@bananas.com")).to be nil
end
end
end
describe "#find_authenticated_domain_from_headers" do
context "when none of the from addresses have a valid domain" do
it "returns nil" do
expect(server.find_authenticated_domain_from_headers("from" => "test@lemons.com")).to be nil
end
end
context "when the from addresses has a valid domain" do
it "returns the domain" do
domain = create(:domain, owner: server)
expect(server.find_authenticated_domain_from_headers("from" => "hello@#{domain.name}")).to eq domain
end
end
context "when there are multiple from addresses" do
context "when none of them match a domain" do
it "returns nil" do
expect(server.find_authenticated_domain_from_headers("from" => ["hello@lemons.com", "hello@apples.com"])).to be nil
end
end
context "when some but not all match" do
it "returns nil" do
domain = create(:domain, owner: server)
expect(server.find_authenticated_domain_from_headers("from" => ["hello@#{domain.name}", "hello@lemons.com"])).to be nil
end
end
context "when all match" do
it "returns the first domain that matched" do
domain1 = create(:domain, owner: server)
domain2 = create(:domain, owner: server)
expect(server.find_authenticated_domain_from_headers("from" => ["hello@#{domain1.name}", "hello@#{domain2.name}"])).to eq domain1
end
end
end
context "when the server is not allowed to use the sender header" do
context "when the sender header has a valid address" do
it "does not return the domain" do
domain = create(:domain, owner: server)
result = server.find_authenticated_domain_from_headers(
"from" => "hello@lemons.com",
"sender" => "hello@#{domain.name}"
)
expect(result).to be nil
end
end
end
context "when the server is allowed to use the sender header" do
let(:server) { build(:server, allow_sender: true) }
context "when none of the from addresses match but sender domains do" do
it "returns the domain that does match" do
domain = create(:domain, owner: server)
result = server.find_authenticated_domain_from_headers(
"from" => "hello@lemons.com",
"sender" => "hello@#{domain.name}"
)
expect(result).to eq domain
end
end
end
end
describe "#suspend" do
let(:server) { create(:server) }
it "sets the suspension time" do
expect { server.suspend("some reason") }.to change { server.reload.suspended_at }.from(nil).to(kind_of(Time))
end
it "sets the suspension reason" do
expect { server.suspend("some reason") }.to change { server.reload.suspension_reason }.from(nil).to("some reason")
end
context "when there are no notification addresses" do
it "does not send an email" do
server.suspend("some reason")
expect(ActionMailer::Base.deliveries).to be_empty
end
end
context "when there are notification addresses" do
before do
server.organization.users << create(:user)
end
it "sends an email" do
server.suspend("some reason")
delivery = ActionMailer::Base.deliveries.last
expect(delivery).to have_attributes(subject: /server has been suspended/i)
end
end
end
describe "#unsuspend" do
let(:server) { create(:server, :suspended) }
it "removes the suspension time" do
expect { server.unsuspend }.to change { server.reload.suspended_at }.to(nil)
end
it "removes the suspension reason" do
expect { server.unsuspend }.to change { server.reload.suspension_reason }.to(nil)
end
end
describe "#ip_pool_for_message" do
context "when the message is not outgoing" do
let(:message) { MessageFactory.incoming(server) }
it "returns nil" do
expect(server.ip_pool_for_message(message)).to be nil
end
end
context "when a server rule matches the message" do
let(:domain) { create(:domain, owner: server) }
let(:ip_pool) { create(:ip_pool, organizations: [server.organization]) }
let(:message) do
MessageFactory.outgoing(server, domain: domain) do |msg|
msg.rcpt_to = "hello@google.com"
end
end
before do
create(:ip_pool_rule, ip_pool: ip_pool, owner: server, from_text: nil, to_text: "google.com")
end
it "returns the pool" do
expect(server.ip_pool_for_message(message)).to eq ip_pool
end
end
context "when an org rule matches the message" do
let(:domain) { create(:domain, owner: server) }
let(:ip_pool) { create(:ip_pool, organizations: [server.organization]) }
let(:message) do
MessageFactory.outgoing(server, domain: domain) do |msg|
msg.rcpt_to = "hello@google.com"
end
end
before do
create(:ip_pool_rule, ip_pool: ip_pool, owner: server.organization, from_text: nil, to_text: "google.com")
end
it "returns the pool" do
expect(server.ip_pool_for_message(message)).to eq ip_pool
end
end
context "when the server has no default pool and no rules match the message" do
let(:domain) { create(:domain, owner: server) }
let(:message) { MessageFactory.outgoing(server, domain: domain) }
it "returns nil" do
expect(server.ip_pool_for_message(message)).to be nil
end
end
context "when the server has a default pool and no rules match the message" do
let(:organization) { create(:organization) }
let(:ip_pool) { create(:ip_pool, organizations: [organization]) }
let(:server) { create(:server, organization: organization, ip_pool: ip_pool) }
let(:domain) { create(:domain, owner: server) }
let(:message) { MessageFactory.outgoing(server, domain: domain) }
it "returns the server's default pool" do
expect(server.ip_pool_for_message(message)).to eq ip_pool
end
end
end
describe ".[]" do
context "when provided with an integer" do
it "returns the server with that ID" do
server = create(:server)
expect(described_class[server.id]).to eq server
end
it "returns nil if no server exists with the ID" do
expect(described_class[1234]).to be nil
end
end
context "when provided with a string" do
it "returns the server that matches the given permalinks" do
server = create(:server)
expect(described_class["#{server.organization.permalink}/#{server.permalink}"]).to eq server
end
it "returns nil if no server exists" do
expect(described_class["hello/world"]).to be nil
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/queued_message_spec.rb | spec/models/queued_message_spec.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: queued_messages
#
# id :integer not null, primary key
# attempts :integer default(0)
# batch_key :string(255)
# domain :string(255)
# locked_at :datetime
# locked_by :string(255)
# manual :boolean default(FALSE)
# retry_after :datetime
# created_at :datetime
# updated_at :datetime
# ip_address_id :integer
# message_id :integer
# route_id :integer
# server_id :integer
#
# Indexes
#
# index_queued_messages_on_domain (domain)
# index_queued_messages_on_message_id (message_id)
# index_queued_messages_on_server_id (server_id)
#
require "rails_helper"
RSpec.describe QueuedMessage do
subject(:queued_message) { build(:queued_message) }
describe "relationships" do
it { is_expected.to belong_to(:server) }
it { is_expected.to belong_to(:ip_address).optional }
end
describe ".ready_with_delayed_retry" do
it "returns messages where retry after is null" do
message = create(:queued_message, retry_after: nil)
expect(described_class.ready_with_delayed_retry).to eq [message]
end
it "returns messages where retry after is less than 30 seconds from now" do
Timecop.freeze do
message1 = create(:queued_message, retry_after: 45.seconds.ago)
message2 = create(:queued_message, retry_after: 5.minutes.ago)
create(:queued_message, retry_after: Time.now)
create(:queued_message, retry_after: 1.minute.from_now)
expect(described_class.ready_with_delayed_retry.order(:id)).to eq [message1, message2]
end
end
end
describe ".with_stale_lock" do
it "returns messages where lock time is less than the configured number of stale days" do
allow(Postal::Config.postal).to receive(:queued_message_lock_stale_days).and_return(2)
message1 = create(:queued_message, locked_at: 3.days.ago, locked_by: "test")
message2 = create(:queued_message, locked_at: 2.days.ago, locked_by: "test")
create(:queued_message, locked_at: 1.days.ago, locked_by: "test")
create(:queued_message)
expect(described_class.with_stale_lock.order(:id)).to eq [message1, message2]
end
end
describe "#retry_now" do
it "removes the retry time" do
message = create(:queued_message, retry_after: 2.minutes.from_now)
expect { message.retry_now }.to change { message.reload.retry_after }.from(kind_of(Time)).to(nil)
end
it "raises an error if invalid" do
message = create(:queued_message, retry_after: 2.minutes.from_now)
message.update_columns(server_id: nil) # unlikely to actually happen
expect { message.retry_now }.to raise_error(ActiveRecord::RecordInvalid)
end
end
describe "#send_bounce" do
let(:server) { create(:server) }
let(:message) { MessageFactory.incoming(server) }
subject(:queued_message) { create(:queued_message, message: message) }
context "when the message is eligiable for bounces" do
it "queues a bounce message for sending" do
expect(BounceMessage).to receive(:new).with(server, kind_of(Postal::MessageDB::Message)).and_wrap_original do |original, *args|
bounce = original.call(*args)
expect(bounce).to receive(:queue)
bounce
end
queued_message.send_bounce
end
end
context "when the message is not eligible for bounces" do
it "returns nil" do
message.update(bounce: true)
expect(queued_message.send_bounce).to be nil
end
it "does not queue a bounce message for sending" do
message.update(bounce: true)
expect(BounceMessage).not_to receive(:new)
queued_message.send_bounce
end
end
end
describe "#allocate_ip_address" do
subject(:queued_message) { create(:queued_message) }
context "when ip pools is disabled" do
it "returns nil" do
expect(queued_message.allocate_ip_address).to be nil
end
it "does not allocate an IP address" do
expect { queued_message.allocate_ip_address }.not_to change(queued_message, :ip_address)
end
end
context "when IP pools is enabled" do
before do
allow(Postal::Config.postal).to receive(:use_ip_pools?).and_return(true)
end
context "when there is no backend message" do
it "returns nil" do
expect(queued_message.allocate_ip_address).to be nil
end
it "does not allocate an IP address" do
expect { queued_message.allocate_ip_address }.not_to change(queued_message, :ip_address)
end
end
context "when no IP pool can be determined for the message" do
let(:server) { create(:server) }
let(:message) { MessageFactory.outgoing(server) }
subject(:queued_message) { create(:queued_message, message: message) }
it "returns nil" do
expect(queued_message.allocate_ip_address).to be nil
end
it "does not allocate an IP address" do
expect { queued_message.allocate_ip_address }.not_to change(queued_message, :ip_address)
end
end
context "when an IP pool can be determined for the message" do
let(:ip_pool) { create(:ip_pool, :with_ip_address) }
let(:server) { create(:server, ip_pool: ip_pool) }
let(:message) { MessageFactory.outgoing(server) }
subject(:queued_message) { create(:queued_message, message: message) }
it "returns an IP address" do
expect(queued_message.allocate_ip_address).to be_a IPAddress
end
it "allocates an IP address to the queued message" do
queued_message.update(ip_address: nil)
expect { queued_message.allocate_ip_address }.to change(queued_message, :ip_address).from(nil).to(ip_pool.ip_addresses.first)
end
end
end
end
describe "#batchable_messages" do
context "when the message is not locked" do
subject(:queued_message) { build(:queued_message) }
it "raises an error" do
expect { queued_message.batchable_messages }.to raise_error(Postal::Error, /must lock current message before locking any friends/i)
end
end
context "when the message is locked" do
let(:batch_key) { nil }
subject(:queued_message) { build(:queued_message, :locked, batch_key: batch_key) }
context "when there is no batch key on the queued message" do
it "returns an empty array" do
expect(queued_message.batch_key).to be nil
expect(queued_message.batchable_messages).to eq []
end
end
context "when there is a batch key" do
let(:batch_key) { "1234" }
it "finds and locks messages with the same batch key and IP address up to the limit specified" do
other_message1 = create(:queued_message, batch_key: batch_key, ip_address: nil)
other_message2 = create(:queued_message, batch_key: batch_key, ip_address: nil)
create(:queued_message, batch_key: batch_key, ip_address: nil)
messages = queued_message.batchable_messages(2)
expect(messages).to eq [other_message1, other_message2]
expect(messages).to all be_locked
end
it "does not find messages with a different batch key" do
create(:queued_message, batch_key: "5678", ip_address: nil)
expect(queued_message.batchable_messages).to eq []
end
it "does not find messages that are not queued for sending yet" do
create(:queued_message, batch_key: batch_key, ip_address: nil, retry_after: 1.minute.from_now)
expect(queued_message.batchable_messages).to eq []
end
it "does not find messages that are for a different IP address" do
create(:queued_message, batch_key: batch_key, ip_address: create(:ip_address))
expect(queued_message.batchable_messages).to eq []
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/organization_spec.rb | spec/models/organization_spec.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: organizations
#
# id :integer not null, primary key
# deleted_at :datetime
# name :string(255)
# permalink :string(255)
# suspended_at :datetime
# suspension_reason :string(255)
# time_zone :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
# owner_id :integer
#
# Indexes
#
# index_organizations_on_permalink (permalink)
# index_organizations_on_uuid (uuid)
#
require "rails_helper"
describe Organization do
context "model" do
subject(:organization) { create(:organization) }
it "should have a UUID" do
expect(organization.uuid).to be_a String
expect(organization.uuid.length).to eq 36
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/user_spec.rb | spec/models/user_spec.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# admin :boolean default(FALSE)
# email_address :string(255)
# email_verification_token :string(255)
# email_verified_at :datetime
# first_name :string(255)
# last_name :string(255)
# oidc_issuer :string(255)
# oidc_uid :string(255)
# password_digest :string(255)
# password_reset_token :string(255)
# password_reset_token_valid_until :datetime
# time_zone :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_users_on_email_address (email_address)
# index_users_on_uuid (uuid)
#
require "rails_helper"
describe User do
subject(:user) { build(:user) }
describe "validations" do
it { is_expected.to validate_presence_of(:first_name) }
it { is_expected.to validate_presence_of(:last_name) }
it { is_expected.to validate_presence_of(:email_address) }
it { is_expected.to validate_presence_of(:password) }
it { is_expected.to validate_uniqueness_of(:email_address).case_insensitive }
it { is_expected.to allow_value("test@example.com").for(:email_address) }
it { is_expected.to allow_value("test@example.co.uk").for(:email_address) }
it { is_expected.to allow_value("test+tagged@example.co.uk").for(:email_address) }
it { is_expected.to allow_value("test+tagged@EXAMPLE.COM").for(:email_address) }
it { is_expected.to_not allow_value("test+tagged").for(:email_address) }
it { is_expected.to_not allow_value("test.com").for(:email_address) }
it "does not require a password when OIDC is enabled" do
allow(Postal::Config.oidc).to receive(:enabled?).and_return(true)
user.password = nil
expect(user.save).to be true
end
end
describe "relationships" do
it { is_expected.to have_many(:organization_users) }
it { is_expected.to have_many(:organizations) }
end
describe "creation" do
before { user.save }
it "should have a UUID" do
expect(user.uuid).to be_a String
expect(user.uuid.length).to eq 36
end
it "has a default timezone" do
expect(user.time_zone).to eq "UTC"
end
end
describe "#organizations_scope" do
context "when the user is an admin" do
it "returns a scope of all organizations" do
user.admin = true
scope = user.organizations_scope
expect(scope).to eq Organization.present
end
end
context "when the user not an admin" do
it "returns a scope including only orgs the user is associated with" do
user.admin = false
user.organizations << create(:organization)
scope = user.organizations_scope
expect(scope).to eq user.organizations.present
end
end
end
describe "#name" do
it "returns the name" do
user.first_name = "John"
user.last_name = "Doe"
expect(user.name).to eq "John Doe"
end
end
describe "#password?" do
it "returns true if the user has a password" do
user.password = "password"
expect(user.password?).to be true
end
it "returns false if the user does not have a password" do
user.password = nil
expect(user.password?).to be false
end
end
describe "#to_param" do
it "returns the UUID" do
user.uuid = "123"
expect(user.to_param).to eq "123"
end
end
describe "#email_tag" do
it "returns the name and email address" do
user.first_name = "John"
user.last_name = "Doe"
user.email_address = "john@example.com"
expect(user.email_tag).to eq "John Doe <john@example.com>"
end
end
describe ".[]" do
it "should find a user by email address" do
user = create(:user)
expect(User[user.email_address]).to eq user
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/user/oidc_spec.rb | spec/models/user/oidc_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe User do
let(:user) { build(:user) }
describe "#oidc?" do
it "returns true if the user has an OIDC UID" do
user.oidc_uid = "123"
expect(user.oidc?).to be true
end
it "returns false if the user does not have an OIDC UID" do
user.oidc_uid = nil
expect(user.oidc?).to be false
end
end
describe ".find_from_oidc" do
let(:issuer) { "https://identity.example.com" }
before do
allow(Postal::Config.oidc).to receive(:enabled?).and_return(true)
allow(Postal::Config.oidc).to receive(:issuer).and_return(issuer)
allow(Postal::Config.oidc).to receive(:email_address_field).and_return("email")
end
let(:uid) { "abcdef" }
let(:oidc_name) { "John Smith" }
let(:oidc_email) { "test@example.com" }
let(:auth) { { "sub" => uid, "email" => oidc_email, "name" => oidc_name } }
let(:logger) { TestLogger.new }
subject(:result) { described_class.find_from_oidc(auth, logger: logger) }
context "when there is a user that matchers the UID and issuer" do
before do
@existing_user = create(:user, oidc_uid: uid, oidc_issuer: issuer, first_name: "mary",
last_name: "apples", email_address: "mary@apples.com")
end
it "returns that user" do
expect(result).to eq @existing_user
end
it "updates the name and email address" do
result
@existing_user.reload
expect(@existing_user.first_name).to eq "John"
expect(@existing_user.last_name).to eq "Smith"
expect(@existing_user.email_address).to eq "test@example.com"
end
it "logs" do
result
expect(logger).to have_logged(/found user with UID abcdef/i)
end
end
context "when there is no user which matches the UID and issuer" do
context "when there is a user which matches the email address without an OIDC UID" do
before do
@existing_user = create(:user, first_name: "mary",
last_name: "apples", email_address: "test@example.com")
end
it "returns that user" do
expect(result).to eq @existing_user
end
it "adds the UID and issuer to the user" do
result
@existing_user.reload
expect(@existing_user.oidc_uid).to eq uid
expect(@existing_user.oidc_issuer).to eq issuer
end
it "updates the name if changed" do
result
@existing_user.reload
expect(@existing_user.first_name).to eq "John"
expect(@existing_user.last_name).to eq "Smith"
end
it "removes the password" do
@existing_user.password = "password"
@existing_user.save!
result
@existing_user.reload
expect(@existing_user.password_digest).to be_nil
end
it "logs" do
result
expect(logger).to have_logged(/no user with UID abcdef/)
expect(logger).to have_logged(/found user with e-mail address test@example.com/)
end
end
context "when there is no user which matches the email address" do
it "returns nil" do
expect(result).to be_nil
end
it "logs" do
result
expect(logger).to have_logged(/no user with UID abcdef/)
expect(logger).to have_logged(/no user with e-mail address/)
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/models/user/authentication_spec.rb | spec/models/user/authentication_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe User do
describe ".authenticate" do
it "does not authenticate users with invalid emails" do
expect { User.authenticate("nothing@nothing.com", "hello") }.to raise_error(Postal::Errors::AuthenticationError) do |e|
expect(e.error).to eq "InvalidEmailAddress"
end
end
it "does not authenticate users with invalid passwords" do
user = create(:user)
expect { User.authenticate(user.email_address, "hello") }.to raise_error(Postal::Errors::AuthenticationError) do |e|
expect(e.error).to eq "InvalidPassword"
end
end
it "authenticates valid users" do
user = create(:user)
auth_user = nil
expect { auth_user = User.authenticate(user.email_address, "passw0rd") }.to_not raise_error
expect(auth_user).to eq user
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/dns_resolver_spec.rb | spec/lib/dns_resolver_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe DNSResolver do
subject(:resolver) { described_class.local }
# Now, we could mock everything in here which would give us some comfort
# but I do think that we'll benefit more from having a full E2E test here
# so we'll test this using values which we know to be fairly static and
# that are within our control.
describe "#a" do
it "returns a list of IP addresses" do
expect(resolver.a("www.dnstest.postalserver.io").sort).to eq ["1.2.3.4", "2.3.4.5"]
end
it "resolves a domain name containing an emoji" do
expect(resolver.a("☺.dnstest.postalserver.io").sort).to eq ["3.4.5.6"]
end
it "returns an empty array when timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.a("www.dnstest.postalserver.io")).to eq []
end
context "when raise_timeout_errors is true" do
it "returns a list of IP addresses" do
expect(resolver.a("www.dnstest.postalserver.io", raise_timeout_errors: true).sort).to eq ["1.2.3.4", "2.3.4.5"]
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.a("www.dnstest.postalserver.io", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe "#aaaa" do
it "returns a list of IP addresses" do
expect(resolver.aaaa("www.dnstest.postalserver.io").sort).to eq ["2a00:67a0:a::1", "2a00:67a0:a::2"]
end
it "returns an empty array when timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.aaaa("www.dnstest.postalserver.io")).to eq []
end
context "when raise_timeout_errors is true" do
it "returns a list of IP addresses" do
expect(resolver.aaaa("www.dnstest.postalserver.io", raise_timeout_errors: true).sort).to eq ["2a00:67a0:a::1", "2a00:67a0:a::2"]
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.aaaa("www.dnstest.postalserver.io", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe "#txt" do
it "returns a list of TXT records" do
expect(resolver.txt("dnstest.postalserver.io").sort).to eq [
"an example txt record",
"another example",
]
end
it "returns an empty array when timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.txt("dnstest.postalserver.io")).to eq []
end
context "when raise_timeout_errors is true" do
it "returns a list of TXT records" do
expect(resolver.txt("dnstest.postalserver.io", raise_timeout_errors: true).sort).to eq [
"an example txt record",
"another example",
]
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.txt("dnstest.postalserver.io", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe "#cname" do
it "returns a list of CNAME records" do
expect(resolver.cname("cname.dnstest.postalserver.io")).to eq ["www.dnstest.postalserver.io"]
end
it "returns an empty array when timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.cname("cname.dnstest.postalserver.io")).to eq []
end
context "when raise_timeout_errors is true" do
it "returns a list of CNAME records" do
expect(resolver.cname("cname.dnstest.postalserver.io", raise_timeout_errors: true)).to eq ["www.dnstest.postalserver.io"]
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.cname("cname.dnstest.postalserver.io", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe "#mx" do
it "returns a list of MX records" do
expect(resolver.mx("dnstest.postalserver.io")).to eq [
[10, "mx1.dnstest.postalserver.io"],
[20, "mx2.dnstest.postalserver.io"],
]
end
it "returns an empty array when timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.mx("dnstest.postalserver.io")).to eq []
end
context "when raise_timeout_errors is true" do
it "returns a list of MX records" do
expect(resolver.mx("dnstest.postalserver.io", raise_timeout_errors: true)).to eq [
[10, "mx1.dnstest.postalserver.io"],
[20, "mx2.dnstest.postalserver.io"],
]
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.mx("dnstest.postalserver.io", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe "#effective_ns" do
it "returns the nameserver names that are authoritative for the given domain" do
expect(resolver.effective_ns("postalserver.io").sort).to eq [
"prestigious-honeybadger.katapultdns.com",
"the-cake-is-a-lie.katapultdns.com",
]
end
it "returns an empty array when timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.effective_ns("postalserver.io")).to eq []
end
context "when raise_timeout_errors is true" do
it "returns a list of NS records" do
expect(resolver.effective_ns("postalserver.io", raise_timeout_errors: true).sort).to eq [
"prestigious-honeybadger.katapultdns.com",
"the-cake-is-a-lie.katapultdns.com",
]
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.effective_ns("postalserver.io", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe "#ip_to_hostname" do
it "returns the hostname for the given IP" do
expect(resolver.ip_to_hostname("151.252.1.100")).to eq "ns1.katapultdns.com"
end
it "returns the IP when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect(resolver.ip_to_hostname("151.252.1.100")).to eq "151.252.1.100"
end
context "when raise_timeout_errors is true" do
it "returns the hostname for the given IP" do
expect(resolver.ip_to_hostname("151.252.1.100", raise_timeout_errors: true)).to eq "ns1.katapultdns.com"
end
it "raises an error when the timeout is exceeded" do
allow(Postal::Config.dns).to receive(:timeout).and_return(0.00001)
expect do
resolver.ip_to_hostname("151.252.1.100", raise_timeout_errors: true)
end.to raise_error(Resolv::ResolvError, /timeout/)
end
end
end
describe ".for_domain" do
it "finds the effective nameservers for a given domain and returns them" do
resolver = described_class.for_domain("dnstest.postalserver.io")
expect(resolver.nameservers.sort).to eq ["151.252.1.100", "151.252.2.100"]
end
end
describe ".local" do
after do
# Remove all cached values for the local resolver
DNSResolver.instance_variable_set(:@local, nil)
end
it "returns a resolver with the local machine's resolvers" do
resolver = described_class.local
expect(resolver.nameservers).to be_a Array
expect(resolver.nameservers).to_not be_empty
end
context "when there is no resolv.conf" do
it "raises an error" do
allow(File).to receive(:file?).with("/etc/resolv.conf").and_return(false)
expect { described_class.local }.to raise_error(DNSResolver::LocalResolversUnavailableError,
/no resolver config found at/i)
end
end
context "when no nameservers are found in resolv.conf" do
it "raises an error" do
allow(Resolv::DNS::Config).to receive(:parse_resolv_conf).with("/etc/resolv.conf").and_return({})
expect { described_class.local }.to raise_error(DNSResolver::LocalResolversUnavailableError,
/could not find nameservers in/i)
end
end
context "when an empty array of nameserver is found in resolv.conf" do
it "raises an error" do
allow(Resolv::DNS::Config).to receive(:parse_resolv_conf).with("/etc/resolv.conf")
.and_return({ nameserver: [] })
expect { described_class.local }.to raise_error(DNSResolver::LocalResolversUnavailableError,
/could not find nameservers in/i)
end
end
end
context "when using a resolver for a domain" do
subject(:resolver) { described_class.for_domain("dnstest.postalserver.io") }
it "will not return domains that are not hosted on that server" do
expect(resolver.a("example.com")).to eq []
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/received_header_spec.rb | spec/lib/received_header_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe ReceivedHeader do
before do
allow(DNSResolver.local).to receive(:ip_to_hostname).and_return("hostname.com")
end
describe ".generate" do
context "when server is nil" do
it "returns the correct string" do
result = described_class.generate(nil, "testhelo", "1.1.1.1", :smtp)
expect(result).to eq "from testhelo (hostname.com [1.1.1.1]) " \
"by #{Postal::Config.postal.smtp_hostname} " \
"with SMTP; #{Time.now.utc.rfc2822}"
end
end
context "when server is provided with privacy_mode=true" do
it "returns the correct string" do
server = Server.new(privacy_mode: true)
result = described_class.generate(server, "testhelo", "1.1.1.1", :smtp)
expect(result).to eq "by #{Postal::Config.postal.smtp_hostname} " \
"with SMTP; #{Time.now.utc.rfc2822}"
end
end
context "when server is provided with privacy_mode=false" do
it "returns the correct string" do
server = Server.new(privacy_mode: false)
result = described_class.generate(server, "testhelo", "1.1.1.1", :smtp)
expect(result).to eq "from testhelo (hostname.com [1.1.1.1]) " \
"by #{Postal::Config.postal.smtp_hostname} " \
"with SMTP; #{Time.now.utc.rfc2822}"
end
end
context "when type is http" do
it "returns the correct string" do
result = described_class.generate(nil, "web-ui", "1.1.1.1", :http)
expect(result).to eq "from web-ui (hostname.com [1.1.1.1]) " \
"by #{Postal::Config.postal.web_hostname} " \
"with HTTP; #{Time.now.utc.rfc2822}"
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/query_string_spec.rb | spec/lib/query_string_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe QueryString do
it "works with a single item" do
qs = described_class.new("to: test@example.com")
expect(qs.hash["to"]).to eq "test@example.com"
end
it "works with a multiple items" do
qs = described_class.new("to: test@example.com from: another@example.com")
expect(qs.hash["to"]).to eq "test@example.com"
expect(qs.hash["from"]).to eq "another@example.com"
end
it "does not require a space after the field name" do
qs = described_class.new("to:test@example.com from:another@example.com")
expect(qs.hash["to"]).to eq "test@example.com"
expect(qs.hash["from"]).to eq "another@example.com"
end
it "returns nil when it receives blank" do
qs = described_class.new("to:[blank]")
expect(qs.hash["to"]).to eq nil
end
it "handles dates with spaces" do
qs = described_class.new("date: 2017-02-12 15:20")
expect(qs.hash["date"]).to eq("2017-02-12 15:20")
end
it "returns an array for multiple items" do
qs = described_class.new("to: test@example.com to: another@example.com")
expect(qs.hash["to"]).to be_a(Array)
expect(qs.hash["to"][0]).to eq "test@example.com"
expect(qs.hash["to"][1]).to eq "another@example.com"
end
it "works with a z in the string" do
qs = described_class.new("to: testaz@example.com")
expect(qs.hash["to"]).to eq "testaz@example.com"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer_spec.rb | spec/lib/message_dequeuer_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe MessageDequeuer do
describe ".process" do
it "calls the initial process with the given message and logger" do
message = create(:queued_message)
logger = TestLogger.new
mock = double("InitialProcessor")
expect(mock).to receive(:process).with(no_args)
expect(MessageDequeuer::InitialProcessor).to receive(:new).with(message, logger: logger).and_return(mock)
described_class.process(message, logger: logger)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/postal_spec.rb | spec/lib/postal_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe Postal do
describe "#signer" do
it "returns a signer with the installation's signing key" do
expect(Postal.signer).to be_a(Postal::Signer)
expect(Postal.signer.private_key.to_pem).to eq OpenSSL::PKey::RSA.new(File.read(Postal::Config.postal.signing_key_path)).to_pem
end
end
describe "#change_database_connection_pool_size" do
it "changes the connection pool size" do
expect { Postal.change_database_connection_pool_size(8) }.to change { ActiveRecord::Base.connection_pool.size }.from(5).to(8)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/dkim_header_spec.rb | spec/lib/dkim_header_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe DKIMHeader do
examples = Rails.root.join("spec/examples/dkim_signing/*.msg")
Dir[examples].each do |path|
contents = File.read(path)
frontmatter, email = contents.split(/^---\n/m, 2)
frontmatter = YAML.safe_load(frontmatter)
email.strip
it "works with #{path.split('/').last}" do
mocked_time = Time.at(frontmatter["time"].to_i)
allow(Time).to receive(:now).and_return(mocked_time)
domain = instance_double("Domain")
allow(domain).to receive(:dkim_status).and_return("OK")
allow(domain).to receive(:name).and_return(frontmatter["domain"])
allow(domain).to receive(:dkim_key).and_return(OpenSSL::PKey::RSA.new(frontmatter["private_key"]))
allow(domain).to receive(:dkim_identifier).and_return(frontmatter["dkim_identifier"])
expectation = "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;\r\n" \
"\td=#{frontmatter['domain']};\r\n" \
"\ts=#{frontmatter['dkim_identifier']}; t=#{mocked_time.to_i};\r\n" \
"\tbh=#{frontmatter['bh']};\r\n" \
"\th=#{frontmatter['headers']};\r\n" \
"\tb=#{frontmatter['b'].scan(/.{1,72}/).join("\r\n\t")}"
header = described_class.new(domain, email)
expect(header.dkim_header).to eq expectation
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/worker/jobs/process_webhook_requests_job_spec.rb | spec/lib/worker/jobs/process_webhook_requests_job_spec.rb | # frozen_string_literal: true
require "rails_helper"
module Worker
module Jobs
RSpec.describe ProcessWebhookRequestsJob do
subject(:job) { described_class.new(logger: Postal.logger) }
let(:mocked_service) { double("Service") }
before do
allow(WebhookDeliveryService).to receive(:new).and_return(mocked_service)
allow(mocked_service).to receive(:call).with(no_args)
end
context "when there are no requests to process" do
it "does nothing" do
job.call
expect(job.work_completed?).to be false
end
end
context "when there is a unlocked request with no retry time" do
it "delivers the request" do
request = create(:webhook_request)
job.call
expect(WebhookDeliveryService).to have_received(:new).with(webhook_request: request)
expect(job.work_completed?).to be true
end
end
context "when there is an unlocked request with a retry time in the past" do
it "delivers the request" do
request = create(:webhook_request, retry_after: 1.minute.ago)
job.call
expect(WebhookDeliveryService).to have_received(:new).with(webhook_request: request)
expect(job.work_completed?).to be true
end
end
context "when there is an unlocked request with a retry time in the future" do
it "does nothing" do
create(:webhook_request, retry_after: 1.minute.from_now)
job.call
expect(job.work_completed?).to be false
end
end
context "when there is a locked requested without a retry time" do
it "does nothing" do
create(:webhook_request, :locked)
job.call
expect(job.work_completed?).to be false
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/worker/jobs/process_queued_messages_job_spec.rb | spec/lib/worker/jobs/process_queued_messages_job_spec.rb | # frozen_string_literal: true
require "rails_helper"
module Worker
module Jobs
RSpec.describe ProcessQueuedMessagesJob do
subject(:job) { described_class.new(logger: Postal.logger) }
before do
allow(MessageDequeuer).to receive(:process)
end
describe "#call" do
context "when there are no queued messages" do
it "does nothing" do
job.call
expect(MessageDequeuer).to_not have_received(:process)
end
end
context "when there is an unlocked queued message for an IP address that is not ours" do
it "does nothing" do
ip_address = create(:ip_address)
queued_message = create(:queued_message, ip_address: ip_address)
job.call
expect(MessageDequeuer).to_not have_received(:process)
expect(queued_message.reload.locked?).to be false
end
end
context "when there is an unlocked queued message without an IP address without a retry time" do
it "locks the message and calls the service" do
queued_message = create(:queued_message, ip_address: nil, retry_after: nil)
job.call
expect(MessageDequeuer).to have_received(:process).with(queued_message, logger: kind_of(Klogger::Logger))
expect(queued_message.reload.locked?).to be true
expect(queued_message.locked_by).to match(/\A#{Postal.locker_name} [a-f0-9]{16}\z/)
expect(queued_message.locked_at).to be_within(1.second).of(Time.current)
end
end
context "when there is an unlocked queued message without an IP address without a retry time in the past" do
it "locks the message and calls the service" do
queued_message = create(:queued_message, ip_address: nil, retry_after: 10.minutes.ago)
job.call
expect(MessageDequeuer).to have_received(:process).with(queued_message, logger: kind_of(Klogger::Logger))
expect(queued_message.reload.locked?).to be true
expect(queued_message.locked_by).to match(/\A#{Postal.locker_name} [a-f0-9]{16}\z/)
expect(queued_message.locked_at).to be_within(1.second).of(Time.current)
end
end
context "when there is an unlocked queued message without an IP address without a retry time in the future" do
it "does nothing" do
queued_message = create(:queued_message, ip_address: nil, retry_after: 10.minutes.from_now)
job.call
expect(MessageDequeuer).to_not have_received(:process)
expect(queued_message.reload.locked?).to be false
end
end
context "when there is a locked queued message without an IP address without a retry time" do
it "does nothing" do
queued_message = create(:queued_message, :locked, ip_address: nil, retry_after: nil)
job.call
expect(MessageDequeuer).to_not have_received(:process)
expect(queued_message.reload.locked?).to be true
end
end
context "when there is a locked queued message without an IP address with a retry time in the past" do
it "does nothing" do
queued_message = create(:queued_message, :locked, ip_address: nil, retry_after: 1.month.ago)
job.call
expect(MessageDequeuer).to_not have_received(:process)
expect(queued_message.reload.locked?).to be true
end
end
context "when there is an unlocked queued message with an IP address that is ours without a retry time" do
it "locks the message and calls the service" do
ip_address = create(:ip_address, ipv4: "10.20.30.40")
allow(Socket).to receive(:ip_address_list).and_return([Addrinfo.new(["AF_INET", 1, "localhost.localdomain", "10.20.30.40"])])
queued_message = create(:queued_message, ip_address: ip_address)
job.call
expect(MessageDequeuer).to have_received(:process).with(queued_message, logger: kind_of(Klogger::Logger))
expect(queued_message.reload.locked?).to be true
expect(queued_message.locked_by).to match(/\A#{Postal.locker_name} [a-f0-9]{16}\z/)
expect(queued_message.locked_at).to be_within(1.second).of(Time.current)
end
end
context "when there is an unlocked queued message with an IP address that is ours without a retry time in the future" do
it "does nothing" do
ip_address = create(:ip_address, ipv4: "10.20.30.40")
allow(Socket).to receive(:ip_address_list).and_return([Addrinfo.new(["AF_INET", 1, "localhost.localdomain", "10.20.30.40"])])
queued_message = create(:queued_message, ip_address: ip_address, retry_after: 1.month.from_now)
job.call
expect(MessageDequeuer).to_not have_received(:process)
expect(queued_message.reload.locked?).to be false
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_client/endpoint_spec.rb | spec/lib/smtp_client/endpoint_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPClient
RSpec.describe Endpoint do
let(:ssl_mode) { SSLModes::AUTO }
let(:server) { Server.new("mx1.example.com", port: 25, ssl_mode: ssl_mode) }
let(:ip) { "1.2.3.4" }
before do
allow(Net::SMTP).to receive(:new).and_wrap_original do |original_method, *args|
smtp = original_method.call(*args)
allow(smtp).to receive(:start)
allow(smtp).to receive(:started?).and_return(true)
allow(smtp).to receive(:send_message)
allow(smtp).to receive(:finish)
smtp
end
end
subject(:endpoint) { described_class.new(server, ip) }
describe "#description" do
it "returns a description for the endpoint" do
expect(endpoint.description).to eq "1.2.3.4:25 (mx1.example.com)"
end
end
describe "#ipv6?" do
context "when the IP address is an IPv6 address" do
let(:ip) { "2a00:67a0:a::1" }
it "returns true" do
expect(endpoint.ipv6?).to be true
end
end
context "when the IP address is an IPv4 address" do
it "returns false" do
expect(endpoint.ipv6?).to be false
end
end
end
describe "#ipv4?" do
context "when the IP address is an IPv4 address" do
it "returns true" do
expect(endpoint.ipv4?).to be true
end
end
context "when the IP address is an IPv6 address" do
let(:ip) { "2a00:67a0:a::1" }
it "returns false" do
expect(endpoint.ipv4?).to be false
end
end
end
describe "#start_smtp_session" do
context "when given no source IP address" do
it "creates a new Net::SMTP client with appropriate details" do
client = endpoint.start_smtp_session
expect(client.address).to eq "1.2.3.4"
end
it "sets the appropriate timeouts from the config" do
client = endpoint.start_smtp_session
expect(client.open_timeout).to eq Postal::Config.smtp_client.open_timeout
expect(client.read_timeout).to eq Postal::Config.smtp_client.read_timeout
end
it "does not set a source address" do
client = endpoint.start_smtp_session
expect(client.source_address).to be_nil
end
it "sets the TLS hostname" do
client = endpoint.start_smtp_session
expect(client.tls_hostname).to eq "mx1.example.com"
end
it "starts the SMTP client the default HELO" do
endpoint.start_smtp_session
expect(endpoint.smtp_client).to have_received(:start).with(Postal::Config.postal.smtp_hostname)
end
context "when the SSL mode is Auto" do
it "enables STARTTLS auto " do
client = endpoint.start_smtp_session
expect(client.starttls?).to eq :auto
end
end
context "when the SSL mode is STARTLS" do
let(:ssl_mode) { SSLModes::STARTTLS }
it "as starttls as always" do
client = endpoint.start_smtp_session
expect(client.starttls?).to eq :always
end
end
context "when the SSL mode is TLS" do
let(:ssl_mode) { SSLModes::TLS }
it "as starttls as always" do
client = endpoint.start_smtp_session
expect(client.tls?).to be true
end
end
context "when the SSL mode is None" do
let(:ssl_mode) { SSLModes::NONE }
it "disables STARTTLS and TLS" do
client = endpoint.start_smtp_session
expect(client.starttls?).to be false
expect(client.tls?).to be false
end
end
context "when the SSL mode is Auto but ssl_allow is false" do
it "disables STARTTLS and TLS" do
client = endpoint.start_smtp_session(allow_ssl: false)
expect(client.starttls?).to be false
expect(client.tls?).to be false
end
end
end
context "when given a source IP address" do
let(:ip_address) { create(:ip_address) }
context "when the endpoint IP is ipv4" do
it "sets the source address to the IPv4 address" do
client = endpoint.start_smtp_session(source_ip_address: ip_address)
expect(client.source_address).to eq ip_address.ipv4
end
end
context "when the endpoint IP is ipv6" do
let(:ip) { "2a00:67a0:a::1" }
it "sets the source address to the IPv6 address" do
client = endpoint.start_smtp_session(source_ip_address: ip_address)
expect(client.source_address).to eq ip_address.ipv6
end
end
it "starts the SMTP client with the IP addresses hostname" do
endpoint.start_smtp_session(source_ip_address: ip_address)
expect(endpoint.smtp_client).to have_received(:start).with(ip_address.hostname)
end
end
end
describe "#send_message" do
context "when the smtp client has not been created" do
it "raises an error" do
expect { endpoint.send_message("", "", "") }.to raise_error Endpoint::SMTPSessionNotStartedError
end
end
context "when the smtp client exists but is not started" do
it "raises an error" do
endpoint.start_smtp_session
expect(endpoint.smtp_client).to receive(:started?).and_return(false)
expect { endpoint.send_message("", "", "") }.to raise_error Endpoint::SMTPSessionNotStartedError
end
end
context "when the smtp client is started" do
before do
endpoint.start_smtp_session
end
it "resets any previous errors" do
expect(endpoint.smtp_client).to receive(:rset_errors)
endpoint.send_message("test message", "from@example.com", "to@example.com")
end
it "sends the message to the SMTP client" do
endpoint.send_message("test message", "from@example.com", "to@example.com")
expect(endpoint.smtp_client).to have_received(:send_message).with("test message", "from@example.com", ["to@example.com"])
end
context "when the connection is reset during sending" do
before do
endpoint.start_smtp_session
allow(endpoint.smtp_client).to receive(:send_message) do
raise Errno::ECONNRESET
end
end
it "closes the SMTP client" do
expect(endpoint).to receive(:finish_smtp_session).and_call_original
endpoint.send_message("test message", "", "")
end
it "retries sending the message once" do
expect(endpoint).to receive(:send_message).twice.and_call_original
endpoint.send_message("test message", "", "")
end
context "if the retry also fails" do
it "raises the error" do
allow(endpoint).to receive(:send_message).and_raise(Errno::ECONNRESET)
expect { endpoint.send_message("test message", "", "") }.to raise_error(Errno::ECONNRESET)
end
end
end
end
end
describe "#reset_smtp_session" do
it "calls rset on the client" do
endpoint.start_smtp_session
expect(endpoint.smtp_client).to receive(:rset)
endpoint.reset_smtp_session
end
context "if there is an error" do
it "finishes the smtp client" do
endpoint.start_smtp_session
allow(endpoint.smtp_client).to receive(:rset).and_raise(StandardError)
expect(endpoint).to receive(:finish_smtp_session)
endpoint.reset_smtp_session
end
end
end
describe "#finish_smtp_session" do
it "calls finish on the client" do
endpoint.start_smtp_session
expect(endpoint.smtp_client).to receive(:finish)
endpoint.finish_smtp_session
end
it "sets the smtp client to nil" do
endpoint.start_smtp_session
endpoint.finish_smtp_session
expect(endpoint.smtp_client).to be_nil
end
context "if the client finish raises an error" do
it "does not raise it" do
endpoint.start_smtp_session
allow(endpoint.smtp_client).to receive(:finish).and_raise(StandardError)
expect { endpoint.finish_smtp_session }.not_to raise_error
end
end
end
describe ".default_helo_hostname" do
context "when the configuration specifies a helo hostname" do
before do
allow(Postal::Config.dns).to receive(:helo_hostname).and_return("helo.example.com")
end
it "returns that" do
expect(described_class.default_helo_hostname).to eq "helo.example.com"
end
end
context "when the configuration does not specify a helo hostname but has an smtp hostname" do
before do
allow(Postal::Config.dns).to receive(:helo_hostname).and_return(nil)
allow(Postal::Config.postal).to receive(:smtp_hostname).and_return("smtp.example.com")
end
it "returns the smtp hostname" do
expect(described_class.default_helo_hostname).to eq "smtp.example.com"
end
end
context "when the configuration has neither a helo hostname or an smtp hostname" do
before do
allow(Postal::Config.dns).to receive(:helo_hostname).and_return(nil)
allow(Postal::Config.postal).to receive(:smtp_hostname).and_return(nil)
end
it "returns localhost" do
expect(described_class.default_helo_hostname).to eq "localhost"
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_client/server_spec.rb | spec/lib/smtp_client/server_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPClient
RSpec.describe Server do
let(:hostname) { "example.com" }
let(:port) { 25 }
let(:ssl_mode) { SSLModes::AUTO }
subject(:server) { described_class.new(hostname, port: port, ssl_mode: ssl_mode) }
describe "#endpoints" do
context "when there are A and AAAA records" do
before do
allow(DNSResolver.local).to receive(:a).and_return(["1.2.3.4", "2.3.4.5"])
allow(DNSResolver.local).to receive(:aaaa).and_return(["2a00::67a0:a::1234", "2a00::67a0:a::2345"])
end
it "asks the resolver for the A and AAAA records for the hostname" do
server.endpoints
expect(DNSResolver.local).to have_received(:a).with(hostname).once
expect(DNSResolver.local).to have_received(:aaaa).with(hostname).once
end
it "returns endpoints for ipv6 addresses followed by ipv4" do
expect(server.endpoints).to match [
have_attributes(ip_address: "2a00::67a0:a::1234"),
have_attributes(ip_address: "2a00::67a0:a::2345"),
have_attributes(ip_address: "1.2.3.4"),
have_attributes(ip_address: "2.3.4.5"),
]
end
end
context "when there are just A records" do
before do
allow(DNSResolver.local).to receive(:a).and_return(["1.2.3.4", "2.3.4.5"])
allow(DNSResolver.local).to receive(:aaaa).and_return([])
end
it "returns ipv4 endpoints" do
expect(server.endpoints).to match [
have_attributes(ip_address: "1.2.3.4"),
have_attributes(ip_address: "2.3.4.5"),
]
end
end
context "when there are just AAAA records" do
before do
allow(DNSResolver.local).to receive(:a).and_return([])
allow(DNSResolver.local).to receive(:aaaa).and_return(["2a00::67a0:a::1234", "2a00::67a0:a::2345"])
end
it "returns ipv6 endpoints" do
expect(server.endpoints).to match [
have_attributes(ip_address: "2a00::67a0:a::1234"),
have_attributes(ip_address: "2a00::67a0:a::2345"),
]
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/postal/signer_spec.rb | spec/lib/postal/signer_spec.rb | # frozen_string_literal: true
require "rails_helper"
module Postal
RSpec.describe Signer do
STATIC_PRIVATE_KEY = OpenSSL::PKey::RSA.new(2048) # rubocop:disable Lint/ConstantDefinitionInBlock
subject(:signer) { described_class.new(STATIC_PRIVATE_KEY) }
describe "#private_key" do
it "returns the private key" do
expect(signer.private_key).to eq(STATIC_PRIVATE_KEY)
end
end
describe "#public_key" do
it "returns the public key" do
expect(signer.public_key.to_s).to eq(STATIC_PRIVATE_KEY.public_key.to_s)
end
end
describe "#sign" do
it "returns a valid signature" do
data = "hello world!"
signature = signer.sign(data)
expect(signature).to be_a(String)
verification = STATIC_PRIVATE_KEY.public_key.verify(OpenSSL::Digest.new("SHA256"),
signature,
data)
expect(verification).to be true
end
end
describe "#sign64" do
it "returns a valid Base64-encoded signature" do
data = "hello world!"
signature = signer.sign64(data)
expect(signature).to be_a(String)
verification = STATIC_PRIVATE_KEY.public_key.verify(OpenSSL::Digest.new("SHA256"),
Base64.strict_decode64(signature),
data)
expect(verification).to be true
end
end
describe "#jwk" do
it "returns a valid JWK" do
jwk = signer.jwk
expect(jwk).to be_a(JWT::JWK::RSA)
end
end
describe "#sha1_sign" do
it "returns a valid signature" do
data = "hello world!"
signature = signer.sha1_sign(data)
expect(signature).to be_a(String)
verification = STATIC_PRIVATE_KEY.public_key.verify(OpenSSL::Digest.new("SHA1"),
signature,
data)
expect(verification).to be true
end
end
describe "#sha1_sign64" do
it "returns a valid Base64-encoded signature" do
data = "hello world!"
signature = signer.sha1_sign64(data)
expect(signature).to be_a(String)
verification = STATIC_PRIVATE_KEY.public_key.verify(OpenSSL::Digest.new("SHA1"),
Base64.strict_decode64(signature),
data)
expect(verification).to be true
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/postal/message_parser_spec.rb | spec/lib/postal/message_parser_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe Postal::MessageParser do
let(:server) { create(:server) }
it "should not do anything when there are no tracking domains" do
expect(server.track_domains.size).to eq 0
message = create_plain_text_message(server, "Hello world!", "test@example.com")
parser = Postal::MessageParser.new(message)
expect(parser.actioned?).to be false
expect(parser.tracked_links).to eq 0
expect(parser.tracked_images).to eq 0
end
it "should replace links in messages" do
message = create_plain_text_message(server, "Hello world! http://github.com/atech/postal", "test@example.com")
create(:track_domain, server: server, domain: message.domain)
parser = Postal::MessageParser.new(message)
expect(parser.actioned?).to be true
expect(parser.new_body).to match(/^Hello world! https:\/\/click\.#{message.domain.name}/)
expect(parser.tracked_links).to eq 1
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/postal/legacy_config_source_spec.rb | spec/lib/postal/legacy_config_source_spec.rb | # frozen_string_literal: true
require "rails_helper"
module Postal
SOURCE_CONFIG = YAML.safe_load(File.read(Rails.root.join("spec/examples/full_legacy_config_file.yml")))
# Rather than actuall test the LegacyConfigSource directly, I have decided
# to test this source via. the Konfig::Config system to ensure it works as
# expected in practice rather than just in theory. Testing '#get' would be
# fairly easy (and mostly pointless) where as testing the values we actually
# want are correct is preferred.
RSpec.describe LegacyConfigSource do
before do
# For the purposes of testing, we want to ignore any defaults provided
# by the schema itself. Otherwise, we might see a value returned that
# looks correct but is actually the default rather than the value from
# config file.
allow_any_instance_of(Konfig::SchemaAttribute).to receive(:default) do |a|
a.array? ? [] : nil
end
end
let(:source) { described_class.new(SOURCE_CONFIG) }
subject(:config) { Konfig::Config.build(ConfigSchema, sources: [source]) }
describe "the 'postal' group" do
it "returns a value for postal.web_hostname" do
expect(config.postal.web_hostname).to eq "postal.llamas.com"
end
it "returns a value for postal.web_protocol" do
expect(config.postal.web_protocol).to eq "https"
end
it "returns a value for postal.smtp_hostname" do
expect(config.postal.smtp_hostname).to eq "smtp.postal.llamas.com"
end
it "returns a value for postal.use_ip_pools?" do
expect(config.postal.use_ip_pools?).to eq false
end
it "returns a value for postal.default_maximum_delivery_attempts" do
expect(config.postal.default_maximum_delivery_attempts).to eq 20
end
it "returns a value for postal.default_maximum_hold_expiry_days" do
expect(config.postal.default_maximum_hold_expiry_days).to eq 10
end
it "returns a value for postal.default_suppression_list_automatic_removal_days" do
expect(config.postal.default_suppression_list_automatic_removal_days).to eq 60
end
it "returns a value for postal.use_local_ns_for_domain_verification?" do
expect(config.postal.use_local_ns_for_domain_verification?).to eq true
end
it "returns a value for postal.default_spam_threshold" do
expect(config.postal.default_spam_threshold).to eq 10
end
it "returns a value for postal.default_spam_failure_threshold" do
expect(config.postal.default_spam_failure_threshold).to eq 25
end
it "returns a value for postal.use_resent_sender_header?" do
expect(config.postal.use_resent_sender_header?).to eq true
end
it "returns a value for postal.smtp_relays" do
expect(config.postal.smtp_relays).to eq [
{ "host" => "1.2.3.4", "port" => 25, "ssl_mode" => "Auto" },
{ "host" => "2.2.2.2", "port" => 2525, "ssl_mode" => "None" },
]
end
end
describe "the 'web_server' group" do
it "returns a value for web_server.default_bind_address" do
expect(config.web_server.default_bind_address).to eq "127.0.0.1"
end
it "returns a value for web_server.default_port" do
expect(config.web_server.default_port).to eq 6000
end
it "returns a value for web_server.max_threads" do
expect(config.web_server.max_threads).to eq 10
end
end
describe "the 'main_db' group" do
it "returns a value for main_db.host" do
expect(config.main_db.host).to eq "localhost"
end
it "returns a value for main_db.port" do
expect(config.main_db.port).to eq 3306
end
it "returns a value for main_db.username" do
expect(config.main_db.username).to eq "postal"
end
it "returns a value for main_db.password" do
expect(config.main_db.password).to eq "t35tpassword"
end
it "returns a value for main_db.database" do
expect(config.main_db.database).to eq "postal"
end
it "returns a value for main_db.pool_size" do
expect(config.main_db.pool_size).to eq 20
end
it "returns a value for main_db.encoding" do
expect(config.main_db.encoding).to eq "utf8mb4"
end
end
describe "the 'message_db' group" do
it "returns a value for message_db.host" do
expect(config.message_db.host).to eq "localhost"
end
it "returns a value for message_db.port" do
expect(config.message_db.port).to eq 3306
end
it "returns a value for message_db.username" do
expect(config.message_db.username).to eq "postal"
end
it "returns a value for message_db.password" do
expect(config.message_db.password).to eq "p05t41"
end
it "returns a value for message_db.database_name_prefix" do
expect(config.message_db.database_name_prefix).to eq "postal"
end
end
describe "the 'logging' group" do
it "returns a value for logging.rails_log_enabled" do
expect(config.logging.rails_log_enabled).to eq true
end
end
describe "the 'gelf' group" do
it "returns a value for gelf.host" do
expect(config.gelf.host).to eq "logs.llamas.com"
end
it "returns a value for gelf.port" do
expect(config.gelf.port).to eq 12_201
end
it "returns a value for gelf.facility" do
expect(config.gelf.facility).to eq "mailer"
end
end
describe "the 'smtp_server' group" do
it "returns a value for smtp_server.default_port" do
expect(config.smtp_server.default_port).to eq 25
end
it "returns a value for smtp_server.default_bind_address" do
expect(config.smtp_server.default_bind_address).to eq "127.0.0.1"
end
it "returns a value for smtp_server.tls_enabled" do
expect(config.smtp_server.tls_enabled).to eq true
end
it "returns a value for smtp_server.tls_certificate_path" do
expect(config.smtp_server.tls_certificate_path).to eq "config/smtp.cert"
end
it "returns a value for smtp_server.tls_private_key_path" do
expect(config.smtp_server.tls_private_key_path).to eq "config/smtp.key"
end
it "returns a value for smtp_server.tls_ciphers" do
expect(config.smtp_server.tls_ciphers).to eq "abc"
end
it "returns a value for smtp_server.ssl_version" do
expect(config.smtp_server.ssl_version).to eq "SSLv23"
end
it "returns a value for smtp_server.proxy_protocol" do
expect(config.smtp_server.proxy_protocol).to eq false
end
it "returns a value for smtp_server.log_connections" do
expect(config.smtp_server.log_connections).to eq true
end
it "returns a value for smtp_server.max_message_size" do
expect(config.smtp_server.max_message_size).to eq 10
end
end
describe "the 'dns' group" do
it "returns a value for dns.mx_records" do
expect(config.dns.mx_records).to eq ["mx1.postal.llamas.com", "mx2.postal.llamas.com"]
end
it "returns a value for dns.spf_include" do
expect(config.dns.spf_include).to eq "spf.postal.llamas.com"
end
it "returns a value for dns.return_path_domain" do
expect(config.dns.return_path_domain).to eq "rp.postal.llamas.com"
end
it "returns a value for dns.route_domain" do
expect(config.dns.route_domain).to eq "routes.postal.llamas.com"
end
it "returns a value for dns.track_domain" do
expect(config.dns.track_domain).to eq "track.postal.llamas.com"
end
it "returns a value for dns.helo_hostname" do
expect(config.dns.helo_hostname).to eq "helo.postal.llamas.com"
end
it "returns a value for dns.dkim_identifier" do
expect(config.dns.dkim_identifier).to eq "postal"
end
it "returns a value for dns.domain_verify_prefix" do
expect(config.dns.domain_verify_prefix).to eq "postal-verification"
end
it "returns a value for dns.custom_return_path_prefix" do
expect(config.dns.custom_return_path_prefix).to eq "psrp"
end
end
describe "the 'smtp' group" do
it "returns a value for smtp.host" do
expect(config.smtp.host).to eq "127.0.0.1"
end
it "returns a value for smtp.port" do
expect(config.smtp.port).to eq 25
end
it "returns a value for smtp.username" do
expect(config.smtp.username).to eq "postalserver"
end
it "returns a value for smtp.password" do
expect(config.smtp.password).to eq "llama"
end
it "returns a value for smtp.from_name" do
expect(config.smtp.from_name).to eq "Postal"
end
it "returns a value for smtp.from_address" do
expect(config.smtp.from_address).to eq "postal@llamas.com"
end
end
describe "the 'rails' group" do
it "returns a value for rails.environment" do
expect(config.rails.environment).to eq "production"
end
it "returns a value for rails.secret_key" do
expect(config.rails.secret_key).to eq "abcdef123123123123123"
end
end
describe "the 'rspamd' group" do
it "returns a value for rspamd.enabled" do
expect(config.rspamd.enabled).to eq true
end
it "returns a value for rspamd.host" do
expect(config.rspamd.host).to eq "rspamd.llamas.com"
end
it "returns a value for rspamd.port" do
expect(config.rspamd.port).to eq 11_334
end
it "returns a value for rspamd.ssl?" do
expect(config.rspamd.ssl?).to eq false
end
it "returns a value for rspamd.password" do
expect(config.rspamd.password).to eq "llama"
end
it "returns a value for rspamd.flags" do
expect(config.rspamd.flags).to eq "abc"
end
end
describe "the 'spamd' group" do
it "returns a value for spamd.enabled" do
expect(config.spamd.enabled).to eq false
end
it "returns a value for spamd.host" do
expect(config.spamd.host).to eq "spamd.llamas.com"
end
it "returns a value for spamd.port" do
expect(config.spamd.port).to eq 783
end
end
describe "the 'clamav' group" do
it "returns a value for clamav.enabled" do
expect(config.clamav.enabled).to eq false
end
it "returns a value for clamav.host" do
expect(config.clamav.host).to eq "clamav.llamas.com"
end
it "returns a value for clamav.port" do
expect(config.clamav.port).to eq 2000
end
end
describe "the 'smtp_client' group" do
it "returns a value for smtp_client.open_timeout" do
expect(config.smtp_client.open_timeout).to eq 60
end
it "returns a value for smtp_client.read_timeout" do
expect(config.smtp_client.read_timeout).to eq 120
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/postal/message_db/database_spec.rb | spec/lib/postal/message_db/database_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe Postal::MessageDB::Database do
context "when provisioned" do
let(:server) { create(:server) }
subject(:database) { server.message_db }
it "should be a message db" do
expect(database).to be_a Postal::MessageDB::Database
end
it "should return the current schema version" do
expect(database.schema_version).to be_a Integer
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/postal/message_db/connection_pool_spec.rb | spec/lib/postal/message_db/connection_pool_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe Postal::MessageDB::ConnectionPool do
subject(:pool) { described_class.new }
describe "#use" do
it "yields a connection" do
counter = 0
pool.use do |connection|
expect(connection).to be_a Mysql2::Client
counter += 1
end
expect(counter).to eq 1
end
it "checks in a connection after the block has executed" do
connection = nil
pool.use do |c|
expect(pool.connections).to be_empty
connection = c
end
expect(pool.connections).to eq [connection]
end
it "checks in a connection if theres an error in the block" do
expect do
pool.use do
raise StandardError
end
end.to raise_error StandardError
expect(pool.connections).to match [kind_of(Mysql2::Client)]
end
it "does not check in connections when there is a connection error" do
expect do
pool.use do
raise Mysql2::Error, "lost connection to server"
end
end.to raise_error Mysql2::Error
expect(pool.connections).to eq []
end
it "retries the block once if there is a connection error" do
clients_seen = []
expect do
pool.use do |client|
clients_seen << client
raise Mysql2::Error, "lost connection to server"
end
end.to raise_error Mysql2::Error
expect(clients_seen.uniq.size).to eq 2
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client_spec.rb | spec/lib/smtp_server/client_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
subject(:client) { described_class.new(ip_address) }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/proxy_spec.rb | spec/lib/smtp_server/client/proxy_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { nil }
subject(:client) { described_class.new(ip_address) }
describe "PROXY" do
context "when the proxy header is sent correctly" do
it "sets the IP address" do
expect(client.handle("PROXY TCP4 1.1.1.1 2.2.2.2 1111 2222")).to eq "220 #{Postal::Config.postal.smtp_hostname} ESMTP Postal/#{client.trace_id}"
expect(client.ip_address).to eq "1.1.1.1"
end
end
context "when the proxy header is not valid" do
it "returns an error" do
expect(client.handle("PROXY TCP4")).to eq "502 Proxy Error"
expect(client.finished?).to be true
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/data_spec.rb | spec/lib/smtp_server/client/data_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
subject(:client) { described_class.new(ip_address) }
describe "DATA" do
it "returns an error if no helo" do
expect(client.handle("DATA")).to eq "503 HELO/EHLO, MAIL FROM and RCPT TO before sending data"
end
it "returns an error if no mail from" do
client.handle("HELO test.example.com")
expect(client.handle("DATA")).to eq "503 HELO/EHLO, MAIL FROM and RCPT TO before sending data"
end
it "returns an error if no rcpt to" do
client.handle("HELO test.example.com")
client.handle("MAIL FROM: test@example.com")
expect(client.handle("DATA")).to eq "503 HELO/EHLO, MAIL FROM and RCPT TO before sending data"
end
it "returns go ahead" do
route = create(:route)
client.handle("HELO test.example.com")
client.handle("MAIL FROM: test@test.com")
client.handle("RCPT TO: #{route.name}@#{route.domain.name}")
expect(client.handle("DATA")).to eq "354 Go ahead"
end
it "adds a received header for itself" do
route = create(:route)
client.handle("HELO test.example.com")
client.handle("MAIL FROM: test@test.com")
client.handle("RCPT TO: #{route.name}@#{route.domain.name}")
Timecop.freeze do
client.handle("DATA")
expect(client.headers["received"]).to include "from test.example.com (1.2.3.4 [1.2.3.4]) by #{Postal::Config.postal.smtp_hostname} with SMTP; #{Time.now.utc.rfc2822}"
end
end
describe "subsequent commands" do
let(:route) { create(:route) }
before do
client.handle("HELO test.example.com")
client.handle("MAIL FROM: test@test.com")
client.handle("RCPT TO: #{route.name}@#{route.domain.name}")
end
it "logs headers" do
client.handle("DATA")
client.handle("Subject: Test")
client.handle("From: test@test.com")
client.handle("To: test1@example.com")
client.handle("To: test2@example.com")
client.handle("X-Something: abcdef1234")
client.handle("X-Multiline: 1234")
client.handle(" 4567")
expect(client.headers["subject"]).to eq ["Test"]
expect(client.headers["from"]).to eq ["test@test.com"]
expect(client.headers["to"]).to eq ["test1@example.com", "test2@example.com"]
expect(client.headers["x-something"]).to eq ["abcdef1234"]
expect(client.headers["x-multiline"]).to eq ["1234 4567"]
end
it "logs content" do
Timecop.freeze do
client.handle("DATA")
client.handle("Subject: Test")
client.handle("")
client.handle("This is some content for the message.")
client.handle("It will keep going.")
expect(client.instance_variable_get("@data")).to eq <<~DATA
Received: from test.example.com (1.2.3.4 [1.2.3.4]) by #{Postal::Config.postal.smtp_hostname} with SMTP; #{Time.now.utc.rfc2822}\r
Subject: Test\r
\r
This is some content for the message.\r
It will keep going.\r
DATA
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/auth_spec.rb | spec/lib/smtp_server/client/auth_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
subject(:client) { described_class.new(ip_address) }
before do
client.handle("HELO test.example.com")
end
describe "AUTH PLAIN" do
context "when no credentials are provided on the initial data" do
it "returns a 334" do
expect(client.handle("AUTH PLAIN")).to eq("334")
end
it "accepts the username and password from the next input" do
client.handle("AUTH PLAIN")
credential = create(:credential, type: "SMTP")
expect(client.handle(credential.to_smtp_plain)).to match(/235 Granted for/)
end
end
context "when valid credentials are provided on one line" do
it "authenticates and returns a response" do
credential = create(:credential, type: "SMTP")
expect(client.handle("AUTH PLAIN #{credential.to_smtp_plain}")).to match(/235 Granted for/)
expect(client.credential).to eq credential
end
end
context "when invalid credentials are provided" do
it "returns an error and resets the state" do
base64 = Base64.encode64("user\0pass")
expect(client.handle("AUTH PLAIN #{base64}")).to eq("535 Invalid credential")
expect(client.state).to eq :welcomed
end
end
context "when username or password is missing" do
it "returns an error and resets the state" do
base64 = Base64.encode64("pass")
expect(client.handle("AUTH PLAIN #{base64}")).to eq("535 Authenticated failed - protocol error")
expect(client.state).to eq :welcomed
end
end
end
describe "AUTH LOGIN" do
context "when no username is provided on the first line" do
it "requests the username" do
expect(client.handle("AUTH LOGIN")).to eq("334 VXNlcm5hbWU6")
end
it "requests a password after a username" do
client.handle("AUTH LOGIN")
expect(client.handle("xx")).to eq("334 UGFzc3dvcmQ6")
end
it "authenticates and returns a response if the password is correct" do
client.handle("AUTH LOGIN")
client.handle("xx")
credential = create(:credential, type: "SMTP")
password = Base64.encode64(credential.key)
expect(client.handle(password)).to match(/235 Granted for/)
end
it "returns an error when an invalid credential is provided" do
client.handle("AUTH LOGIN")
client.handle("xx")
password = Base64.encode64("xx")
expect(client.handle(password)).to eq("535 Invalid credential")
end
end
context "when a username is provided on the first line" do
it "requests a password" do
username = Base64.encode64("xx")
expect(client.handle("AUTH LOGIN #{username}")).to eq("334 UGFzc3dvcmQ6")
end
it "authenticates and returns a response" do
credential = create(:credential, type: "SMTP")
username = Base64.encode64("xx")
password = Base64.encode64(credential.key)
expect(client.handle("AUTH LOGIN #{username}")).to eq("334 UGFzc3dvcmQ6")
expect(client.handle(password)).to match(/235 Granted for/)
expect(client.credential).to eq credential
end
it "returns an error and resets the state" do
username = Base64.encode64("xx")
password = Base64.encode64("xx")
expect(client.handle("AUTH LOGIN #{username}")).to eq("334 UGFzc3dvcmQ6")
expect(client.handle(password)).to eq("535 Invalid credential")
expect(client.state).to eq :welcomed
end
end
end
describe "AUTH CRAM-MD5" do
context "when valid credentials are provided" do
it "authenticates and returns a response" do
credential = create(:credential, type: "SMTP")
result = client.handle("AUTH CRAM-MD5")
expect(result).to match(/\A334 [A-Za-z0-9=]+\z/)
challenge = Base64.decode64(result.split[1])
password = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("md5"), credential.key, challenge)
base64 = Base64.encode64("#{credential.server.organization.permalink}/#{credential.server.permalink} #{password}")
expect(client.handle(base64)).to match(/235 Granted for/)
expect(client.credential).to eq credential
end
end
context "when no org/server matches the provided username" do
it "returns an error" do
client.handle("AUTH CRAM-MD5")
base64 = Base64.encode64("org/server password")
expect(client.handle(base64)).to eq "535 Denied"
end
end
context "when invalid credentials are provided" do
it "returns an error and resets the state" do
server = create(:server)
base64 = Base64.encode64("#{server.organization.permalink}/#{server.permalink} invalid-password")
client.handle("AUTH CRAM-MD5")
expect(client.handle(base64)).to eq("535 Denied")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/rcpt_to_spec.rb | spec/lib/smtp_server/client/rcpt_to_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
subject(:client) { described_class.new(ip_address) }
describe "RCPT TO" do
let(:helo) { "test.example.com" }
let(:mail_from) { "test@example.com" }
before do
client.handle("HELO #{helo}")
client.handle("MAIL FROM: #{mail_from}") if mail_from
end
context "when MAIL FROM has not been sent" do
let(:mail_from) { nil }
it "returns an error if RCPT TO is sent before MAIL FROM" do
expect(client.handle("RCPT TO: no-route-here@internal.com")).to eq "503 EHLO/HELO and MAIL FROM first please"
expect(client.state).to eq :welcomed
end
end
it "returns an error if RCPT TO is not valid" do
expect(client.handle("RCPT TO: blah")).to eq "501 Invalid RCPT TO"
end
it "returns an error if RCPT TO is empty" do
expect(client.handle("RCPT TO: ")).to eq "501 RCPT TO should not be empty"
end
context "when the RCPT TO address is the system return path host" do
it "returns an error if the server does not exist" do
expect(client.handle("RCPT TO: nothing@#{Postal::Config.dns.return_path_domain}")).to eq "550 Invalid server token"
end
it "returns an error if the server is suspended" do
server = create(:server, :suspended)
expect(client.handle("RCPT TO: #{server.token}@#{Postal::Config.dns.return_path_domain}"))
.to eq "535 Mail server has been suspended"
end
it "adds a recipient if all OK" do
server = create(:server)
address = "#{server.token}@#{Postal::Config.dns.return_path_domain}"
expect(client.handle("RCPT TO: #{address}")).to eq "250 OK"
expect(client.recipients).to eq [[:bounce, address, server]]
expect(client.state).to eq :rcpt_to_received
end
end
context "when the RCPT TO address is on a host using the return path prefix" do
it "returns an error if the server does not exist" do
address = "nothing@#{Postal::Config.dns.custom_return_path_prefix}.example.com"
expect(client.handle("RCPT TO: #{address}")).to eq "550 Invalid server token"
end
it "returns an error if the server is suspended" do
server = create(:server, :suspended)
address = "#{server.token}@#{Postal::Config.dns.custom_return_path_prefix}.example.com"
expect(client.handle("RCPT TO: #{address}")).to eq "535 Mail server has been suspended"
end
it "adds a recipient if all OK" do
server = create(:server)
address = "#{server.token}@#{Postal::Config.dns.custom_return_path_prefix}.example.com"
expect(client.handle("RCPT TO: #{address}")).to eq "250 OK"
expect(client.recipients).to eq [[:bounce, address, server]]
expect(client.state).to eq :rcpt_to_received
end
end
context "when the RCPT TO address is within the route domain" do
it "returns an error if the route token is invalid" do
address = "nothing@#{Postal::Config.dns.route_domain}"
expect(client.handle("RCPT TO: #{address}")).to eq "550 Invalid route token"
end
it "returns an error if the server is suspended" do
server = create(:server, :suspended)
route = create(:route, server: server)
address = "#{route.token}@#{Postal::Config.dns.route_domain}"
expect(client.handle("RCPT TO: #{address}")).to eq "535 Mail server has been suspended"
end
it "returns an error if the route is set to Reject mail" do
server = create(:server)
route = create(:route, server: server, mode: "Reject")
address = "#{route.token}@#{Postal::Config.dns.route_domain}"
expect(client.handle("RCPT TO: #{address}")).to eq "550 Route does not accept incoming messages"
end
it "adds a recipient if all OK" do
server = create(:server)
route = create(:route, server: server)
address = "#{route.token}+tag1@#{Postal::Config.dns.route_domain}"
expect(client.handle("RCPT TO: #{address}")).to eq "250 OK"
expect(client.recipients).to eq [[:route, "#{route.name}+tag1@#{route.domain.name}", server, { route: route }]]
expect(client.state).to eq :rcpt_to_received
end
end
context "when authenticated and the RCPT TO address is provided" do
it "returns an error if the server is suspended" do
server = create(:server, :suspended)
credential = create(:credential, server: server, type: "SMTP")
expect(client.handle("AUTH PLAIN #{credential.to_smtp_plain}")).to match(/235 Granted for /)
expect(client.handle("RCPT TO: outgoing@example.com")).to eq "535 Mail server has been suspended"
end
it "adds a recipient if all OK" do
server = create(:server)
credential = create(:credential, server: server, type: "SMTP")
expect(client.handle("AUTH PLAIN #{credential.to_smtp_plain}")).to match(/235 Granted for /)
expect(client.handle("RCPT TO: outgoing@example.com")).to eq "250 OK"
expect(client.recipients).to eq [[:credential, "outgoing@example.com", server]]
expect(client.state).to eq :rcpt_to_received
end
end
context "when not authenticated and the RCPT TO address is a route" do
it "returns an error if the server is suspended" do
server = create(:server, :suspended)
route = create(:route, server: server)
address = "#{route.name}@#{route.domain.name}"
expect(client.handle("RCPT TO: #{address}")).to eq "535 Mail server has been suspended"
end
it "returns an error if the route is set to Reject mail" do
server = create(:server)
route = create(:route, server: server, mode: "Reject")
address = "#{route.name}@#{route.domain.name}"
expect(client.handle("RCPT TO: #{address}")).to eq "550 Route does not accept incoming messages"
end
it "adds a recipient if all OK" do
server = create(:server)
route = create(:route, server: server)
address = "#{route.name}@#{route.domain.name}"
expect(client.handle("RCPT TO: #{address}")).to eq "250 OK"
expect(client.recipients).to eq [[:route, address, server, { route: route }]]
expect(client.state).to eq :rcpt_to_received
end
end
context "when not authenticated and RCPT TO does not match a route" do
it "returns an error" do
expect(client.handle("RCPT TO: nothing@nothing.com")).to eq "530 Authentication required"
end
context "when the connecting IP has an credential" do
it "adds a recipient" do
server = create(:server)
create(:credential, server: server, type: "SMTP-IP", key: "1.0.0.0/8")
address = "test@example.com"
expect(client.handle("RCPT TO: #{address}")).to eq "250 OK"
expect(client.recipients).to eq [[:credential, address, server]]
expect(client.state).to eq :rcpt_to_received
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/helo_spec.rb | spec/lib/smtp_server/client/helo_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
subject(:client) { described_class.new(ip_address) }
describe "HELO" do
it "returns the hostname" do
expect(client.state).to eq :welcome
expect(client.handle("HELO: test.example.com")).to eq "250 #{Postal::Config.postal.smtp_hostname}"
expect(client.state).to eq :welcomed
end
end
describe "EHLO" do
it "returns the capabilities" do
expect(client.handle("EHLO test.example.com")).to eq ["250-My capabilities are",
"250 AUTH CRAM-MD5 PLAIN LOGIN",]
end
context "when TLS is enabled" do
it "returns capabilities include starttls" do
allow(Postal::Config.smtp_server).to receive(:tls_enabled?).and_return(true)
expect(client.handle("EHLO test.example.com")).to eq ["250-My capabilities are",
"250-STARTTLS",
"250 AUTH CRAM-MD5 PLAIN LOGIN",]
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/finished_spec.rb | spec/lib/smtp_server/client/finished_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
let(:server) { create(:server) }
subject(:client) { described_class.new(ip_address) }
let(:credential) { create(:credential, server: server, type: "SMTP") }
let(:auth_plain) { credential&.to_smtp_plain }
let(:mail_from) { "test@example.com" }
let(:rcpt_to) { "test@example.com" }
before do
client.handle("HELO test.example.com")
client.handle("AUTH PLAIN #{auth_plain}") if auth_plain
client.handle("MAIL FROM: #{mail_from}")
client.handle("RCPT TO: #{rcpt_to}")
end
describe "when finished sending data" do
context "when the . character does not end with a <CR>" do
it "does nothing" do
allow(Postal::Config.smtp_server).to receive(:max_message_size).and_return(1)
client.handle("DATA")
client.handle("Subject: Hello")
client.handle("\r")
expect(client.handle(".")).to be nil
end
end
context "when the data before the . character does not end with a <CR>" do
it "does nothing" do
allow(Postal::Config.smtp_server).to receive(:max_message_size).and_return(1)
client.handle("DATA")
client.handle("Subject: Hello")
expect(client.handle(".\r")).to be nil
end
end
context "when the data is larger than the maximum message size" do
it "returns an error and resets the state" do
allow(Postal::Config.smtp_server).to receive(:max_message_size).and_return(1)
client.handle("DATA")
client.handle("a" * 1024 * 1024 * 10)
client.handle("\r")
expect(client.handle(".\r")).to eq "552 Message too large (maximum size 1MB)"
end
end
context "when a loop is detected" do
it "returns an error and resets the state" do
client.handle("DATA")
client.handle("Received: from example1.com by #{Postal::Config.postal.smtp_hostname}")
client.handle("Received: from example2.com by #{Postal::Config.postal.smtp_hostname}")
client.handle("Received: from example1.com by #{Postal::Config.postal.smtp_hostname}")
client.handle("Received: from example2.com by #{Postal::Config.postal.smtp_hostname}")
client.handle("Subject: Test")
client.handle("From: #{mail_from}")
client.handle("To: #{rcpt_to}")
client.handle("")
client.handle("This is a test message")
client.handle("\r")
expect(client.handle(".\r")).to eq "550 Loop detected"
end
end
context "when the email content is not suitable for the credential" do
it "returns an error and resets the state" do
client.handle("DATA")
client.handle("Subject: Test")
client.handle("From: invalid@krystal.uk")
client.handle("To: #{rcpt_to}")
client.handle("")
client.handle("This is a test message")
client.handle("\r")
expect(client.handle(".\r")).to eq "530 From/Sender name is not valid"
end
end
context "when sending an outgoing email" do
let(:domain) { create(:domain, owner: server) }
let(:mail_from) { "test@#{domain.name}" }
let(:auth_plain) { credential.to_smtp_plain }
it "stores the message and resets the state" do
client.handle("DATA")
client.handle("Subject: Test")
client.handle("From: #{mail_from}")
client.handle("To: #{rcpt_to}")
client.handle("")
client.handle("This is a test message")
client.handle("\r")
expect(client.handle(".\r")).to eq "250 OK"
queued_message = QueuedMessage.first
expect(queued_message).to have_attributes(
domain: "example.com",
server: server
)
expect(server.message(queued_message.message_id)).to have_attributes(
mail_from: mail_from,
rcpt_to: rcpt_to,
subject: "Test",
scope: "outgoing",
route_id: nil,
credential_id: credential.id,
raw_headers: kind_of(String),
raw_message: kind_of(String)
)
end
end
context "when sending a bounce message" do
let(:credential) { nil }
let(:rcpt_to) { "#{server.token}@#{Postal::Config.dns.return_path_domain}" }
context "when there is a return path route" do
let(:domain) { create(:domain, owner: server) }
before do
endpoint = create(:http_endpoint, server: server)
create(:route, domain: domain, server: server, name: "__returnpath__", mode: "Endpoint", endpoint: endpoint)
end
it "stores the message for the return path route and resets the state" do
client.handle("DATA")
client.handle("Subject: Bounce: Test")
client.handle("From: #{mail_from}")
client.handle("To: #{rcpt_to}")
client.handle("")
client.handle("This is a test message")
client.handle("\r")
expect(client.handle(".\r")).to eq "250 OK"
queued_message = QueuedMessage.first
expect(queued_message).to have_attributes(
domain: Postal::Config.dns.return_path_domain,
server: server
)
expect(server.message(queued_message.message_id)).to have_attributes(
mail_from: mail_from,
rcpt_to: rcpt_to,
subject: "Bounce: Test",
scope: "incoming",
route_id: server.routes.first.id,
domain_id: domain.id,
credential_id: nil,
raw_headers: kind_of(String),
raw_message: kind_of(String),
bounce: true
)
end
end
context "when there is no return path route" do
it "stores the message normally and resets the state" do
client.handle("DATA")
client.handle("Subject: Bounce: Test")
client.handle("From: #{mail_from}")
client.handle("To: #{rcpt_to}")
client.handle("")
client.handle("This is a test message")
client.handle("\r")
expect(client.handle(".\r")).to eq "250 OK"
queued_message = QueuedMessage.first
expect(queued_message).to have_attributes(
domain: Postal::Config.dns.return_path_domain,
server: server
)
expect(server.message(queued_message.message_id)).to have_attributes(
mail_from: mail_from,
rcpt_to: rcpt_to,
subject: "Bounce: Test",
scope: "incoming",
route_id: nil,
domain_id: nil,
credential_id: nil,
raw_headers: kind_of(String),
raw_message: kind_of(String),
bounce: true
)
end
end
end
context "when receiving an incoming email" do
let(:domain) { create(:domain, owner: server) }
let(:route) { create(:route, server: server, domain: domain) }
let(:credential) { nil }
let(:rcpt_to) { "#{route.name}@#{domain.name}" }
it "stores the message and resets the state" do
client.handle("DATA")
client.handle("Subject: Test")
client.handle("From: #{mail_from}")
client.handle("To: #{rcpt_to}")
client.handle("")
client.handle("This is a test message")
client.handle("\r")
expect(client.handle(".\r")).to eq "250 OK"
queued_message = QueuedMessage.first
expect(queued_message).to have_attributes(
domain: domain.name,
server: server
)
expect(server.message(queued_message.message_id)).to have_attributes(
mail_from: mail_from,
rcpt_to: rcpt_to,
subject: "Test",
scope: "incoming",
route_id: route.id,
domain_id: domain.id,
credential_id: nil,
raw_headers: kind_of(String),
raw_message: kind_of(String)
)
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/smtp_server/client/mail_from_spec.rb | spec/lib/smtp_server/client/mail_from_spec.rb | # frozen_string_literal: true
require "rails_helper"
module SMTPServer
describe Client do
let(:ip_address) { "1.2.3.4" }
subject(:client) { described_class.new(ip_address) }
describe "MAIL FROM" do
it "returns an error if no HELO is provided" do
expect(client.handle("MAIL FROM: test@example.com")).to eq "503 EHLO/HELO first please"
expect(client.state).to eq :welcome
end
it "resets the transaction when called" do
expect(client).to receive(:transaction_reset).and_call_original.at_least(3).times
client.handle("HELO test.example.com")
client.handle("MAIL FROM: test@example.com")
client.handle("MAIL FROM: test2@example.com")
end
it "sets the mail from address" do
client.handle("HELO test.example.com")
expect(client.handle("MAIL FROM: test@example.com")).to eq "250 OK"
expect(client.state).to eq :mail_from_received
expect(client.instance_variable_get("@mail_from")).to eq "test@example.com"
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer/initial_message_processor_spec.rb | spec/lib/message_dequeuer/initial_message_processor_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MessageDequeuer
RSpec.describe InitialProcessor do
let(:server) { create(:server) }
let(:logger) { TestLogger.new }
let(:route) { create(:route, server: server) }
let(:message) { MessageFactory.incoming(server, route: route) }
let(:queued_message) { create(:queued_message, :locked, message: message) }
subject(:processor) { described_class.new(queued_message, logger: logger) }
it "has state when not given any" do
expect(processor.state).to be_a State
end
context "when associated message does not exist" do
let(:queued_message) { create(:queued_message, :locked, message_id: 12_345) }
it "logs" do
processor.process
expect(logger).to have_logged(/unqueue because backend message has been removed/)
end
it "removes from queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the queued message is not ready for processing" do
let(:queued_message) { create(:queued_message, :locked, message: message, retry_after: 1.hour.from_now) }
it "logs" do
processor.process
expect(logger).to have_logged(/skipping because message isn't ready for processing/)
end
it "unlocks and keeps the queued message" do
processor.process
expect(queued_message.reload).to_not be_locked
end
end
context "when there are no other batchable messages" do
it "calls the single message processor for the initial message" do
expect(SingleMessageProcessor).to receive(:process).with(queued_message,
logger: logger,
state: processor.state)
processor.process
end
end
context "when there are batchable messages" do
before do
@message2 = MessageFactory.incoming(server, route: route)
@queued_message2 = create(:queued_message, message: @message2)
@message3 = MessageFactory.incoming(server, route: route)
@queued_message3 = create(:queued_message, message: @message3)
end
context "when postal.batch_queued_messages is enabled" do
it "calls the single message process for the initial message and all batchable messages" do
[queued_message, @queued_message2, @queued_message3].each do |msg|
expect(SingleMessageProcessor).to receive(:process).with(msg,
logger: logger,
state: processor.state)
end
processor.process
end
end
context "when postal.batch_queued_messages is disabled" do
before do
allow(Postal::Config.postal).to receive(:batch_queued_messages?) { false }
end
it "does not call the single message process more than once" do
expect(SingleMessageProcessor).to receive(:process).once.with(queued_message,
logger: logger,
state: processor.state)
processor.process
end
end
end
context "when an error occurs while finding batchable messages" do
before do
allow(queued_message).to receive(:batchable_messages) { 1 / 0 }
end
it "unlocks the queued message and raises the error" do
expect { processor.process }.to raise_error(ZeroDivisionError)
expect(queued_message.reload).to_not be_locked
end
end
context "when finished" do
it "notifies the state that processing is complete" do
expect(processor.state).to receive(:finished)
processor.process
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer/outgoing_message_processor_spec.rb | spec/lib/message_dequeuer/outgoing_message_processor_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MessageDequeuer
RSpec.describe OutgoingMessageProcessor do
let(:server) { create(:server) }
let(:state) { State.new }
let(:logger) { TestLogger.new }
let(:domain) { create(:domain, server: server) }
let(:credential) { create(:credential, server: server) }
let(:message) { MessageFactory.outgoing(server, domain: domain, credential: credential) }
let(:queued_message) { create(:queued_message, :locked, message: message) }
subject(:processor) { described_class.new(queued_message, logger: logger, state: state) }
context "when the domain belonging to the message no longer exists" do
let(:message) { MessageFactory.outgoing(server, domain: nil, credential: credential) }
it "logs" do
processor.process
expect(logger).to have_logged(/message has no domain/)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /Message's domain no longer exist/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message has no rcpt to address" do
before do
message.update(rcpt_to: "")
end
it "logs" do
processor.process
expect(logger).to have_logged(/message has no 'to' address/)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /Message doesn't have an RCPT to/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message has a x-postal-tag header" do
let(:message) do
MessageFactory.outgoing(server, domain: domain) do |_msg, mail|
mail["x-postal-tag"] = "example-tag"
end
end
it "logs" do
processor.process
expect(logger).to have_logged(/added tag: example-tag/)
end
it "adds the tag to the message object" do
processor.process
expect(message.reload.tag).to eq("example-tag")
end
end
context "when the credential says to hold the message" do
let(:credential) { create(:credential, hold: true) }
context "when the message was queued manually" do
let(:queued_message) { create(:queued_message, :locked, message: message, manual: true) }
it "does not hold the message" do
processor.process
deliveries = message.deliveries.find { |d| d.status == "Held" }
expect(deliveries).to be_nil
end
end
context "when the message was not queued manually" do
it "logs" do
processor.process
expect(logger).to have_logged(/credential wants us to hold messages/)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /Credential is configured to hold all messages authenticated/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when the rcpt address is on the suppression list" do
before do
server.message_db.suppression_list.add(:recipient, message.rcpt_to, reason: "testing")
end
context "when the message was queued manually" do
let(:queued_message) { create(:queued_message, :locked, message: message, manual: true) }
it "does not hold the message" do
processor.process
deliveries = message.deliveries.find { |d| d.status == "Held" }
expect(deliveries).to be_nil
end
end
context "when the message was not queued manually" do
it "logs" do
processor.process
expect(logger).to have_logged(/recipient is on the suppression list/)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /Recipient \(#{message.rcpt_to}\) is on the suppression list/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when the message content has not been parsed" do
it "parses the content" do
mocked_parser = double("Result")
allow(mocked_parser).to receive(:actioned?).and_return(false)
allow(mocked_parser).to receive(:tracked_links).and_return(0)
allow(mocked_parser).to receive(:tracked_images).and_return(0)
expect(Postal::MessageParser).to receive(:new).with(kind_of(Postal::MessageDB::Message)).and_return(mocked_parser)
processor.process
reloaded_message = message.reload
expect(reloaded_message.parsed).to eq 1
expect(reloaded_message.tracked_links).to eq 0
expect(reloaded_message.tracked_images).to eq 0
end
end
context "when the server has an outbound spam threshold configured" do
let(:server) { create(:server, outbound_spam_threshold: 5.0) }
it "logs" do
processor.process
expect(logger).to have_logged(/inspecting message/)
expect(logger).to have_logged(/message inspected successfully/)
end
it "inspects the message" do
inspection_result = double("Result", spam_score: 1.0, threat: false, threat_message: nil, spam_checks: [])
expect(Postal::MessageInspection).to receive(:scan).and_return(inspection_result)
processor.process
end
context "when the message spam score is higher than the threshold" do
before do
inspection_result = double("Result", spam_score: 6.0, threat: false, threat_message: nil, spam_checks: [])
allow(Postal::MessageInspection).to receive(:scan).and_return(inspection_result)
end
it "logs" do
processor.process
expect(logger).to have_logged(/message is spam/)
end
it "sets the spam boolean on the message" do
processor.process
expect(message.reload.spam).to be true
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /Message is likely spam. Threshold is 5.0 and the message scored 6.0/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when the server does not have a outbound spam threshold configured" do
it "does not inspect the message" do
expect(Postal::MessageInspection).to_not receive(:scan)
processor.process
end
end
context "when the message already has an x-postal-msgid header" do
let(:message) do
MessageFactory.outgoing(server, domain: domain, credential: credential) do |_, mail|
mail["x-postal-msgid"] = "existing-id"
end
end
it "does not another one" do
processor.process
expect(message.reload.headers["x-postal-msgid"]).to eq ["existing-id"]
end
it "does not add dkim headers" do
processor.process
expect(message.reload.headers["dkim-signature"]).to be_nil
end
end
context "when the message does not have a x-postal-msgid header" do
it "adds it" do
processor.process
expect(message.reload.headers["x-postal-msgid"]).to match [match(/[a-zA-Z0-9]{12}/)]
end
it "adds a dkim header" do
processor.process
expect(message.reload.headers["dkim-signature"]).to match [match(/\Av=1; a=rsa-sha256/)]
end
end
context "when the server has exceeded its send limit" do
let(:server) { create(:server, send_limit: 5) }
before do
5.times { server.message_db.live_stats.increment("outgoing") }
end
it "updates the time the limit was exceeded" do
expect { processor.process }.to change { server.reload.send_limit_exceeded_at }.from(nil).to(kind_of(Time))
end
it "logs" do
processor.process
expect(logger).to have_logged(/server send limit has been exceeded/)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /Message held because send limit \(5\) has been reached/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the server is approaching its send limit" do
let(:server) { create(:server, send_limit: 10) }
before do
9.times { server.message_db.live_stats.increment("outgoing") }
end
it "updates the time the limit was being approached" do
expect { processor.process }.to change { server.reload.send_limit_approaching_at }.from(nil).to(kind_of(Time))
end
it "does not set the exceeded time" do
expect { processor.process }.to_not change { server.reload.send_limit_exceeded_at } # rubocop:disable Lint/AmbiguousBlockAssociation
end
end
context "when the server is not exceeded or approaching its limit" do
let(:server) { create(:server, :exceeded_send_limit, send_limit: 10) }
it "clears the approaching and exceeded limits" do
processor.process
server.reload
expect(server.send_limit_approaching_at).to be_nil
expect(server.send_limit_exceeded_at).to be_nil
end
end
context "when the server is in development mode" do
let(:server) { create(:server, mode: "Development") }
context "when the message was queued manually" do
let(:queued_message) { create(:queued_message, :locked, message: message, manual: true) }
it "does not hold the message" do
processor.process
deliveries = message.deliveries.find { |d| d.status == "Held" }
expect(deliveries).to be_nil
end
end
context "when the message was not queued manually" do
it "logs" do
processor.process
expect(logger).to have_logged(/server is in development mode/)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /Server is in development mode/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when there are no other impediments" do
let(:send_result) do
SendResult.new do |r|
r.type = "Sent"
end
end
before do
mocked_sender = double("SMTPSender")
allow(mocked_sender).to receive(:send_message).and_return(send_result)
allow(state).to receive(:sender_for).and_return(mocked_sender)
end
it "increments the live stats" do
expect { processor.process }.to change { server.message_db.live_stats.total(60) }.from(0).to(1)
end
context "when there is an IP address assigned to the queued message" do
let(:ip) { create(:ip_address) }
let(:queued_message) { create(:queued_message, :locked, message: message, ip_address: ip) }
it "gets a sender from the state and sends the message to it" do
mocked_sender = double("SMTPSender")
expect(mocked_sender).to receive(:send_message).with(queued_message.message).and_return(send_result)
expect(state).to receive(:sender_for).with(SMTPSender, message.recipient_domain, ip).and_return(mocked_sender)
processor.process
end
end
context "when there is no IP address assigned to the queued message" do
it "gets a sender from the state and sends the message to it" do
mocked_sender = double("SMTPSender")
expect(mocked_sender).to receive(:send_message).with(queued_message.message).and_return(send_result)
expect(state).to receive(:sender_for).with(SMTPSender, message.recipient_domain, nil).and_return(mocked_sender)
processor.process
end
end
context "when the message hard fails" do
before do
send_result.type = "HardFail"
end
context "when the recipient has got no hard fails in the last 24 hours" do
it "does not add to the suppression list" do
processor.process
expect(server.message_db.suppression_list.all_with_pagination(1)[:total]).to eq 0
end
end
context "when the recipient has more than one hard fail in the last 24 hours" do
before do
2.times do
MessageFactory.outgoing(server, domain: domain, credential: credential) do |msg|
msg.status = "HardFail"
end
end
end
it "logs" do
processor.process
expect(logger).to have_logged(/added #{message.rcpt_to} to suppression list because 2 hard fails in 24 hours/i)
end
it "adds the recipient to the suppression list" do
processor.process
entry = server.message_db.suppression_list.get(:recipient, message.rcpt_to)
expect(entry).to match hash_including(
"address" => message.rcpt_to,
"type" => "recipient",
"reason" => "too many hard fails"
)
end
end
end
context "when the message is sent manually and the recipient is on the suppression list" do
let(:queued_message) { create(:queued_message, :locked, message: message, manual: true) }
before do
server.message_db.suppression_list.add(:recipient, message.rcpt_to, reason: "testing")
end
it "logs" do
processor.process
expect(logger).to have_logged(/removed #{message.rcpt_to} from suppression list/)
end
it "removes them from the suppression list" do
processor.process
expect(server.message_db.suppression_list.get(:recipient, message.rcpt_to)).to be_nil
end
it "adds the details to the delivery details" do
processor.process
delivery = message.deliveries.last
expect(delivery.details).to include("Recipient removed from suppression list")
end
end
it "creates a delivery with the appropriate details" do
send_result.details = "Sent successfully to mx.example.com"
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Sent", details: "Sent successfully to mx.example.com")
end
context "if the message should be retried" do
before do
send_result.type = "SoftFail"
send_result.retry = true
end
it "logs" do
processor.process
expect(logger).to have_logged(/message requeued for trying later/)
end
it "sets the message status to SoftFail" do
processor.process
expect(message.reload.status).to eq "SoftFail"
end
it "updates the retry time on the queued message" do
Timecop.freeze do
retry_time = 5.minutes.from_now.change(usec: 0)
processor.process
expect(queued_message.reload.retry_after).to eq retry_time
end
end
end
context "if the message should not be retried" do
it "logs" do
processor.process
expect(logger).to have_logged(/message processing complete/)
end
it "sets the message status to Sent" do
processor.process
expect(message.reload.status).to eq "Sent"
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when an exception occurrs during processing" do
before do
smtp_sender_mock = double("SMTPSender")
allow(SMTPSender).to receive(:new).and_return(smtp_sender_mock)
allow(smtp_sender_mock).to receive(:start)
allow(smtp_sender_mock).to receive(:send_message) do
1 / 0
end
end
it "logs" do
processor.process
expect(logger).to have_logged(/internal error: ZeroDivisionError/i)
end
it "creates an Error delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Error", details: /internal error/i)
end
it "marks the message for retrying later" do
processor.process
expect(queued_message.reload.retry_after).to be_present
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer/incoming_message_processor_spec.rb | spec/lib/message_dequeuer/incoming_message_processor_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MessageDequeuer
RSpec.describe IncomingMessageProcessor do
let(:server) { create(:server) }
let(:state) { State.new }
let(:logger) { TestLogger.new }
let(:route) { create(:route, server: server) }
let(:message) { MessageFactory.incoming(server, route: route) }
let(:queued_message) { create(:queued_message, :locked, message: message) }
subject(:processor) { described_class.new(queued_message, logger: logger, state: state) }
context "when the message was a bounce but there's no return path for it" do
let(:message) do
MessageFactory.incoming(server) do |msg|
msg.bounce = true
end
end
it "logs" do
processor.process
expect(logger).to have_logged(/no source messages found, hard failing/)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /was a bounce but we couldn't link it with any outgoing message/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message is a bounce for an existing message" do
let(:existing_message) { MessageFactory.outgoing(server) }
let(:message) do
MessageFactory.incoming(server) do |msg, mail|
msg.bounce = true
mail["X-Postal-MsgID"] = existing_message.token
end
end
it "logs" do
processor.process
expect(logger).to have_logged(/message is a bounce/)
end
it "adds the original message as the bounce ID for the received message" do
processor.process
expect(message.reload.bounce_for_id).to eq existing_message.id
end
it "sets the received message status to Processed" do
processor.process
expect(message.reload.status).to eq "Processed"
end
it "creates a Processed delivery on the received message" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Processed", details: /This has been detected as a bounce message for <msg:#{existing_message.id}>/i)
end
it "sets the existing message status to Bounced" do
processor.process
expect(existing_message.reload.status).to eq "Bounced"
end
it "creates a Bounced delivery on the original message" do
processor.process
delivery = existing_message.deliveries.last
expect(delivery).to have_attributes(status: "Bounced", details: /received a bounce message for this e-mail. See <msg:#{message.id}> for/i)
end
it "triggers a MessageBounced webhook event" do
expect(WebhookRequest).to receive(:trigger).with(server, "MessageBounced", {
original_message: kind_of(Hash),
bounce: kind_of(Hash)
})
processor.process
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message is not a bounce" do
it "increments the stats for the server" do
expect { processor.process }.to change { server.message_db.live_stats.total(5) }.by(1)
end
it "inspects the message and adds headers" do
expect { processor.process }.to change { message.reload.inspected }.from(false).to(true)
new_message = message.reload
expect(new_message.headers).to match hash_including(
"x-postal-spam" => ["no"],
"x-postal-spam-threshold" => ["5.0"],
"x-postal-threat" => ["no"]
)
end
it "marks the message as spam if the spam score is higher than the server threshold" do
inspection_result = double("Result", spam_score: server.spam_threshold + 1, threat: false, threat_message: nil, spam_checks: [])
allow(Postal::MessageInspection).to receive(:scan).and_return(inspection_result)
processor.process
expect(message.reload.spam).to be true
end
end
context "when the message has a spam score greater than the server's spam failure threshold" do
before do
inspection_result = double("Result", spam_score: 100, threat: false, threat_message: nil, spam_checks: [])
allow(Postal::MessageInspection).to receive(:scan).and_return(inspection_result)
end
it "logs" do
processor.process
expect(logger).to have_logged(/message has a spam score higher than the server's maxmimum/)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /spam score is higher than the failure threshold for this server/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the server mode is Development and the message was not manually queued" do
before do
server.update!(mode: "Development")
end
after do
server.update!(mode: "Live")
end
it "logs" do
processor.process
expect(logger).to have_logged(/server is in development mode/)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /server is in development mode/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when there is no route for the incoming message" do
let(:route) { nil }
it "logs" do
processor.process
expect(logger).to have_logged(/no route and\/or endpoint available for processing/i)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /does not have a route and\/or endpoint available/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the route's spam mode is Quarantine, the message is spam and not manually queued" do
let(:route) { create(:route, server: server, spam_mode: "Quarantine") }
before do
inspection_result = double("Result", spam_score: server.spam_threshold + 1, threat: false, threat_message: nil, spam_checks: [])
allow(Postal::MessageInspection).to receive(:scan).and_return(inspection_result)
end
it "logs" do
processor.process
expect(logger).to have_logged(/message is spam and route says to quarantine spam message/i)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /message placed into quarantine/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the route's spam mode is Fail, the message is spam and not manually queued" do
let(:route) { create(:route, server: server, spam_mode: "Fail") }
before do
inspection_result = double("Result", spam_score: server.spam_threshold + 1, threat: false, threat_message: nil, spam_checks: [])
allow(Postal::MessageInspection).to receive(:scan).and_return(inspection_result)
end
it "logs" do
processor.process
expect(logger).to have_logged(/message is spam and route says to fail spam message/i)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /message is spam and the route specifies it should be failed/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the route's mode is Accept" do
it "logs" do
processor.process
expect(logger).to have_logged(/route says to accept without endpoint/i)
end
it "sets the message status to Processed" do
processor.process
expect(message.reload.status).to eq "Processed"
end
it "creates a Processed delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Processed", details: /message has been accepted but not sent to any endpoints/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the route's mode is Hold" do
let(:route) { create(:route, server: server, mode: "Hold") }
context "when the message was queued manually" do
let(:queued_message) { create(:queued_message, :locked, server: server, message: message, manual: true) }
it "logs" do
processor.process
expect(logger).to have_logged(/route says to hold and message was queued manually/i)
end
it "sets the message status to Processed" do
processor.process
expect(message.reload.status).to eq "Processed"
end
it "creates a Processed delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Processed", details: /message has been processed/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message was not queued manually" do
let(:queued_message) { create(:queued_message, :locked, server: server, message: message, manual: false) }
it "logs" do
processor.process
expect(logger).to have_logged(/route says to hold, marking as held/i)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /message has been accepted but not sent to any endpoints/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when the route's mode is Bounce" do
let(:route) { create(:route, server: server, mode: "Bounce") }
it "logs" do
processor.process
expect(logger).to have_logged(/route says to bounce/i)
end
it "sends a bounce" do
expect(BounceMessage).to receive(:new).with(server, queued_message.message)
processor.process
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /message has been bounced because/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the route's mode is Reject" do
let(:route) { create(:route, server: server, mode: "Reject") }
it "logs" do
processor.process
expect(logger).to have_logged(/route says to bounce/i)
end
it "sends a bounce" do
expect(BounceMessage).to receive(:new).with(server, queued_message.message)
processor.process
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /message has been bounced because/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the route's endpoint is an HTTP endpoint" do
let(:endpoint) { create(:http_endpoint, server: server) }
let(:route) { create(:route, server: server, mode: "Endpoint", endpoint: endpoint) }
it "gets a sender from the state and sends the message to it" do
http_sender_double = double("HTTPSender")
expect(http_sender_double).to receive(:send_message).with(queued_message.message).and_return(SendResult.new)
expect(state).to receive(:sender_for).with(HTTPSender, endpoint).and_return(http_sender_double)
processor.process
end
end
context "when the route's endpoint is an SMTP endpoint" do
let(:endpoint) { create(:smtp_endpoint, server: server) }
let(:route) { create(:route, server: server, mode: "Endpoint", endpoint: endpoint) }
it "gets a sender from the state and sends the message to it" do
smtp_sender_double = double("SMTPSender")
expect(smtp_sender_double).to receive(:send_message).with(queued_message.message).and_return(SendResult.new)
expect(state).to receive(:sender_for).with(SMTPSender, message.recipient_domain, nil, { servers: [kind_of(SMTPClient::Server)] }).and_return(smtp_sender_double)
processor.process
end
end
context "when the route's endpoint is an Address endpoint" do
let(:endpoint) { create(:address_endpoint, server: server) }
let(:route) { create(:route, server: server, mode: "Endpoint", endpoint: endpoint) }
it "gets a sender from the state and sends the message to it" do
smtp_sender_double = double("SMTPSender")
expect(smtp_sender_double).to receive(:send_message).with(queued_message.message).and_return(SendResult.new)
expect(state).to receive(:sender_for).with(SMTPSender, endpoint.domain, nil, { rcpt_to: endpoint.address }).and_return(smtp_sender_double)
processor.process
end
end
context "when the route's endpoint is an unknown endpoint" do
let(:route) { create(:route, server: server, mode: "Endpoint", endpoint: create(:webhook, server: server)) }
it "logs" do
processor.process
expect(logger).to have_logged(/invalid endpoint for route/i)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /invalid endpoint for route/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message has been sent to a sender" do
let(:endpoint) { create(:smtp_endpoint, server: server) }
let(:route) { create(:route, server: server, mode: "Endpoint", endpoint: endpoint) }
let(:send_result) do
SendResult.new do |result|
result.type = "Sent"
result.details = "Sent successfully"
end
end
before do
smtp_sender_mock = double("SMTPSender")
allow(SMTPSender).to receive(:new).and_return(smtp_sender_mock)
allow(smtp_sender_mock).to receive(:start)
allow(smtp_sender_mock).to receive(:finish)
allow(smtp_sender_mock).to receive(:send_message).and_return(send_result)
end
context "when the sender returns a HardFail and bounces are suppressed" do
before do
send_result.type = "HardFail"
send_result.suppress_bounce = true
end
it "logs" do
processor.process
expect(logger).to have_logged(/suppressing bounce message after hard fail/)
end
it "does not send a bounce" do
allow(BounceMessage).to receive(:new)
processor.process
expect(BounceMessage).to_not have_received(:new)
end
end
context "when the sender returns a HardFail and bounces should be sent" do
before do
send_result.type = "HardFail"
send_result.details = "Failed to send message"
end
it "logs" do
processor.process
expect(logger).to have_logged(/sending a bounce because message hard failed/)
end
it "sends a bounce" do
expect(BounceMessage).to receive(:new).with(server, queued_message.message)
processor.process
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a delivery with the details and a suffix about the bounce message" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /Failed to send message. Sent bounce message to sender \(see message <msg:\d+>\)/i)
end
end
it "creates a delivery with the result from the sender" do
send_result.output = "some output here"
send_result.secure = true
send_result.log_id = "12345"
send_result.time = 2.32
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Sent",
details: "Sent successfully",
output: "some output here",
sent_with_ssl: true,
log_id: "12345",
time: 2.32)
end
context "when the sender wants to retry" do
before do
send_result.type = "SoftFail"
send_result.retry = true
end
it "logs" do
processor.process
expect(logger).to have_logged(/message requeued for trying later, at/i)
end
it "sets the message status to SoftFail" do
processor.process
expect(message.reload.status).to eq "SoftFail"
end
it "updates the queued message with a new retry time" do
Timecop.freeze do
retry_time = 5.minutes.from_now.change(usec: 0)
processor.process
expect(queued_message.reload.retry_after).to eq retry_time
end
end
it "allocates a new IP address to send the message from and updates the queued message" do
expect(queued_message).to receive(:allocate_ip_address)
processor.process
end
it "does not remove the queued message" do
processor.process
expect(queued_message.reload).to be_present
end
end
context "when the sender does not want a retry" do
it "logs" do
processor.process
expect(logger).to have_logged(/message processing completed/i)
end
it "sets the message status to Sent" do
processor.process
expect(message.reload.status).to eq "Sent"
end
it "marks the endpoint as used" do
route.endpoint.update!(last_used_at: nil)
Timecop.freeze do
expect { processor.process }.to change { route.endpoint.reload.last_used_at.to_i }.from(0).to(Time.now.to_i)
end
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
context "when an exception occurrs during processing" do
let(:endpoint) { create(:smtp_endpoint, server: server) }
let(:route) { create(:route, server: server, mode: "Endpoint", endpoint: endpoint) }
before do
smtp_sender_mock = double("SMTPSender")
allow(SMTPSender).to receive(:new).and_return(smtp_sender_mock)
allow(smtp_sender_mock).to receive(:start)
allow(smtp_sender_mock).to receive(:finish)
allow(smtp_sender_mock).to receive(:send_message) do
1 / 0
end
end
it "logs" do
processor.process
expect(logger).to have_logged(/internal error: ZeroDivisionError/i)
end
it "creates an Error delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Error", details: /internal error/i)
end
it "marks the message for retrying later" do
processor.process
expect(queued_message.reload.retry_after).to be_present
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer/base_spec.rb | spec/lib/message_dequeuer/base_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MessageDequeuer
RSpec.describe Base do
describe ".new" do
context "when given state" do
it "uses that state" do
base = described_class.new(nil, logger: nil, state: 1234)
expect(base.state).to eq 1234
end
end
context "when not given state" do
it "creates a new state" do
base = described_class.new(nil, logger: nil)
expect(base.state).to be_a State
end
end
end
describe ".process" do
it "creates a new instances of the class and calls process" do
message = create(:queued_message)
logger = TestLogger.new
mock = double("Base")
expect(mock).to receive(:process).once
expect(described_class).to receive(:new).with(message, logger: logger).and_return(mock)
described_class.process(message, logger: logger)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer/state_spec.rb | spec/lib/message_dequeuer/state_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MessageDequeuer
RSpec.describe State do
subject(:state) { described_class.new }
describe "#send_result" do
it "can be get and set" do
result = instance_double(SendResult)
state.send_result = result
expect(state.send_result).to be result
end
end
describe "#sender_for" do
it "returns a instance of the given sender initialized with the args" do
sender = state.sender_for(HTTPSender, "1234")
expect(sender).to be_a HTTPSender
end
it "returns a cached sender on subsequent calls" do
sender = state.sender_for(HTTPSender, "1234")
expect(state.sender_for(HTTPSender, "1234")).to be sender
end
end
describe "#finished" do
it "calls finish on all cached senders" do
sender1 = state.sender_for(HTTPSender, "1234")
sender2 = state.sender_for(HTTPSender, "4444")
expect(sender1).to receive(:finish)
expect(sender2).to receive(:finish)
state.finished
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/lib/message_dequeuer/single_message_processor_spec.rb | spec/lib/message_dequeuer/single_message_processor_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MessageDequeuer
RSpec.describe SingleMessageProcessor do
let(:server) { create(:server) }
let(:state) { State.new }
let(:logger) { TestLogger.new }
let(:route) { create(:route, server: server) }
let(:message) { MessageFactory.incoming(server, route: route) }
let(:queued_message) { create(:queued_message, :locked, message: message) }
subject(:processor) { described_class.new(queued_message, logger: logger, state: state) }
context "when the server is suspended" do
before do
allow(queued_message.server).to receive(:suspended?).and_return(true)
end
it "logs" do
processor.process
expect(logger).to have_logged(/server is suspended/)
end
it "sets the message status to Held" do
processor.process
expect(message.reload.status).to eq "Held"
end
it "creates a Held delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "Held", details: /server has been suspended/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the number of attempts is more than the maximum" do
let(:queued_message) { create(:queued_message, :locked, message: message, attempts: Postal::Config.postal.default_maximum_delivery_attempts + 1) }
it "logs" do
processor.process
expect(logger).to have_logged(/message has reached maximum number of attempts/)
end
it "sends a bounce to the sender" do
expect(BounceMessage).to receive(:new).with(server, queued_message.message)
processor.process
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /maximum number of delivery attempts.*bounce sent to sender/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message raw data has been removed" do
before do
message.raw_table = nil
message.save
end
it "logs" do
processor.process
expect(logger).to have_logged(/raw message has been removed/)
end
it "sets the message status to HardFail" do
processor.process
expect(message.reload.status).to eq "HardFail"
end
it "creates a HardFail delivery" do
processor.process
delivery = message.deliveries.last
expect(delivery).to have_attributes(status: "HardFail", details: /Raw message has been removed/i)
end
it "removes the queued message" do
processor.process
expect { queued_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the message is incoming" do
it "calls the incoming message processor" do
expect(IncomingMessageProcessor).to receive(:new).with(queued_message,
logger: logger,
state: processor.state)
processor.process
end
it "does not call the outgoing message processor" do
expect(OutgoingMessageProcessor).to_not receive(:process)
processor.process
end
end
context "when the message is outgoing" do
let(:message) { MessageFactory.outgoing(server) }
it "calls the outgoing message processor" do
expect(OutgoingMessageProcessor).to receive(:process).with(queued_message,
logger: logger,
state: processor.state)
processor.process
end
it "does not call the incoming message processor" do
expect(IncomingMessageProcessor).to_not receive(:process)
processor.process
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/apis/legacy_api/messages/message_spec.rb | spec/apis/legacy_api/messages/message_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Legacy Messages API", type: :request do
describe "/api/v1/messages/message" do
context "when no authentication is provided" do
it "returns an error" do
post "/api/v1/messages/message"
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "AccessDenied"
end
end
context "when the credential does not match anything" do
it "returns an error" do
post "/api/v1/messages/message", headers: { "x-server-api-key" => "invalid" }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "InvalidServerAPIKey"
end
end
context "when the credential belongs to a suspended server" do
it "returns an error" do
server = create(:server, :suspended)
credential = create(:credential, server: server)
post "/api/v1/messages/message", headers: { "x-server-api-key" => credential.key }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "ServerSuspended"
end
end
context "when the credential is valid" do
let(:server) { create(:server) }
let(:credential) { create(:credential, server: server) }
context "when no message ID is provided" do
it "returns an error" do
post "/api/v1/messages/message", headers: { "x-server-api-key" => credential.key }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "parameter-error"
expect(parsed_body["data"]["message"]).to match(/`id` parameter is required but is missing/)
end
end
context "when the message ID does not exist" do
it "returns an error" do
post "/api/v1/messages/message",
headers: { "x-server-api-key" => credential.key,
"content-type" => "application/json" },
params: { id: 123 }.to_json
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "MessageNotFound"
end
end
context "when the message ID exists" do
let(:server) { create(:server) }
let(:credential) { create(:credential, server: server) }
let(:message) { MessageFactory.outgoing(server) }
let(:expansions) { [] }
before do
post "/api/v1/messages/message",
headers: { "x-server-api-key" => credential.key,
"content-type" => "application/json" },
params: { id: message.id, _expansions: expansions }.to_json
end
context "when no expansions are requested" do
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token
})
end
end
context "when all expansions are requested" do
let(:expansions) { true }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"status" => { "held" => false,
"hold_expiry" => nil,
"last_delivery_attempt" => nil,
"status" => "Pending" },
"details" => { "bounce" => false,
"bounce_for_id" => 0,
"direction" => "outgoing",
"mail_from" => "test@example.com",
"message_id" => message.message_id,
"rcpt_to" => "john@example.com",
"received_with_ssl" => nil,
"size" => kind_of(String),
"subject" => "An example message",
"tag" => nil,
"timestamp" => kind_of(Float) },
"inspection" => { "inspected" => false,
"spam" => false,
"spam_score" => 0.0,
"threat" => false,
"threat_details" => nil },
"plain_body" => message.plain_body,
"html_body" => message.html_body,
"attachments" => [],
"headers" => message.headers,
"raw_message" => Base64.encode64(message.raw_message),
"activity_entries" => {
"loads" => [],
"clicks" => []
}
})
end
end
context "when the status expansion is requested" do
let(:expansions) { ["status"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"status" => { "held" => false,
"hold_expiry" => nil,
"last_delivery_attempt" => nil,
"status" => "Pending" }
})
end
end
context "when the details expansion is requested" do
let(:expansions) { ["details"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"details" => { "bounce" => false,
"bounce_for_id" => 0,
"direction" => "outgoing",
"mail_from" => "test@example.com",
"message_id" => message.message_id,
"rcpt_to" => "john@example.com",
"received_with_ssl" => nil,
"size" => kind_of(String),
"subject" => "An example message",
"tag" => nil,
"timestamp" => kind_of(Float) }
})
end
end
context "when the details expansion is requested" do
let(:expansions) { ["inspection"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"inspection" => { "inspected" => false,
"spam" => false,
"spam_score" => 0.0,
"threat" => false,
"threat_details" => nil }
})
end
end
context "when the body expansions are requested" do
let(:expansions) { %w[plain_body html_body] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"plain_body" => message.plain_body,
"html_body" => message.html_body
})
end
end
context "when the attachments expansions is requested" do
let(:message) do
MessageFactory.outgoing(server) do |_, mail|
mail.attachments["example.txt"] = "hello world!"
end
end
let(:expansions) { ["attachments"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"attachments" => [
{
"content_type" => "text/plain",
"data" => Base64.encode64("hello world!"),
"filename" => "example.txt",
"hash" => Digest::SHA1.hexdigest("hello world!"),
"size" => 12
},
]
})
end
end
context "when the headers expansions is requested" do
let(:expansions) { ["headers"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"headers" => message.headers
})
end
end
context "when the raw_message expansions is requested" do
let(:expansions) { ["raw_message"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"raw_message" => Base64.encode64(message.raw_message)
})
end
end
context "when the activity_entries expansions is requested" do
let(:message) do
MessageFactory.outgoing(server) do |msg|
msg.create_load(double("request", ip: "1.2.3.4", user_agent: "user agent"))
link = msg.create_link("https://example.com")
link_id = msg.database.select(:links, where: { token: link }).first["id"]
msg.database.insert(:clicks, {
message_id: msg.id,
link_id: link_id,
ip_address: "1.2.3.4",
user_agent: "user agent",
timestamp: Time.now.to_f
})
end
end
let(:expansions) { ["activity_entries"] }
it "returns details about the message" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match({
"id" => message.id,
"token" => message.token,
"activity_entries" => {
"loads" => [{
"ip_address" => "1.2.3.4",
"user_agent" => "user agent",
"timestamp" => match(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z\z/)
}],
"clicks" => [{
"url" => "https://example.com",
"ip_address" => "1.2.3.4",
"user_agent" => "user agent",
"timestamp" => match(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z\z/)
}]
}
})
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/apis/legacy_api/messages/deliveries_spec.rb | spec/apis/legacy_api/messages/deliveries_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Legacy Messages API", type: :request do
describe "/api/v1/messages/deliveries" do
context "when no authentication is provided" do
it "returns an error" do
post "/api/v1/messages/deliveries"
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "AccessDenied"
end
end
context "when the credential does not match anything" do
it "returns an error" do
post "/api/v1/messages/deliveries", headers: { "x-server-api-key" => "invalid" }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "InvalidServerAPIKey"
end
end
context "when the credential belongs to a suspended server" do
it "returns an error" do
server = create(:server, :suspended)
credential = create(:credential, server: server)
post "/api/v1/messages/deliveries", headers: { "x-server-api-key" => credential.key }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "ServerSuspended"
end
end
context "when the credential is valid" do
let(:server) { create(:server) }
let(:credential) { create(:credential, server: server) }
context "when no message ID is provided" do
it "returns an error" do
post "/api/v1/messages/deliveries", headers: { "x-server-api-key" => credential.key }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "parameter-error"
expect(parsed_body["data"]["message"]).to match(/`id` parameter is required but is missing/)
end
end
context "when the message ID does not exist" do
it "returns an error" do
post "/api/v1/messages/deliveries",
headers: { "x-server-api-key" => credential.key,
"content-type" => "application/json" },
params: { id: 123 }.to_json
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "MessageNotFound"
expect(parsed_body["data"]["id"]).to eq 123
end
end
context "when the message ID exists" do
let(:server) { create(:server) }
let(:credential) { create(:credential, server: server) }
let(:message) { MessageFactory.outgoing(server) }
before do
message.create_delivery("SoftFail", details: "no server found",
output: "404",
sent_with_ssl: true,
log_id: "1234",
time: 1.2)
message.create_delivery("Sent", details: "sent successfully",
output: "200",
sent_with_ssl: false,
log_id: "5678",
time: 2.2)
end
before do
post "/api/v1/messages/deliveries",
headers: { "x-server-api-key" => credential.key,
"content-type" => "application/json" },
params: { id: message.id }.to_json
end
it "returns an array of deliveries" do
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]).to match([
{ "id" => kind_of(Integer),
"status" => "SoftFail",
"details" => "no server found",
"output" => "404",
"sent_with_ssl" => true,
"log_id" => "1234",
"time" => 1.2,
"timestamp" => kind_of(Float) },
{ "id" => kind_of(Integer),
"status" => "Sent",
"details" => "sent successfully",
"output" => "200",
"sent_with_ssl" => false,
"log_id" => "5678",
"time" => 2.2,
"timestamp" => kind_of(Float) },
])
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/apis/legacy_api/send/message_spec.rb | spec/apis/legacy_api/send/message_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Legacy Send API", type: :request do
describe "/api/v1/send/message" do
context "when no authentication is provided" do
it "returns an error" do
post "/api/v1/send/message"
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "AccessDenied"
end
end
context "when the credential does not match anything" do
it "returns an error" do
post "/api/v1/send/message", headers: { "x-server-api-key" => "invalid" }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "InvalidServerAPIKey"
end
end
context "when the credential belongs to a suspended server" do
it "returns an error" do
server = create(:server, :suspended)
credential = create(:credential, server: server)
post "/api/v1/send/message", headers: { "x-server-api-key" => credential.key }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "ServerSuspended"
end
end
context "when the credential is valid" do
let(:server) { create(:server) }
let(:credential) { create(:credential, server: server) }
let(:domain) { create(:domain, owner: server) }
context "when parameters are provided in a JSON body" do
let(:default_params) do
{
to: ["test@example.com"],
cc: ["cc@example.com"],
bcc: ["bcc@example.com"],
from: "test@#{domain.name}",
sender: "sender@#{domain.name}",
tag: "test-tag",
reply_to: "reply@example.com",
plain_body: "plain text",
html_body: "<p>html</p>",
attachments: [{ name: "test1.txt", content_type: "text/plain", data: Base64.encode64("hello world 1") },
{ name: "test2.txt", content_type: "text/plain", data: Base64.encode64("hello world 2") },],
headers: { "x-test-header-1" => "111", "x-test-header-2" => "222" },
bounce: false,
subject: "Test"
}
end
let(:params) { default_params }
before do
post "/api/v1/send/message",
headers: { "x-server-api-key" => credential.key,
"content-type" => "application/json" },
params: params.to_json
end
context "when no recipients are provided" do
let(:params) { default_params.merge(to: [], cc: [], bcc: []) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "NoRecipients"
expect(parsed_body["data"]["message"]).to match(/there are no recipients defined to receive this message/i)
end
end
context "when no content is provided" do
let(:params) { default_params.merge(html_body: nil, plain_body: nil) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "NoContent"
expect(parsed_body["data"]["message"]).to match(/there is no content defined for this e-mail/i)
end
end
context "when the number of 'To' recipients exceeds the maximum" do
let(:params) { default_params.merge(to: ["a@a.com"] * 51) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "TooManyToAddresses"
expect(parsed_body["data"]["message"]).to match(/the maximum number of To addresses has been reached/i)
end
end
context "when the number of 'CC' recipients exceeds the maximum" do
let(:params) { default_params.merge(cc: ["a@a.com"] * 51) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "TooManyCCAddresses"
expect(parsed_body["data"]["message"]).to match(/the maximum number of CC addresses has been reached/i)
end
end
context "when the number of 'BCC' recipients exceeds the maximum" do
let(:params) { default_params.merge(bcc: ["a@a.com"] * 51) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "TooManyBCCAddresses"
expect(parsed_body["data"]["message"]).to match(/the maximum number of BCC addresses has been reached/i)
end
end
context "when the 'From' address is missing" do
let(:params) { default_params.merge(from: nil) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "FromAddressMissing"
expect(parsed_body["data"]["message"]).to match(/the from address is missing and is required/i)
end
end
context "when the 'From' address is not authorised" do
let(:params) { default_params.merge(from: "test@another.com") }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "UnauthenticatedFromAddress"
expect(parsed_body["data"]["message"]).to match(/the from address is not authorised to send mail from this server/i)
end
end
context "when an attachment is missing a name" do
let(:params) { default_params.merge(attachments: [{ name: nil, content_type: "text/plain", data: Base64.encode64("hello world 1") }]) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "AttachmentMissingName"
expect(parsed_body["data"]["message"]).to match(/an attachment is missing a name/i)
end
end
context "when an attachment is missing data" do
let(:params) { default_params.merge(attachments: [{ name: "test1.txt", content_type: "text/plain", data: nil }]) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "AttachmentMissingData"
expect(parsed_body["data"]["message"]).to match(/an attachment is missing data/i)
end
end
context "when an attachment entry is not a hash" do
let(:params) { default_params.merge(attachments: [123, "string"]) }
it "continues as if it wasn't there" do
parsed_body = JSON.parse(response.body)
["test@example.com", "cc@example.com", "bcc@example.com"].each do |rcpt_to|
message_id = parsed_body["data"]["messages"][rcpt_to]["id"]
message = server.message(message_id)
expect(message.attachments).to be_empty
end
end
end
context "when given a complete email to send" do
it "returns details of the messages created" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]["messages"]).to match({
"test@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ },
"cc@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ },
"bcc@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ }
})
end
it "adds an appropriate received header" do
parsed_body = JSON.parse(response.body)
message_id = parsed_body["data"]["messages"]["test@example.com"]["id"]
message = server.message(message_id)
expect(message.headers["received"].first).to match(/\Afrom api/)
end
it "creates appropriate message objects" do
parsed_body = JSON.parse(response.body)
["test@example.com", "cc@example.com", "bcc@example.com"].each do |rcpt_to|
message_id = parsed_body["data"]["messages"][rcpt_to]["id"]
message = server.message(message_id)
expect(message).to have_attributes(
server: server,
rcpt_to: rcpt_to,
mail_from: params[:from],
subject: params[:subject],
message_id: kind_of(String),
timestamp: kind_of(Time),
domain_id: domain.id,
credential_id: credential.id,
bounce: false,
tag: params[:tag],
headers: hash_including("x-test-header-1" => ["111"],
"x-test-header-2" => ["222"],
"sender" => [params[:sender]],
"to" => ["test@example.com"],
"cc" => ["cc@example.com"],
"reply-to" => ["reply@example.com"]),
plain_body: params[:plain_body],
html_body: params[:html_body],
attachments: [
have_attributes(content_type: /\Atext\/plain/, filename: "test1.txt", body: have_attributes(to_s: "hello world 1")),
have_attributes(content_type: /\Atext\/plain/, filename: "test2.txt", body: have_attributes(to_s: "hello world 2")),
]
)
end
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/spec/apis/legacy_api/send/raw_spec.rb | spec/apis/legacy_api/send/raw_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Legacy Send API", type: :request do
describe "/api/v1/send/raw" do
context "when no authentication is provided" do
it "returns an error" do
post "/api/v1/send/raw"
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "AccessDenied"
end
end
context "when the credential does not match anything" do
it "returns an error" do
post "/api/v1/send/raw", headers: { "x-server-api-key" => "invalid" }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "InvalidServerAPIKey"
end
end
context "when the credential belongs to a suspended server" do
it "returns an error" do
server = create(:server, :suspended)
credential = create(:credential, server: server)
post "/api/v1/send/raw", headers: { "x-server-api-key" => credential.key }
expect(response.status).to eq 200
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "error"
expect(parsed_body["data"]["code"]).to eq "ServerSuspended"
end
end
context "when the credential is valid" do
let(:server) { create(:server) }
let(:credential) { create(:credential, server: server) }
let(:domain) { create(:domain, owner: server) }
let(:data) do
mail = Mail.new
mail.to = "test1@example.com"
mail.from = "test@#{domain.name}"
mail.subject = "test"
mail.text_part = Mail::Part.new
mail.text_part.body = "plain text"
mail.html_part = Mail::Part.new
mail.html_part.content_type = "text/html; charset=UTF-8"
mail.html_part.body = "<p>html</p>"
mail
end
let(:default_params) do
{
mail_from: "test@#{domain.name}",
rcpt_to: ["test1@example.com", "test2@example.com"],
data: Base64.encode64(data.to_s),
bounce: false
}
end
let(:content_type) { "application/json" }
let(:params) { default_params }
before do
post "/api/v1/send/raw",
headers: { "x-server-api-key" => credential.key,
"content-type" => content_type },
params: content_type == "application/json" ? params.to_json : params
end
context "when rcpt_to is not provided" do
let(:params) { default_params.except(:rcpt_to) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "parameter-error"
expect(parsed_body["data"]["message"]).to match(/`rcpt_to` parameter is required but is missing/i)
end
end
context "when mail_from is not provided" do
let(:params) { default_params.except(:mail_from) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "parameter-error"
expect(parsed_body["data"]["message"]).to match(/`mail_from` parameter is required but is missing/i)
end
end
context "when data is not provided" do
let(:params) { default_params.except(:data) }
it "returns an error" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "parameter-error"
expect(parsed_body["data"]["message"]).to match(/`data` parameter is required but is missing/i)
end
end
context "when no recipients are provided" do
let(:params) { default_params.merge(rcpt_to: []) }
it "returns success but with no messages" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["status"]).to eq "success"
expect(parsed_body["data"]["messages"]).to eq({})
expect(parsed_body["data"]["message_id"]).to be nil
end
end
context "when a valid email is provided" do
it "returns details of the messages created" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["data"]["message_id"]).to be_a String
expect(parsed_body["data"]["messages"]).to be_a Hash
expect(parsed_body["data"]["messages"]).to match({
"test1@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ },
"test2@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ }
})
end
it "creates appropriate message objects" do
parsed_body = JSON.parse(response.body)
["test1@example.com", "test2@example.com"].each do |rcpt_to|
message_id = parsed_body["data"]["messages"][rcpt_to]["id"]
message = server.message(message_id)
expect(message).to have_attributes(
server: server,
rcpt_to: rcpt_to,
mail_from: "test@#{domain.name}",
subject: "test",
message_id: kind_of(String),
timestamp: kind_of(Time),
domain_id: domain.id,
credential_id: credential.id,
bounce: false,
headers: hash_including("to" => ["test1@example.com"]),
plain_body: "plain text",
html_body: "<p>html</p>",
attachments: [],
received_with_ssl: true,
scope: "outgoing",
raw_message: data.to_s
)
end
end
context "when params are provided as a param" do
let(:content_type) { nil }
let(:params) { { params: default_params.to_json } }
it "returns details of the messages created" do
parsed_body = JSON.parse(response.body)
expect(parsed_body["data"]["message_id"]).to be_a String
expect(parsed_body["data"]["messages"]).to be_a Hash
expect(parsed_body["data"]["messages"]).to match({
"test1@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ },
"test2@example.com" => { "id" => kind_of(Integer), "token" => /\A[a-zA-Z0-9]{16}\z/ }
})
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/send_html_email.rb | script/send_html_email.rb | # frozen_string_literal: true
# This script will automatically send an HTML email to the
# SMTP server given.
require "mail"
require "net/smtp"
from = ARGV[0]
to = ARGV[1]
if from.nil? || to.nil?
puts "Usage: ruby send-html-email.rb <from> <to>"
exit 1
end
mail = Mail.new
mail.to = to
mail.from = from
mail.subject = "A test email from #{Time.now}"
mail["X-Postal-Tag"] = "send-html-email-script"
mail.text_part = Mail::Part.new do
body <<~BODY
Hello there.
This is an example. It doesn't do all that much.
Some other characters: őúéáűí
There is a link here through... https://postalserver.io/test-plain-text-link?foo=bar&baz=qux
BODY
end
mail.html_part = Mail::Part.new do
content_type "text/html; charset=UTF-8"
body <<~BODY
<p>Hello there</p>
<p>This is an example email. It doesn't do all that much.</p>
<p>Some other characters: őúéáűí</p>
<p>There is a <a href='https://postalserver.io/test-plain-text-link?foo=bar&baz=qux'>link here</a> though...</p>
BODY
end
c = OpenSSL::SSL::SSLContext.new
c.verify_mode = OpenSSL::SSL::VERIFY_NONE
smtp = Net::SMTP.new("127.0.0.1", 2525)
smtp.enable_starttls(c)
smtp.start("localhost")
smtp.send_message mail.to_s, mail.from.first, mail.to.first
smtp.finish
puts "Sent"
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/default_dkim_record.rb | script/default_dkim_record.rb | # frozen_string_literal: true
ENV["SILENCE_POSTAL_CONFIG_LOCATION_MESSAGE"] = "true"
require File.expand_path("../lib/postal/config", __dir__)
puts Postal.rp_dkim_dns_record
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/version.rb | script/version.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
require File.expand_path("../lib/postal/config", __dir__)
puts Postal.version
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/queue_size.rb | script/queue_size.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
require_relative "../lib/postal/config"
require "mysql2"
client = Mysql2::Client.new(
host: Postal::Config.main_db.host,
username: Postal::Config.main_db.username,
password: Postal::Config.main_db.password,
port: Postal::Config.main_db.port,
database: Postal::Config.main_db.database
)
result = client.query("SELECT COUNT(id) as size FROM `queued_messages` WHERE retry_after IS NULL OR " \
"retry_after <= ADDTIME(UTC_TIMESTAMP(), '30') AND locked_at IS NULL")
puts result.to_a.first["size"]
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/test_app_smtp.rb | script/test_app_smtp.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
trap("INT") do
puts
exit
end
if ARGV[0].nil? || ARGV[0] !~ /@/
puts "usage: postal test-app-smtp [email address]"
exit 1
end
require_relative "../config/environment"
begin
Timeout.timeout(10) do
AppMailer.test_message(ARGV[0]).deliver
end
puts "\e[32mMessage has been sent successfully.\e[0m"
rescue Timeout::Error
puts "Sending timed out"
rescue StandardError => e
puts "\e[31mMessage was not delivered successfully to SMTP server.\e[0m"
puts "Error: #{e.class} (#{e.message})"
puts
puts " SMTP Host: #{Postal::Config.smtp.host}"
puts " SMTP Port: #{Postal::Config.smtp.port}"
puts " SMTP Username: #{Postal::Config.smtp.username}"
puts " SMTP Password: #{Postal::Config.smtp.password}"
puts
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/insert-bounce.rb | script/insert-bounce.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
# This script will insert a message into your database that looks like a bounce
# for a message that you specify.
# usage: insert-bounce.rb [serverid] [messageid]
if ARGV[0].nil? || ARGV[1].nil?
puts "usage: #{__FILE__} [server-id] [message-id]"
exit 1
end
require_relative "../config/environment"
server = Server.find(ARGV[0])
puts "Got server #{server.name}"
template = File.read(Rails.root.join("resource/postfix-bounce.msg"))
if ARGV[1].to_s =~ /\A(\d+)\z/
message = server.message_db.message(ARGV[1].to_i)
puts "Got message #{message.id} with token #{message.token}"
template.gsub!("{{MSGID}}", message.token)
else
template.gsub!("{{MSGID}}", ARGV[1].to_s)
end
message = server.message_db.new_message
message.scope = "incoming"
message.rcpt_to = "#{server.token}@#{Postal::Config.dns.return_path_domain}"
message.mail_from = "MAILER-DAEMON@smtp.infra.atech.io"
message.raw_message = template
message.bounce = true
message.save
puts "Added message with id #{message.id}"
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/make_user.rb | script/make_user.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
trap("INT") do
puts
exit
end
require_relative "../config/environment"
UserCreator.start do |u|
u.admin = true
u.email_verified_at = Time.now
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/worker.rb | script/worker.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
$stdout.sync = true
$stderr.sync = true
require_relative "../config/environment"
HealthServer.start(
name: "worker",
default_port: Postal::Config.worker.default_health_server_port,
default_bind_address: Postal::Config.worker.default_health_server_bind_address
)
Worker::Process.new.run
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/smtp_server.rb | script/smtp_server.rb | # frozen_string_literal: true
$stdout.sync = true
$stderr.sync = true
require_relative "../config/environment"
HealthServer.start(
name: "smtp-server",
default_port: Postal::Config.smtp_server.default_health_server_port,
default_bind_address: Postal::Config.smtp_server.default_health_server_bind_address
)
SMTPServer::Server.new(debug: true).run
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/script/generate_tls_certificate.rb | script/generate_tls_certificate.rb | # frozen_string_literal: true
require File.expand_path("../lib/postal/config", __dir__)
require "openssl"
key_path = Postal::Config.smtp_server.tls_private_key_path
cert_path = Postal::Config.smtp_server.tls_certificate_path
unless File.exist?(key_path)
key = OpenSSL::PKey::RSA.new(2048).to_s
File.write(key_path, key)
puts "Created new private key for encrypting SMTP connections at #{key_path}"
end
unless File.exist?(cert_path)
cert = OpenSSL::X509::Certificate.new
cert.subject = cert.issuer = OpenSSL::X509::Name.parse("/C=GB/O=Test/OU=Test/CN=Test")
cert.not_before = Time.now
cert.not_after = Time.now + (365 * 24 * 60 * 60)
cert.public_key = SMTPServer::Server.tls_private_key.public_key
cert.serial = 0x0
cert.version = 2
cert.sign SMTPServer::Server.tls_private_key, OpenSSL::Digest.new("SHA256")
File.write(cert_path, cert.to_pem)
puts "Created new self signed certificate for encrypting SMTP connections at #{cert_path}"
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/migration_waiter.rb | lib/migration_waiter.rb | # frozen_string_literal: true
# This initializer will wait for all pending migrations to be applied before
# continuing to start the application. This is useful when running the application
# in a cluster where migrations are run in a separate job which runs at the same
# time as the other processes.
class MigrationWaiter
ATTEMPTS = Postal::Config.migration_waiter.attempts
SLEEP_TIME = Postal::Config.migration_waiter.sleep_time
class << self
def wait
attempts_remaining = ATTEMPTS
loop do
pending_migrations = ActiveRecord::Base.connection.migration_context.open.pending_migrations.size
if pending_migrations.zero?
Postal.logger.info "no pending migrations, continuing"
return
end
attempts_remaining -= 1
if attempts_remaining.zero?
Postal.logger.info "#{pending_migrations} migration(s) are still pending after #{ATTEMPTS} attempts, exiting"
Process.exit(1)
else
Postal.logger.info "waiting for #{pending_migrations} migration(s) to be applied (#{attempts_remaining} remaining)"
sleep SLEEP_TIME
end
end
end
def wait_if_appropriate
# Don't wait if not configured
return unless Postal::Config.migration_waiter.enabled?
# Don't wait in the console, rake tasks or rails commands
return if console? || rake_task? || rails_command?
wait
end
def console?
Rails.const_defined?("Console")
end
def rake_task?
Rake.application.top_level_tasks.any?
end
def rails_command?
caller.any? { |c| c =~ /rails\/commands/ }
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.