Event Notifications Reference Guide
    • Dark
      Light

    Event Notifications Reference Guide

    • Dark
      Light

    Article Summary

    This article provides information about Backblaze B2 Cloud Storage Event Notifications such as rule structure, event types, and webhooks.

    To create and use Event Notifications, click here.

    You can also use the Backblaze B2 API to manage Event Notifications:

    Note
    This feature is currently in private preview. For information about enabling this feature, see Automate Your Data Workflows With Backblaze B2 Event Notifications.

    Event Notification Rules

    Event notification rules instruct Backblaze B2 to perform actions when certain events happen in the system. You can set up rules to trigger a webhook. An HTTP POST request is sent to a URL that you configure whenever certain events occur, such as an object upload or an object being created in a destination bucket during replication.

    A bucket can have up to 25 Event Notifications rules. Event Notification rules are not supported for object download events or for replication of objects from a source bucket. All webhook invocations use the POST HTTP method and must use HTTPS protocol. You must allow incoming requests to your webhook endpoint from the IP address blocks that are listed in the Backblaze IP Address List.

    Event Notification Rule Structure

    Each Event Notification rule can have the following parameters.

    eventTypes
    required
    Events to which the rule applies. The value is an array of strings. For more information, see Event Types below.
    isEnabled
    required
    Specifies whether the Event Notification rule is enabled. Possible values are true or false. By default, the value is set to true (enabled).
    name
    required
    A name for identifying the rule. Names must be unique within a bucket. Names can consist only of uppercase and lowercase English letters, numbers, and hyphens (-). A name must be between six and 63 characters long. Names that start with b2- are reserved for Backblaze use.

    Examples of valid names are myObjectUploadRule and mycompany-webhooks.
    objectNamePrefix
    required
    Specifies the objects in the bucket in which the Event Notification rule applies. Objects with names that begin with objectNamePrefix are subject to the rule. An empty string prefix "" means that the rule applies to all of the objects in the bucket. The objectNamePrefix must not overlap with another objectNamePrefix for the same event type. For example, an Event Notification rule with the prefix "images/pets/" is not allowed if there is an existing rule of the same event type with "images/."
    customHeaders
    required
    A set of name/value pairs for custom headers that are added to the webhook invocation. For example, this can be a bearer token. There can be at most 10 custom header name/value pairs. The total number of URL-encoded bytes must not exceed 2,048. Each custom header name/value pair has three extra bytes added to the total, accounting for the :, \r, and \n characters. You may not use a custom header name that begins with X-Bz-.
    targetType
    required
    Configuration type of the Event Notification rule. Currently, the only supported targetType is "webhook."
    url
    required
    The URL that identifies where the webhook resides. The URL must include the protocol, which must be HTTPS. The URL must not point to a Backblaze hostname or IP address.
    hmacSha256SigningSecret
    optional
    This attribute specifies a 32-character secret that is used to sign the webhook invocation payload using the HMAC SHA-256 algorithm. This alphanumeric string can include characters from 0-9 and A-Z, both uppercase and lowercase. The signing secret is encrypted at rest on Backblaze servers. The signature in the X-Bz-Event-Notification-Signature HTTP header of each Event Notification message is computed from hmacSha256SigningSecret, and it can be used to verify that the webhook originated from Backblaze. If this attribute is not set, then the webhook will not be signed.
    isSuspended
    optional
    This attribute specifies whether the Event Notification rule is suspended. The value can be either true or false. By default, the value is false, meaning that the rule is not suspended. Backblaze may take action to suspend an Event Notification rule as necessary, based on operational policies. If Backblaze takes such action, the suspensionReason includes a brief description about why the rule was suspended. In such cases, the rule cannot be used until it is deleted and re-added (with appropriate updates), or if Backblaze resumes the rule. If you attempt to set this attribute yourself, it will be ignored.
    suspensionReason
    optional
    This attribute gives a brief description about why a rule was suspended. If present, this is a string. If you attempt to set this attribute yourself, it will be ignored. See the isSuspended attribute for more details.

    Event Types

    Backblaze B2 currently supports the following event types for Event Notifications. New event types may be added in the future, so ensure that your code can handle the potential addition of new event types.

    b2:ObjectCreated:UploadA new object that is uploaded to Backblaze B2 that is not copied or replicated. This does not include multipart objects.
    b2:ObjectCreated:MultipartUploadA multipart object that was completed in Backblaze B2 that was not replicated.
    b2:ObjectCreated:CopyA copied object in Backblaze B2.
    b2:ObjectCreated:ReplicaAn object that was replicated in Backblaze B2. This does not include multipart objects. This is the replicated object, and not the source object.
    b2:ObjectCreated:MultipartReplicaA multipart object that was replicated in Backblaze B2. This is the replicated object, and not the source object.
    b2:ObjectDeleted:DeleteAn object that was deleted by user action, such as with an API call or by using the Backblaze web UI.
    b2:ObjectDeleted:LifecycleRuleAn object that was deleted by a Lifecycle Rule.
    b2:HideMarkerCreated:HideA hide marker that was created by user action, such as with an API call.
    b2:HideMarkerCreated:LifecycleRuleA hide marker that was created by a Lifecycle Rule.

    Event types support the wildcard * only in the final component. For example, b2:ObjectCreated:* corresponds to the following event types:

    • b2:ObjectCreated:Upload
    • b2:ObjectCreated:MultipartUpload
    • b2:ObjectCreated:Copy
    • b2:ObjectCreated:Replica
    • b2:ObjectCreated:MultipartReplica


    The wildcard also matches any new event types within the same category that you may add in the future.

    An Event Notification rule must not specify any event types that overlap. For example, if both b2:ObjectCreated:Upload and b2:ObjectCreated:* are event types in the same Event Notification rule, it constitutes an error.

    The following example shows a request structure for an Event Notification rule using b2_set_bucket_notification_rules:

    {
      "bucketId": "aea8c5bc362ae55070130333",
      "eventNotificationRules": [
        {
          "eventTypes": [
            "b2:ObjectCreated:Upload",
            "b2:ObjectCreated:MultipartUpload"
          ],
          "isEnabled": true,
          "name": "mySampleRule1",
          "objectNamePrefix": "",
          "targetConfiguration": {
            "customHeaders": [
              {
                "name": "X-My-Custom-Header-1",
                "value": "myCustomHeaderVal1"
              },
              {
                "name": "X-My-Custom-Header-2",
                "value": "myCustomHeaderVal2"
              }
            ],
            "hmacSha256SigningSecret": "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0",        
            "targetType": "webhook",
            "url": "https://www.example.com/sampleurl"
          },
        }
      ]
    }

    The following example shows a response structure from an Event Notification rule:

    {
      "bucketId": "aea8c5bc362ae55070130333",
      "eventNotificationRules": [
        {
          "eventTypes": [
            "b2:ObjectCreated:Upload",
            "b2:ObjectCreated:MultipartUpload"
          ],
          "isEnabled": true,
          "isSuspended": false,
          "name": "mySampleRule1",
          "objectNamePrefix": "",
          "suspensionReason": "",
          "targetConfiguration": {
            "customHeaders": [
              {
                "name": "X-My-Custom-Header-1",
                "value": "myCustomHeaderVal1"
              },
              {
                "name": "X-My-Custom-Header-2",
                "value": "myCustomHeaderVal2"
              }
            ],
            "hmacSha256SigningSecret": "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0",
            "targetType": "webhook",
            "url": "https://www.example.com/sampleurl"
          },
        }
      ]
    }

    Event Type Categories

    An event type category is the event type without the final component. For example, the category for the event type b2:ObjectCreated:Copy is b2:ObjectCreated. The three event type categories are:

    • b2:ObjectCreated
    • b2:ObjectDeleted
    • b2:HideMarkerCreated

    You cannot use event types from different categories in the same Event Notification rule. So, you could not use both the event types b2:ObjectCreated:Copy and b2:HideMarkerCreated:Hide in the same rule. However, you can make a rule that uses event types from the same category. For example, you could use both of the event types b2:ObjectCreated:Copy and b2:ObjectCreated:Replica in the same rule.

    Webhooks

    When an event that matches an Event Notification rule occurs within a bucket, Backblaze B2 sends a webhook (an HTTP POST request with a JSON-encoded payload) to the endpoint URL that you specify in the rule.

    Backblaze B2 sets a five-second timeout on the webhook request. Your code should defer any substantial processing until after sending a 200 response to reply within the time limit. Backblaze B2 attempts to send each webhook request once at most, and it does not perform retries.

    Note
    In the public release version of the Event Notifications feature, Backblaze B2 will retry the request if your endpoint does not return a 200 response within the time limit.

    If the rule has an hmacSha256SigningSecret, each webhook invocation includes an X-Bz-Event-Notification-Signature HTTP header. The value of this header is the lowercase hex-encoded HMAC SHA-256 signature of the request payload, signed using the hmacSha256SigningSecret from the Event Notification rule. You can use the header and value to ensure that the webhook invocation is coming from Backblaze. The signature value is prepended by the version number. 

    Here is an example of a signature value: v1=2c86b8e1f15f41f805f3331f3cf4eb20875be8887ab734b2cdccfa2350e5e231.

    Additionally, any custom HTTP headers that were defined in the Event Notification rules are included in the webhook requests.

    The following example shows a webhook HTTP request (with long strings shortened for readability):

    POST /sampleurl HTTP/1.1
    Host: www.example.com
    Content-Length: 468
    X-Bz-Event-Notification-Signature: v1=2c86b8e1f15f41f8...
    X-My-Custom-Header-1: myCustomHeaderVal1
    X-My-Custom-Header-2: myCustomHeaderVal2
    User-Agent: B2/EventNotifications
    Content-Type: application/json; charset=UTF-8
    
    {
      "events": [ 
        {
          "accountId": "e85c6a500333",
          "bucketId": "aea8c5bc362ae55070130333",
          "bucketName": "mySampleBucket",
          "eventTimestamp": 1684793309123,
          "eventType": "b2:ObjectCreated:Upload",
          "eventVersion": 1,
          "matchedRuleName": "mySampleRule1",
          "objectName": "objectName.txt",
          "objectSize": 10495842,
          "objectVersionId": "4_zaea8c5bc362a..."
        }
      ]
    }

    The following metadata fields are in the JSON payload.

    accountIdThe unique identifier of the account that owns the bucket where the object resides.
    bucketIdThe unique identifier of the bucket where the object resides. The Event Notification rule was configured on this bucket.
    bucketNameThe name of the bucket where the object resides. The Event Notification rule was configured on this bucket.
    eventTimestampThe UTC time when this event was generated. It is a Base-10 number of milliseconds since midnight, January 1, 1970 UTC. This fits in a 64-bit integer, such as the type "long" in the Java programming language.
    eventTypeThe event type of the Event Notification rule that corresponds to the event. This field is defined in the Event Notification rule configuration.
    eventVersionA numeric value indicating the version of the Event Notification payload. This field is defined for compatibility reasons in case it changes in the future.
    matchedRuleNameThe name of the Event Notification rule that corresponds to the event. This field is defined in the Event Notification rule configuration.
    objectNameThe name of the object that corresponds to the event.
    objectSizeThe size of the object in bytes. The objectSize is non-null on deletes. The objectSize is 0 for hide markers, similar to the response for list file versions.
    objectVersionIdThe unique identifier for the version of the object that corresponds to the event.

    Verifying the Webhook Request Signature

    If you provide an hmacSha256SigningSecret, then the webhook request includes an X-Bz-Event-Notification-Signature HTTP header that contains the HMAC SHA-256 signature of the request payload. The signature header value comprises the signature version, always v1, followed by an equals sign =, followed by the lowercase hex-encoded signature value. You must provide an hmacSha256SigningSecret to get a signature.

    Here is an example of the HTTP header, with the signature value truncated for readability. The actual signature value contains 64 lowercase hex characters, encoding the 256-bit message digest.

    X-Bz-Event-Notification-Signature: v1=2c86b8e1f15f41f8...

    To verify the signature, create an HMAC SHA-256 digest using the hmacSha256SigningSecret from the Event Notification rule as the key, with the request payload as the data. The resulting hex-encoded HMAC digest value must match the signature in the header. If it matches, your code may perform additional message validation—such as parsing the Event Notification from the JSON-encoded request body—before responding to the request with a 200 OK HTTP response. Your code may then continue to process the Event Notification according to your needs. If the calculated digest value does not match the request signature, you should respond to the request with a 401 Unauthorized HTTP response and cease processing the request.

    Note

    Test events are currently signed with a dummy key. You should not attempt to verify the signature on a test event.

    The following code is an example of how you might verify the webhook request signature in JavaScript. If you intend to check the signature, you should first make sure that you have set the hmacSha256SigningSecret in the Event Notification rule. Otherwise, the signature will be missing and the code will exit prematurely.

    import { createHmac } from 'node:crypto';
    
    // Is the signature header present?
    const signature = req.headers['x-bz-event-notification-signature'];
    if (!signature) {
      res.status(401).send('Missing signature header');
      return;
    }
    
    // Does the signature have the correct form?
    const pair = signature.split('=');
    if (!pair || pair.length !== 2) {
      res.status(401).send('Invalid signature format');
      return;
    }
    
    // Is the signature version correct?
    const version = pair[0];
    if (version !== 'v1') {
      res.status(401).send('Invalid signature version');
      return;
    }
    
    // Note - at present (4/15/24), test events need special handling
    // * Test event requests are signed with a dummy key
    if (event.body.eventType === 'b2:TestEvent') {
      // Don't bother validating signature on test events, since we know it will not match
      console.log('Skipping signature verification for test event')
    } else {
      const receivedSig = pair[1];
      // req.body must contain the raw, unparsed body
      const calculatedSig = createHmac('sha256', signingSecret)
        .update(req.body)
        .digest('hex');
      if (receivedSig !== calculatedSig) {
        res.status(401).send('Invalid signature');
        return;
      }
    }
    
    // Parse the event notification payload from the request body
    let payload
    try {
      payload = JSON.parse(req.body);
    } catch (e) {
      res.status(400).send('Bad request');
      return;
    }
    
    // Respond with success before any further processing, 
    // since B2 needs the response within 5 seconds.
    res.status(200).send('OK');
    
    // Continue processing

    Application Key Capabilities

    New application key capabilities have been added to support the Event Notifications feature:

    readBucketNotificationsReads the Event Notification rules for a bucket.

    This capability is used in the following API: b2_get_bucket_notification_rules
    writeBucketNotificationsWrites Event Notification rule information for a bucket.

    This capability is used in the following API: b2_set_bucket_notification_rules

    For more information, see Application Keys and Application Key Capabilities.


    Was this article helpful?