Class: OpenAI::Resources::Webhooks

Inherits:
Object
  • Object
show all
Defined in:
lib/openai/resources/webhooks.rb

Instance Method Summary collapse

Constructor Details

#initialize(client:) ⇒ Webhooks

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Webhooks.

Parameters:



119
120
121
# File 'lib/openai/resources/webhooks.rb', line 119

def initialize(client:)
  @client = client
end

Instance Method Details

#unwrap(payload, headers = {}, webhook_secret = @client.webhook_secret || ENV["OPENAI_WEBHOOK_SECRET"]) ⇒ OpenAI::Models::Webhooks::BatchCancelledWebhookEvent, ...

Validates that the given payload was sent by OpenAI and parses the payload.



18
19
20
21
22
23
24
25
26
27
# File 'lib/openai/resources/webhooks.rb', line 18

def unwrap(
  payload,
  headers = {},
  webhook_secret = @client.webhook_secret || ENV["OPENAI_WEBHOOK_SECRET"]
)
  verify_signature(payload, headers, webhook_secret)

  parsed = JSON.parse(payload, symbolize_names: true)
  OpenAI::Internal::Type::Converter.coerce(OpenAI::Models::Webhooks::UnwrapWebhookEvent, parsed)
end

#verify_signature(payload, headers, webhook_secret = @client.webhook_secret || ENV["OPENAI_WEBHOOK_SECRET"], tolerance = 300) ⇒ void

Validates whether or not the webhook payload was sent by OpenAI.

Parameters:

  • payload (String)

    The webhook payload as a string

  • headers (Hash)

    The webhook headers

  • webhook_secret (String, nil) (defaults to: @client.webhook_secret || ENV["OPENAI_WEBHOOK_SECRET"])

    The webhook secret (optional, will use client webhook secret or ENV["OPENAI_WEBHOOK_SECRET"] if not provided)

  • tolerance (Integer) (defaults to: 300)

    Maximum age of the webhook in seconds (default: 300 = 5 minutes)

Raises:

  • (ArgumentError)

    if the signature is invalid



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/openai/resources/webhooks.rb', line 37

def verify_signature(
  payload,
  headers,
  webhook_secret = @client.webhook_secret || ENV["OPENAI_WEBHOOK_SECRET"],
  tolerance = 300
)
  if webhook_secret.nil?
    raise ArgumentError,
          "The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, " \
          "or passed to this function"
  end

  # Extract required headers
  signature_header = headers["webhook-signature"] || headers[:webhook_signature]
  timestamp_header = headers["webhook-timestamp"] || headers[:webhook_timestamp]
  webhook_id = headers["webhook-id"] || headers[:webhook_id]

  if signature_header.nil?
    raise ArgumentError, "Missing required webhook-signature header"
  end

  if timestamp_header.nil?
    raise ArgumentError, "Missing required webhook-timestamp header"
  end

  if webhook_id.nil?
    raise ArgumentError, "Missing required webhook-id header"
  end

  # Validate timestamp to prevent replay attacks
  begin
    timestamp_seconds = timestamp_header.to_i
  rescue ArgumentError
    raise ArgumentError, "Invalid webhook timestamp format"
  end

  now = Time.now.to_i

  if now - timestamp_seconds > tolerance
    raise OpenAI::Errors::InvalidWebhookSignatureError, "Webhook timestamp is too old"
  end

  if timestamp_seconds > now + tolerance
    raise OpenAI::Errors::InvalidWebhookSignatureError, "Webhook timestamp is too new"
  end

  # Extract signatures from v1,<base64> format
  # The signature header can have multiple values, separated by spaces.
  # Each value is in the format v1,<base64>. We should accept if any match.
  signatures = signature_header.split.map do |part|
    if part.start_with?("v1,")
      part[3..]
    else
      part
    end
  end

  # Decode the secret if it starts with whsec_
  decoded_secret = if webhook_secret.start_with?("whsec_")
    Base64.decode64(webhook_secret[6..])
  else
    webhook_secret
  end

  # Create the signed payload: {webhook_id}.{timestamp}.{payload}
  signed_payload = "#{webhook_id}.#{timestamp_header}.#{payload}"

  # Compute HMAC-SHA256 signature
  expected_signature = Base64.encode64(
    OpenSSL::HMAC.digest("sha256", decoded_secret, signed_payload)
  ).strip

  # Accept if any signature matches using timing-safe comparison
  return if signatures.any? { |signature| OpenSSL.secure_compare(expected_signature, signature) }

  raise OpenAI::Errors::InvalidWebhookSignatureError,
        "The given webhook signature does not match the expected signature"
end