@@ -79,6 +79,9 @@ const (
|
||||
SCIMEventEntityType uint16 = 53
|
||||
TokenEntityType uint16 = 54
|
||||
SCIMBridgeEntityType uint16 = 55
|
||||
WebhookConfigurationEntityType uint16 = 56
|
||||
WebhookEventEntityType uint16 = 57
|
||||
WebhookCallEntityType uint16 = 58
|
||||
)
|
||||
|
||||
func NewEntityFromID(id gid.GID) (any, bool) {
|
||||
@@ -191,6 +194,12 @@ func NewEntityFromID(id gid.GID) (any, bool) {
|
||||
return &Token{ID: id}, true
|
||||
case SCIMBridgeEntityType:
|
||||
return &SCIMBridge{ID: id}, true
|
||||
case WebhookConfigurationEntityType:
|
||||
return &WebhookConfiguration{ID: id}, true
|
||||
case WebhookEventEntityType:
|
||||
return &WebhookEvent{ID: id}, true
|
||||
case WebhookCallEntityType:
|
||||
return &WebhookCall{ID: id}, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
|
||||
52
pkg/coredata/migrations/20260210T135740Z.sql
Normal file
52
pkg/coredata/migrations/20260210T135740Z.sql
Normal file
@@ -0,0 +1,52 @@
|
||||
CREATE TYPE webhook_event_type AS ENUM (
|
||||
'meeting:created',
|
||||
'meeting:updated',
|
||||
'meeting:deleted',
|
||||
'vendor:created',
|
||||
'vendor:updated',
|
||||
'vendor:deleted'
|
||||
);
|
||||
|
||||
CREATE TABLE webhook_configurations (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id TEXT NOT NULL,
|
||||
organization_id TEXT NOT NULL REFERENCES organizations(id) ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
endpoint_url TEXT NOT NULL,
|
||||
selected_events webhook_event_type[] NOT NULL,
|
||||
encrypted_signing_secret BYTEA NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
|
||||
CREATE TYPE webhook_event_status AS ENUM (
|
||||
'PENDING',
|
||||
'PROCESSING',
|
||||
'DELIVERED'
|
||||
);
|
||||
|
||||
CREATE TABLE webhook_events (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id TEXT NOT NULL,
|
||||
organization_id TEXT NOT NULL REFERENCES organizations(id) ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
event_type webhook_event_type NOT NULL,
|
||||
status webhook_event_status NOT NULL,
|
||||
data JSONB NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
processed_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE TYPE webhook_call_status AS ENUM (
|
||||
'SUCCEEDED',
|
||||
'FAILED'
|
||||
);
|
||||
|
||||
CREATE TABLE webhook_calls (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id TEXT NOT NULL,
|
||||
webhook_event_id TEXT NOT NULL REFERENCES webhook_events(id) ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
webhook_configuration_id TEXT NOT NULL REFERENCES webhook_configurations(id) ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
endpoint_url TEXT NOT NULL,
|
||||
status webhook_call_status NOT NULL,
|
||||
response JSONB,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
87
pkg/coredata/webhook_call.go
Normal file
87
pkg/coredata/webhook_call.go
Normal file
@@ -0,0 +1,87 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
)
|
||||
|
||||
type (
|
||||
WebhookCall struct {
|
||||
ID gid.GID `db:"id"`
|
||||
WebhookEventID gid.GID `db:"webhook_event_id"`
|
||||
WebhookConfigurationID gid.GID `db:"webhook_configuration_id"`
|
||||
EndpointURL string `db:"endpoint_url"`
|
||||
Status WebhookCallStatus `db:"status"`
|
||||
Response json.RawMessage `db:"response"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
}
|
||||
|
||||
WebhookCalls []*WebhookCall
|
||||
)
|
||||
|
||||
func (w *WebhookCall) Insert(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
) error {
|
||||
q := `
|
||||
INSERT INTO webhook_calls (
|
||||
id,
|
||||
tenant_id,
|
||||
webhook_event_id,
|
||||
webhook_configuration_id,
|
||||
endpoint_url,
|
||||
status,
|
||||
response,
|
||||
created_at
|
||||
)
|
||||
VALUES (
|
||||
@id,
|
||||
@tenant_id,
|
||||
@webhook_event_id,
|
||||
@webhook_configuration_id,
|
||||
@endpoint_url,
|
||||
@status,
|
||||
@response,
|
||||
@created_at
|
||||
)
|
||||
`
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"id": w.ID,
|
||||
"tenant_id": scope.GetTenantID(),
|
||||
"webhook_event_id": w.WebhookEventID,
|
||||
"webhook_configuration_id": w.WebhookConfigurationID,
|
||||
"endpoint_url": w.EndpointURL,
|
||||
"status": w.Status,
|
||||
"response": w.Response,
|
||||
"created_at": w.CreatedAt,
|
||||
}
|
||||
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot insert webhook call: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
64
pkg/coredata/webhook_call_status.go
Normal file
64
pkg/coredata/webhook_call_status.go
Normal file
@@ -0,0 +1,64 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type WebhookCallStatus string
|
||||
|
||||
const (
|
||||
WebhookCallStatusSucceeded WebhookCallStatus = "SUCCEEDED"
|
||||
WebhookCallStatusFailed WebhookCallStatus = "FAILED"
|
||||
)
|
||||
|
||||
func (s WebhookCallStatus) String() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
func (s WebhookCallStatus) IsValid() bool {
|
||||
switch s {
|
||||
case WebhookCallStatusSucceeded, WebhookCallStatusFailed:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s WebhookCallStatus) MarshalText() ([]byte, error) {
|
||||
return []byte(s.String()), nil
|
||||
}
|
||||
|
||||
func (s *WebhookCallStatus) UnmarshalText(text []byte) error {
|
||||
*s = WebhookCallStatus(text)
|
||||
if !s.IsValid() {
|
||||
return fmt.Errorf("%s is not a valid WebhookCallStatus", string(text))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *WebhookCallStatus) Scan(value any) error {
|
||||
str, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unsupported type for WebhookCallStatus: %T", value)
|
||||
}
|
||||
|
||||
return s.UnmarshalText([]byte(str))
|
||||
}
|
||||
|
||||
func (s WebhookCallStatus) Value() (driver.Value, error) {
|
||||
return s.String(), nil
|
||||
}
|
||||
411
pkg/coredata/webhook_configuration.go
Normal file
411
pkg/coredata/webhook_configuration.go
Normal file
@@ -0,0 +1,411 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/crypto/cipher"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
)
|
||||
|
||||
type (
|
||||
WebhookConfiguration struct {
|
||||
ID gid.GID `db:"id"`
|
||||
OrganizationID gid.GID `db:"organization_id"`
|
||||
EndpointURL string `db:"endpoint_url"`
|
||||
SelectedEvents WebhookEventTypes `db:"selected_events"`
|
||||
EncryptedSigningSecret []byte `db:"encrypted_signing_secret"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at"`
|
||||
}
|
||||
|
||||
WebhookConfigurations []*WebhookConfiguration
|
||||
)
|
||||
|
||||
func (w *WebhookConfiguration) GenerateSigningSecret(encryptionKey cipher.EncryptionKey) (string, error) {
|
||||
secret := make([]byte, 32)
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
return "", fmt.Errorf("cannot generate signing secret: %w", err)
|
||||
}
|
||||
|
||||
signingSecret := "whsec_" + hex.EncodeToString(secret)
|
||||
|
||||
encrypted, err := cipher.Encrypt([]byte(signingSecret), encryptionKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot encrypt signing secret: %w", err)
|
||||
}
|
||||
|
||||
w.EncryptedSigningSecret = encrypted
|
||||
|
||||
return signingSecret, nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfiguration) DecryptSigningSecret(encryptionKey cipher.EncryptionKey) (string, error) {
|
||||
if len(w.EncryptedSigningSecret) == 0 {
|
||||
return "", fmt.Errorf("no encrypted signing secret")
|
||||
}
|
||||
|
||||
plaintext, err := cipher.Decrypt(w.EncryptedSigningSecret, encryptionKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot decrypt signing secret: %w", err)
|
||||
}
|
||||
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
func (w WebhookConfiguration) CursorKey(orderBy WebhookConfigurationOrderField) page.CursorKey {
|
||||
switch orderBy {
|
||||
case WebhookConfigurationOrderFieldCreatedAt:
|
||||
return page.NewCursorKey(w.ID, w.CreatedAt)
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("unsupported order by: %s", orderBy))
|
||||
}
|
||||
|
||||
// AuthorizationAttributes returns the authorization attributes for policy evaluation.
|
||||
func (w *WebhookConfiguration) AuthorizationAttributes(ctx context.Context, conn pg.Conn) (map[string]string, error) {
|
||||
q := `SELECT organization_id FROM webhook_configurations WHERE id = $1 LIMIT 1;`
|
||||
|
||||
var organizationID gid.GID
|
||||
if err := conn.QueryRow(ctx, q, w.ID).Scan(&organizationID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrResourceNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("cannot query webhook configuration authorization attributes: %w", err)
|
||||
}
|
||||
|
||||
return map[string]string{"organization_id": organizationID.String()}, nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfiguration) LoadByID(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
webhookConfigurationID gid.GID,
|
||||
) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
endpoint_url,
|
||||
selected_events,
|
||||
encrypted_signing_secret,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM
|
||||
webhook_configurations
|
||||
WHERE
|
||||
%s
|
||||
AND id = @webhook_configuration_id
|
||||
LIMIT 1;
|
||||
`
|
||||
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{"webhook_configuration_id": webhookConfigurationID}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
rows, err := conn.Query(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot query webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
wc, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[WebhookConfiguration])
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot collect webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
*w = wc
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfigurations) LoadByOrganizationID(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
organizationID gid.GID,
|
||||
cursor *page.Cursor[WebhookConfigurationOrderField],
|
||||
) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
endpoint_url,
|
||||
selected_events,
|
||||
encrypted_signing_secret,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM
|
||||
webhook_configurations
|
||||
WHERE
|
||||
%s
|
||||
AND organization_id = @organization_id
|
||||
AND %s
|
||||
`
|
||||
q = fmt.Sprintf(q, scope.SQLFragment(), cursor.SQLFragment())
|
||||
|
||||
args := pgx.NamedArgs{"organization_id": organizationID}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
maps.Copy(args, cursor.SQLArguments())
|
||||
|
||||
rows, err := conn.Query(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot query webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
configurations, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[WebhookConfiguration])
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot collect webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
*w = configurations
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfigurations) CountByOrganizationID(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
organizationID gid.GID,
|
||||
) (int, error) {
|
||||
q := `
|
||||
SELECT
|
||||
COUNT(*)
|
||||
FROM
|
||||
webhook_configurations
|
||||
WHERE
|
||||
%s
|
||||
AND organization_id = @organization_id
|
||||
`
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"organization_id": organizationID,
|
||||
}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
row := conn.QueryRow(ctx, q, args)
|
||||
var count int
|
||||
if err := row.Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("cannot count webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfigurations) ExistsByOrganizationIDAndEventType(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
organizationID gid.GID,
|
||||
eventType WebhookEventType,
|
||||
) (bool, error) {
|
||||
q := `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM webhook_configurations
|
||||
WHERE %s
|
||||
AND organization_id = @organization_id
|
||||
AND @event_type = ANY(selected_events)
|
||||
)
|
||||
`
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"organization_id": organizationID,
|
||||
"event_type": eventType.String(),
|
||||
}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
var exists bool
|
||||
if err := conn.QueryRow(ctx, q, args).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("cannot check webhook configuration existence: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfiguration) Insert(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
) error {
|
||||
q := `
|
||||
INSERT INTO
|
||||
webhook_configurations (
|
||||
tenant_id,
|
||||
id,
|
||||
organization_id,
|
||||
endpoint_url,
|
||||
selected_events,
|
||||
encrypted_signing_secret,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
@tenant_id,
|
||||
@webhook_configuration_id,
|
||||
@organization_id,
|
||||
@endpoint_url,
|
||||
@selected_events,
|
||||
@encrypted_signing_secret,
|
||||
@created_at,
|
||||
@updated_at
|
||||
);
|
||||
`
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"tenant_id": scope.GetTenantID(),
|
||||
"webhook_configuration_id": w.ID,
|
||||
"organization_id": w.OrganizationID,
|
||||
"endpoint_url": w.EndpointURL,
|
||||
"selected_events": w.SelectedEvents,
|
||||
"encrypted_signing_secret": w.EncryptedSigningSecret,
|
||||
"created_at": w.CreatedAt,
|
||||
"updated_at": w.UpdatedAt,
|
||||
}
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot insert webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfiguration) Update(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
) error {
|
||||
q := `
|
||||
UPDATE webhook_configurations
|
||||
SET
|
||||
endpoint_url = @endpoint_url,
|
||||
selected_events = @selected_events,
|
||||
updated_at = @updated_at
|
||||
WHERE %s
|
||||
AND id = @webhook_configuration_id
|
||||
`
|
||||
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"webhook_configuration_id": w.ID,
|
||||
"endpoint_url": w.EndpointURL,
|
||||
"selected_events": w.SelectedEvents,
|
||||
"updated_at": w.UpdatedAt,
|
||||
}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot update webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfigurations) LoadMatchingByOrganizationIDAndEventType(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
organizationID gid.GID,
|
||||
eventType WebhookEventType,
|
||||
) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
endpoint_url,
|
||||
selected_events,
|
||||
encrypted_signing_secret,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM
|
||||
webhook_configurations
|
||||
WHERE
|
||||
%s
|
||||
AND organization_id = @organization_id
|
||||
AND @event_type = ANY(selected_events)
|
||||
`
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"organization_id": organizationID,
|
||||
"event_type": eventType.String(),
|
||||
}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
rows, err := conn.Query(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot query matching webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
configurations, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[WebhookConfiguration])
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot collect matching webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
*w = configurations
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookConfiguration) Delete(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
) error {
|
||||
q := `
|
||||
DELETE FROM webhook_configurations
|
||||
WHERE %s
|
||||
AND id = @webhook_configuration_id
|
||||
`
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"webhook_configuration_id": w.ID,
|
||||
}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot delete webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
55
pkg/coredata/webhook_configuration_order_field.go
Normal file
55
pkg/coredata/webhook_configuration_order_field.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type (
|
||||
WebhookConfigurationOrderField string
|
||||
)
|
||||
|
||||
const (
|
||||
WebhookConfigurationOrderFieldCreatedAt WebhookConfigurationOrderField = "CREATED_AT"
|
||||
)
|
||||
|
||||
func (p WebhookConfigurationOrderField) Column() string {
|
||||
return string(p)
|
||||
}
|
||||
|
||||
func (p WebhookConfigurationOrderField) String() string {
|
||||
return string(p)
|
||||
}
|
||||
|
||||
func (p WebhookConfigurationOrderField) IsValid() bool {
|
||||
switch p {
|
||||
case WebhookConfigurationOrderFieldCreatedAt:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p WebhookConfigurationOrderField) MarshalText() ([]byte, error) {
|
||||
return []byte(p.String()), nil
|
||||
}
|
||||
|
||||
func (p *WebhookConfigurationOrderField) UnmarshalText(text []byte) error {
|
||||
*p = WebhookConfigurationOrderField(text)
|
||||
if !p.IsValid() {
|
||||
return fmt.Errorf("%s is not a valid WebhookConfigurationOrderField", string(text))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
160
pkg/coredata/webhook_event.go
Normal file
160
pkg/coredata/webhook_event.go
Normal file
@@ -0,0 +1,160 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
)
|
||||
|
||||
type (
|
||||
WebhookEvent struct {
|
||||
ID gid.GID `db:"id"`
|
||||
OrganizationID gid.GID `db:"organization_id"`
|
||||
EventType WebhookEventType `db:"event_type"`
|
||||
Status WebhookEventStatus `db:"status"`
|
||||
Data json.RawMessage `db:"data"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
ProcessedAt *time.Time `db:"processed_at"`
|
||||
}
|
||||
|
||||
WebhookEvents []*WebhookEvent
|
||||
|
||||
)
|
||||
|
||||
func (w *WebhookEvent) Insert(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
) error {
|
||||
q := `
|
||||
INSERT INTO webhook_events (
|
||||
id,
|
||||
tenant_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
status,
|
||||
data,
|
||||
created_at
|
||||
)
|
||||
VALUES (
|
||||
@id,
|
||||
@tenant_id,
|
||||
@organization_id,
|
||||
@event_type,
|
||||
@status,
|
||||
@data,
|
||||
@created_at
|
||||
)
|
||||
`
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"id": w.ID,
|
||||
"tenant_id": scope.GetTenantID(),
|
||||
"organization_id": w.OrganizationID,
|
||||
"event_type": w.EventType,
|
||||
"status": w.Status,
|
||||
"data": w.Data,
|
||||
"created_at": w.CreatedAt,
|
||||
}
|
||||
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookEvent) LoadNextPendingForUpdate(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
) error {
|
||||
q := `
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
event_type,
|
||||
status,
|
||||
data,
|
||||
created_at,
|
||||
processed_at
|
||||
FROM webhook_events
|
||||
WHERE status = 'PENDING'
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`
|
||||
|
||||
rows, err := conn.Query(ctx, q)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot query pending webhook events: %w", err)
|
||||
}
|
||||
|
||||
event, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[WebhookEvent])
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot collect webhook event: %w", err)
|
||||
}
|
||||
|
||||
*w = event
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookEvent) UpdateStatus(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope Scoper,
|
||||
) error {
|
||||
q := `
|
||||
UPDATE webhook_events
|
||||
SET
|
||||
status = @status,
|
||||
processed_at = @processed_at
|
||||
WHERE %s
|
||||
AND id = @id
|
||||
`
|
||||
|
||||
q = fmt.Sprintf(q, scope.SQLFragment())
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"id": w.ID,
|
||||
"status": w.Status.String(),
|
||||
"processed_at": w.ProcessedAt,
|
||||
}
|
||||
maps.Copy(args, scope.SQLArguments())
|
||||
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot update webhook event: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
65
pkg/coredata/webhook_event_status.go
Normal file
65
pkg/coredata/webhook_event_status.go
Normal file
@@ -0,0 +1,65 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type WebhookEventStatus string
|
||||
|
||||
const (
|
||||
WebhookEventStatusPending WebhookEventStatus = "PENDING"
|
||||
WebhookEventStatusProcessing WebhookEventStatus = "PROCESSING"
|
||||
WebhookEventStatusDelivered WebhookEventStatus = "DELIVERED"
|
||||
)
|
||||
|
||||
func (s WebhookEventStatus) String() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
func (s WebhookEventStatus) IsValid() bool {
|
||||
switch s {
|
||||
case WebhookEventStatusPending, WebhookEventStatusProcessing, WebhookEventStatusDelivered:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s WebhookEventStatus) MarshalText() ([]byte, error) {
|
||||
return []byte(s.String()), nil
|
||||
}
|
||||
|
||||
func (s *WebhookEventStatus) UnmarshalText(text []byte) error {
|
||||
*s = WebhookEventStatus(text)
|
||||
if !s.IsValid() {
|
||||
return fmt.Errorf("%s is not a valid WebhookEventStatus", string(text))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *WebhookEventStatus) Scan(value any) error {
|
||||
str, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unsupported type for WebhookEventStatus: %T", value)
|
||||
}
|
||||
|
||||
return s.UnmarshalText([]byte(str))
|
||||
}
|
||||
|
||||
func (s WebhookEventStatus) Value() (driver.Value, error) {
|
||||
return s.String(), nil
|
||||
}
|
||||
133
pkg/coredata/webhook_event_type.go
Normal file
133
pkg/coredata/webhook_event_type.go
Normal file
@@ -0,0 +1,133 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package coredata
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type WebhookEventType string
|
||||
|
||||
const (
|
||||
WebhookEventTypeMeetingCreated WebhookEventType = "meeting:created"
|
||||
WebhookEventTypeMeetingUpdated WebhookEventType = "meeting:updated"
|
||||
WebhookEventTypeMeetingDeleted WebhookEventType = "meeting:deleted"
|
||||
WebhookEventTypeVendorCreated WebhookEventType = "vendor:created"
|
||||
WebhookEventTypeVendorUpdated WebhookEventType = "vendor:updated"
|
||||
WebhookEventTypeVendorDeleted WebhookEventType = "vendor:deleted"
|
||||
)
|
||||
|
||||
func (w WebhookEventType) String() string {
|
||||
return string(w)
|
||||
}
|
||||
|
||||
func (w WebhookEventType) IsValid() bool {
|
||||
switch w {
|
||||
case WebhookEventTypeMeetingCreated, WebhookEventTypeMeetingUpdated, WebhookEventTypeMeetingDeleted,
|
||||
WebhookEventTypeVendorCreated, WebhookEventTypeVendorUpdated, WebhookEventTypeVendorDeleted:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (w WebhookEventType) MarshalText() ([]byte, error) {
|
||||
return []byte(w.String()), nil
|
||||
}
|
||||
|
||||
func (w *WebhookEventType) UnmarshalText(text []byte) error {
|
||||
*w = WebhookEventType(text)
|
||||
if !w.IsValid() {
|
||||
return fmt.Errorf("%s is not a valid WebhookEventType", string(text))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WebhookEventType) Scan(value any) error {
|
||||
var s string
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
s = v
|
||||
case []byte:
|
||||
s = string(v)
|
||||
default:
|
||||
return fmt.Errorf("unsupported type for WebhookEventType: %T", value)
|
||||
}
|
||||
|
||||
return w.UnmarshalText([]byte(s))
|
||||
}
|
||||
|
||||
func (w WebhookEventType) Value() (driver.Value, error) {
|
||||
return w.String(), nil
|
||||
}
|
||||
|
||||
type WebhookEventTypes []WebhookEventType
|
||||
|
||||
func (s *WebhookEventTypes) Scan(value any) error {
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return s.scanFromString(v)
|
||||
case []byte:
|
||||
return s.scanFromString(string(v))
|
||||
default:
|
||||
return fmt.Errorf("unsupported type for WebhookEventTypes: %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WebhookEventTypes) scanFromString(str string) error {
|
||||
str = strings.TrimSpace(str)
|
||||
if str == "{}" || str == "" {
|
||||
*s = []WebhookEventType{}
|
||||
return nil
|
||||
}
|
||||
|
||||
if strings.HasPrefix(str, "{") && strings.HasSuffix(str, "}") {
|
||||
str = str[1 : len(str)-1]
|
||||
}
|
||||
|
||||
parts := strings.Split(str, ",")
|
||||
result := make([]WebhookEventType, len(parts))
|
||||
|
||||
for i, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
|
||||
if strings.HasPrefix(part, `"`) && strings.HasSuffix(part, `"`) {
|
||||
part = part[1 : len(part)-1]
|
||||
}
|
||||
|
||||
var et WebhookEventType
|
||||
if err := et.Scan(part); err != nil {
|
||||
return fmt.Errorf("invalid webhook event type in array: %s", part)
|
||||
}
|
||||
result[i] = et
|
||||
}
|
||||
|
||||
*s = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s WebhookEventTypes) Value() (driver.Value, error) {
|
||||
if len(s) == 0 {
|
||||
return "{}", nil
|
||||
}
|
||||
|
||||
values := make([]string, len(s))
|
||||
for i, et := range s {
|
||||
values[i] = et.String()
|
||||
}
|
||||
|
||||
return "{" + strings.Join(values, ",") + "}", nil
|
||||
}
|
||||
@@ -316,4 +316,11 @@ const (
|
||||
ActionApplicabilityStatementCreate = "core:applicability-statement:create"
|
||||
ActionApplicabilityStatementUpdate = "core:applicability-statement:update"
|
||||
ActionApplicabilityStatementDelete = "core:applicability-statement:delete"
|
||||
|
||||
// WebhookConfiguration actions
|
||||
ActionWebhookConfigurationList = "core:webhook-configuration:list"
|
||||
ActionWebhookConfigurationGet = "core:webhook-configuration:get"
|
||||
ActionWebhookConfigurationCreate = "core:webhook-configuration:create"
|
||||
ActionWebhookConfigurationUpdate = "core:webhook-configuration:update"
|
||||
ActionWebhookConfigurationDelete = "core:webhook-configuration:delete"
|
||||
)
|
||||
|
||||
@@ -23,7 +23,9 @@ import (
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
"go.probo.inc/probo/pkg/server/api/console/v1/types"
|
||||
"go.probo.inc/probo/pkg/validator"
|
||||
"go.probo.inc/probo/pkg/webhook"
|
||||
)
|
||||
|
||||
type MeetingService struct {
|
||||
@@ -207,6 +209,10 @@ func (s MeetingService) Create(
|
||||
}
|
||||
}
|
||||
|
||||
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, organization.ID, coredata.WebhookEventTypeMeetingCreated, types.NewMeeting(meeting)); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
@@ -283,6 +289,10 @@ func (s MeetingService) Update(
|
||||
}
|
||||
}
|
||||
|
||||
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, meeting.OrganizationID, coredata.WebhookEventTypeMeetingUpdated, types.NewMeeting(meeting)); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
@@ -307,6 +317,10 @@ func (s MeetingService) Delete(
|
||||
return fmt.Errorf("cannot load meeting: %w", err)
|
||||
}
|
||||
|
||||
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, meeting.OrganizationID, coredata.WebhookEventTypeMeetingDeleted, types.NewMeeting(meeting)); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
if err := meeting.Delete(ctx, conn, s.svc.scope); err != nil {
|
||||
return fmt.Errorf("cannot delete meeting: %w", err)
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ var ViewerPolicy = policy.NewPolicy(
|
||||
ActionRightsRequestGet, ActionRightsRequestList,
|
||||
ActionStateOfApplicabilityGet, ActionStateOfApplicabilityList,
|
||||
ActionApplicabilityStatementGet, ActionApplicabilityStatementList,
|
||||
ActionWebhookConfigurationGet, ActionWebhookConfigurationList,
|
||||
).WithSID("entity-read-access").When(organizationCondition),
|
||||
|
||||
policy.Allow(
|
||||
|
||||
@@ -92,6 +92,7 @@ type (
|
||||
Data *DatumService
|
||||
Audits *AuditService
|
||||
Meetings *MeetingService
|
||||
WebhookConfigurations *WebhookConfigurationService
|
||||
Reports *ReportService
|
||||
TrustCenters *TrustCenterService
|
||||
TrustCenterAccesses *TrustCenterAccessService
|
||||
@@ -213,6 +214,7 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
||||
tenantService.Data = &DatumService{svc: tenantService}
|
||||
tenantService.Audits = &AuditService{svc: tenantService}
|
||||
tenantService.Meetings = &MeetingService{svc: tenantService}
|
||||
tenantService.WebhookConfigurations = &WebhookConfigurationService{svc: tenantService}
|
||||
tenantService.Reports = &ReportService{svc: tenantService}
|
||||
tenantService.TrustCenters = &TrustCenterService{svc: tenantService}
|
||||
tenantService.TrustCenterAccesses = &TrustCenterAccessService{svc: tenantService}
|
||||
|
||||
@@ -23,7 +23,9 @@ import (
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
"go.probo.inc/probo/pkg/server/api/console/v1/types"
|
||||
"go.probo.inc/probo/pkg/validator"
|
||||
"go.probo.inc/probo/pkg/webhook"
|
||||
)
|
||||
|
||||
type (
|
||||
@@ -392,6 +394,10 @@ func (s VendorService) Update(
|
||||
return fmt.Errorf("cannot update vendor: %w", err)
|
||||
}
|
||||
|
||||
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, vendor.OrganizationID, coredata.WebhookEventTypeVendorUpdated, types.NewVendor(vendor)); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
@@ -427,10 +433,19 @@ func (s VendorService) Delete(
|
||||
ctx context.Context,
|
||||
vendorID gid.GID,
|
||||
) error {
|
||||
vendor := coredata.Vendor{ID: vendorID}
|
||||
return s.svc.pg.WithConn(
|
||||
vendor := &coredata.Vendor{}
|
||||
|
||||
return s.svc.pg.WithTx(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := vendor.LoadByID(ctx, conn, s.svc.scope, vendorID); err != nil {
|
||||
return fmt.Errorf("cannot load vendor: %w", err)
|
||||
}
|
||||
|
||||
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, vendor.OrganizationID, coredata.WebhookEventTypeVendorDeleted, types.NewVendor(vendor)); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return vendor.Delete(ctx, conn, s.svc.scope)
|
||||
},
|
||||
)
|
||||
@@ -504,6 +519,10 @@ func (s VendorService) Create(
|
||||
return fmt.Errorf("cannot insert vendor: %w", err)
|
||||
}
|
||||
|
||||
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, organization.ID, coredata.WebhookEventTypeVendorCreated, types.NewVendor(vendor)); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
290
pkg/probo/webhook_configuration_service.go
Normal file
290
pkg/probo/webhook_configuration_service.go
Normal file
@@ -0,0 +1,290 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package probo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
"go.probo.inc/probo/pkg/validator"
|
||||
)
|
||||
|
||||
type WebhookConfigurationService struct {
|
||||
svc *TenantService
|
||||
}
|
||||
|
||||
type (
|
||||
CreateWebhookConfigurationRequest struct {
|
||||
OrganizationID gid.GID
|
||||
EndpointURL string
|
||||
SelectedEvents []coredata.WebhookEventType
|
||||
}
|
||||
|
||||
UpdateWebhookConfigurationRequest struct {
|
||||
WebhookConfigurationID gid.GID
|
||||
EndpointURL *string
|
||||
SelectedEvents []coredata.WebhookEventType
|
||||
}
|
||||
)
|
||||
|
||||
func (r *CreateWebhookConfigurationRequest) Validate() error {
|
||||
v := validator.New()
|
||||
|
||||
v.Check(r.OrganizationID, "organization_id", validator.Required(), validator.GID(coredata.OrganizationEntityType))
|
||||
v.Check(r.EndpointURL, "endpoint_url", validator.Required(), validator.URL())
|
||||
|
||||
return v.Error()
|
||||
}
|
||||
|
||||
func (r *UpdateWebhookConfigurationRequest) Validate() error {
|
||||
v := validator.New()
|
||||
|
||||
v.Check(r.WebhookConfigurationID, "webhook_configuration_id", validator.Required(), validator.GID(coredata.WebhookConfigurationEntityType))
|
||||
v.Check(r.EndpointURL, "endpoint_url", validator.NotEmpty(), validator.URL())
|
||||
|
||||
return v.Error()
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) ListForOrganizationID(
|
||||
ctx context.Context,
|
||||
organizationID gid.GID,
|
||||
cursor *page.Cursor[coredata.WebhookConfigurationOrderField],
|
||||
) (*page.Page[*coredata.WebhookConfiguration, coredata.WebhookConfigurationOrderField], error) {
|
||||
var configurations coredata.WebhookConfigurations
|
||||
organization := &coredata.Organization{}
|
||||
|
||||
err := s.svc.pg.WithConn(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := organization.LoadByID(ctx, conn, s.svc.scope, organizationID); err != nil {
|
||||
return fmt.Errorf("cannot load organization: %w", err)
|
||||
}
|
||||
|
||||
err := configurations.LoadByOrganizationID(
|
||||
ctx,
|
||||
conn,
|
||||
s.svc.scope,
|
||||
organization.ID,
|
||||
cursor,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot load webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return page.NewPage(configurations, cursor), nil
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) CountForOrganizationID(
|
||||
ctx context.Context,
|
||||
organizationID gid.GID,
|
||||
) (int, error) {
|
||||
var count int
|
||||
|
||||
err := s.svc.pg.WithConn(
|
||||
ctx,
|
||||
func(conn pg.Conn) (err error) {
|
||||
configurations := &coredata.WebhookConfigurations{}
|
||||
count, err = configurations.CountByOrganizationID(ctx, conn, s.svc.scope, organizationID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot count webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) Get(
|
||||
ctx context.Context,
|
||||
webhookConfigurationID gid.GID,
|
||||
) (*coredata.WebhookConfiguration, error) {
|
||||
wc := &coredata.WebhookConfiguration{}
|
||||
|
||||
err := s.svc.pg.WithConn(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := wc.LoadByID(ctx, conn, s.svc.scope, webhookConfigurationID); err != nil {
|
||||
return fmt.Errorf("cannot load webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return wc, nil
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) Create(
|
||||
ctx context.Context,
|
||||
req CreateWebhookConfigurationRequest,
|
||||
) (*coredata.WebhookConfiguration, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var wc *coredata.WebhookConfiguration
|
||||
organization := &coredata.Organization{}
|
||||
|
||||
err := s.svc.pg.WithTx(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := organization.LoadByID(ctx, conn, s.svc.scope, req.OrganizationID); err != nil {
|
||||
return fmt.Errorf("cannot load organization: %w", err)
|
||||
}
|
||||
|
||||
wc = &coredata.WebhookConfiguration{
|
||||
ID: gid.New(organization.ID.TenantID(), coredata.WebhookConfigurationEntityType),
|
||||
OrganizationID: organization.ID,
|
||||
EndpointURL: req.EndpointURL,
|
||||
SelectedEvents: req.SelectedEvents,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if _, err := wc.GenerateSigningSecret(s.svc.encryptionKey); err != nil {
|
||||
return fmt.Errorf("cannot generate signing secret: %w", err)
|
||||
}
|
||||
|
||||
if err := wc.Insert(ctx, conn, s.svc.scope); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return wc, nil
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) Update(
|
||||
ctx context.Context,
|
||||
req UpdateWebhookConfigurationRequest,
|
||||
) (*coredata.WebhookConfiguration, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wc := &coredata.WebhookConfiguration{}
|
||||
|
||||
err := s.svc.pg.WithTx(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := wc.LoadByID(ctx, conn, s.svc.scope, req.WebhookConfigurationID); err != nil {
|
||||
return fmt.Errorf("cannot load webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
if req.EndpointURL != nil {
|
||||
wc.EndpointURL = *req.EndpointURL
|
||||
}
|
||||
if req.SelectedEvents != nil {
|
||||
wc.SelectedEvents = req.SelectedEvents
|
||||
}
|
||||
|
||||
wc.UpdatedAt = time.Now()
|
||||
|
||||
if err := wc.Update(ctx, conn, s.svc.scope); err != nil {
|
||||
return fmt.Errorf("cannot update webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return wc, nil
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) GetSigningSecret(
|
||||
ctx context.Context,
|
||||
webhookConfigurationID gid.GID,
|
||||
) (string, error) {
|
||||
wc := &coredata.WebhookConfiguration{}
|
||||
|
||||
err := s.svc.pg.WithConn(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := wc.LoadByID(ctx, conn, s.svc.scope, webhookConfigurationID); err != nil {
|
||||
return fmt.Errorf("cannot load webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return wc.DecryptSigningSecret(s.svc.encryptionKey)
|
||||
}
|
||||
|
||||
func (s WebhookConfigurationService) Delete(
|
||||
ctx context.Context,
|
||||
webhookConfigurationID gid.GID,
|
||||
) error {
|
||||
wc := &coredata.WebhookConfiguration{ID: webhookConfigurationID}
|
||||
|
||||
err := s.svc.pg.WithTx(
|
||||
ctx,
|
||||
func(conn pg.Conn) error {
|
||||
if err := wc.LoadByID(ctx, conn, s.svc.scope, webhookConfigurationID); err != nil {
|
||||
return fmt.Errorf("cannot load webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
if err := wc.Delete(ctx, conn, s.svc.scope); err != nil {
|
||||
return fmt.Errorf("cannot delete webhook configuration: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -15,6 +15,11 @@
|
||||
package probod
|
||||
|
||||
type notificationsConfig struct {
|
||||
Mailer mailerConfig `json:"mailer"`
|
||||
Slack slackConfig `json:"slack"`
|
||||
Mailer mailerConfig `json:"mailer"`
|
||||
Slack slackConfig `json:"slack"`
|
||||
Webhook webhookConfig `json:"webhook"`
|
||||
}
|
||||
|
||||
type webhookConfig struct {
|
||||
SenderInterval int `json:"sender-interval"`
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ import (
|
||||
"go.probo.inc/probo/pkg/server"
|
||||
"go.probo.inc/probo/pkg/slack"
|
||||
"go.probo.inc/probo/pkg/trust"
|
||||
"go.probo.inc/probo/pkg/webhook"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
@@ -154,6 +155,9 @@ func New() *Implm {
|
||||
Slack: slackConfig{
|
||||
SenderInterval: 60,
|
||||
},
|
||||
Webhook: webhookConfig{
|
||||
SenderInterval: 5,
|
||||
},
|
||||
},
|
||||
CustomDomains: customDomainsConfig{
|
||||
RenewalInterval: 3600,
|
||||
@@ -479,6 +483,19 @@ func (impl *Implm) Run(
|
||||
},
|
||||
)
|
||||
|
||||
webhookSenderCtx, stopWebhookSender := context.WithCancel(context.Background())
|
||||
webhookSender := webhook.NewSender(pgClient, l.Named("webhook-sender"), webhook.Config{
|
||||
Interval: time.Duration(impl.cfg.Notifications.Webhook.SenderInterval) * time.Second,
|
||||
EncryptionKey: impl.cfg.EncryptionKey,
|
||||
})
|
||||
wg.Go(
|
||||
func() {
|
||||
if err := webhookSender.Run(webhookSenderCtx); err != nil {
|
||||
cancel(fmt.Errorf("webhook sender crashed: %w", err))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
exportJobExporterCtx, stopExportJobExporter := context.WithCancel(context.Background())
|
||||
wg.Go(
|
||||
func() {
|
||||
@@ -511,6 +528,7 @@ func (impl *Implm) Run(
|
||||
|
||||
stopMailer()
|
||||
stopSlackSender()
|
||||
stopWebhookSender()
|
||||
stopExportJobExporter()
|
||||
stopIAMService()
|
||||
stopApiServer()
|
||||
|
||||
@@ -2654,6 +2654,7 @@ type Mutation {
|
||||
updateSCIMBridge(
|
||||
input: UpdateSCIMBridgeInput!
|
||||
): UpdateSCIMBridgePayload @session(required: PRESENT)
|
||||
|
||||
}
|
||||
|
||||
type Identity implements Node {
|
||||
@@ -3499,6 +3500,8 @@ type RegenerateSCIMTokenPayload {
|
||||
type UpdateSCIMBridgePayload {
|
||||
scimBridge: SCIMBridge!
|
||||
}
|
||||
|
||||
|
||||
`, BuiltIn: false},
|
||||
{Name: "../../../../gqlutils/directives/session/schema.graphql", Input: `# Session directive for GraphQL APIs
|
||||
# Include this schema in your gqlgen configuration to enable session-based access control.
|
||||
|
||||
@@ -488,6 +488,16 @@ enum MeetingOrderField
|
||||
)
|
||||
}
|
||||
|
||||
enum WebhookConfigurationOrderField
|
||||
@goModel(
|
||||
model: "go.probo.inc/probo/pkg/coredata.WebhookConfigurationOrderField"
|
||||
) {
|
||||
CREATED_AT
|
||||
@goEnum(
|
||||
value: "go.probo.inc/probo/pkg/coredata.WebhookConfigurationOrderFieldCreatedAt"
|
||||
)
|
||||
}
|
||||
|
||||
enum RiskOrderField
|
||||
@goModel(model: "go.probo.inc/probo/pkg/coredata.RiskOrderField") {
|
||||
CREATED_AT
|
||||
@@ -1345,6 +1355,14 @@ input MeetingOrder
|
||||
field: MeetingOrderField!
|
||||
}
|
||||
|
||||
input WebhookConfigurationOrder
|
||||
@goModel(
|
||||
model: "go.probo.inc/probo/pkg/server/api/console/v1/types.WebhookConfigurationOrderBy"
|
||||
) {
|
||||
direction: OrderDirection!
|
||||
field: WebhookConfigurationOrderField!
|
||||
}
|
||||
|
||||
input RiskOrder
|
||||
@goModel(
|
||||
model: "go.probo.inc/probo/pkg/server/api/console/v1/types.RiskOrderBy"
|
||||
@@ -1817,6 +1835,14 @@ type Organization implements Node {
|
||||
|
||||
customDomain: CustomDomain @goField(forceResolver: true)
|
||||
|
||||
webhookConfigurations(
|
||||
first: Int
|
||||
after: CursorKey
|
||||
last: Int
|
||||
before: CursorKey
|
||||
orderBy: WebhookConfigurationOrder
|
||||
): WebhookConfigurationConnection! @goField(forceResolver: true)
|
||||
|
||||
createdAt: Datetime!
|
||||
updatedAt: Datetime!
|
||||
|
||||
@@ -2242,6 +2268,48 @@ type Meeting implements Node {
|
||||
permission(action: String!): Boolean! @goField(forceResolver: true)
|
||||
}
|
||||
|
||||
enum WebhookEventType
|
||||
@goModel(model: "go.probo.inc/probo/pkg/coredata.WebhookEventType") {
|
||||
MEETING_CREATED
|
||||
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeMeetingCreated")
|
||||
MEETING_UPDATED
|
||||
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeMeetingUpdated")
|
||||
MEETING_DELETED
|
||||
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeMeetingDeleted")
|
||||
VENDOR_CREATED
|
||||
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeVendorCreated")
|
||||
VENDOR_UPDATED
|
||||
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeVendorUpdated")
|
||||
VENDOR_DELETED
|
||||
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeVendorDeleted")
|
||||
}
|
||||
|
||||
type WebhookConfiguration implements Node {
|
||||
id: ID!
|
||||
organization: Organization @goField(forceResolver: true)
|
||||
endpointUrl: String!
|
||||
signingSecret: String! @goField(forceResolver: true)
|
||||
selectedEvents: [WebhookEventType!]!
|
||||
createdAt: Datetime!
|
||||
updatedAt: Datetime!
|
||||
|
||||
permission(action: String!): Boolean! @goField(forceResolver: true)
|
||||
}
|
||||
|
||||
type WebhookConfigurationConnection
|
||||
@goModel(
|
||||
model: "go.probo.inc/probo/pkg/server/api/console/v1/types.WebhookConfigurationConnection"
|
||||
) {
|
||||
edges: [WebhookConfigurationEdge!]!
|
||||
pageInfo: PageInfo!
|
||||
totalCount: Int! @goField(forceResolver: true)
|
||||
}
|
||||
|
||||
type WebhookConfigurationEdge {
|
||||
cursor: CursorKey!
|
||||
node: WebhookConfiguration!
|
||||
}
|
||||
|
||||
type StateOfApplicability implements Node {
|
||||
id: ID!
|
||||
name: String!
|
||||
@@ -3270,6 +3338,16 @@ type Mutation {
|
||||
createMeeting(input: CreateMeetingInput!): CreateMeetingPayload!
|
||||
updateMeeting(input: UpdateMeetingInput!): UpdateMeetingPayload!
|
||||
deleteMeeting(input: DeleteMeetingInput!): DeleteMeetingPayload!
|
||||
# WebhookConfiguration mutations
|
||||
createWebhookConfiguration(
|
||||
input: CreateWebhookConfigurationInput!
|
||||
): CreateWebhookConfigurationPayload!
|
||||
updateWebhookConfiguration(
|
||||
input: UpdateWebhookConfigurationInput!
|
||||
): UpdateWebhookConfigurationPayload!
|
||||
deleteWebhookConfiguration(
|
||||
input: DeleteWebhookConfigurationInput!
|
||||
): DeleteWebhookConfigurationPayload!
|
||||
# StateOfApplicability mutations
|
||||
createStateOfApplicability(
|
||||
input: CreateStateOfApplicabilityInput!
|
||||
@@ -4621,6 +4699,34 @@ type DeleteMeetingPayload {
|
||||
deletedMeetingId: ID!
|
||||
}
|
||||
|
||||
input CreateWebhookConfigurationInput {
|
||||
organizationId: ID!
|
||||
endpointUrl: String!
|
||||
selectedEvents: [WebhookEventType!]!
|
||||
}
|
||||
|
||||
input UpdateWebhookConfigurationInput {
|
||||
id: ID!
|
||||
endpointUrl: String
|
||||
selectedEvents: [WebhookEventType!]
|
||||
}
|
||||
|
||||
input DeleteWebhookConfigurationInput {
|
||||
webhookConfigurationId: ID!
|
||||
}
|
||||
|
||||
type CreateWebhookConfigurationPayload {
|
||||
webhookConfigurationEdge: WebhookConfigurationEdge!
|
||||
}
|
||||
|
||||
type UpdateWebhookConfigurationPayload {
|
||||
webhookConfiguration: WebhookConfiguration!
|
||||
}
|
||||
|
||||
type DeleteWebhookConfigurationPayload {
|
||||
deletedWebhookConfigurationId: ID!
|
||||
}
|
||||
|
||||
type CreateStateOfApplicabilityPayload {
|
||||
stateOfApplicabilityEdge: StateOfApplicabilityEdge!
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -693,6 +693,16 @@ type CreateVendorServicePayload struct {
|
||||
VendorServiceEdge *VendorServiceEdge `json:"vendorServiceEdge"`
|
||||
}
|
||||
|
||||
type CreateWebhookConfigurationInput struct {
|
||||
OrganizationID gid.GID `json:"organizationId"`
|
||||
EndpointURL string `json:"endpointUrl"`
|
||||
SelectedEvents []coredata.WebhookEventType `json:"selectedEvents"`
|
||||
}
|
||||
|
||||
type CreateWebhookConfigurationPayload struct {
|
||||
WebhookConfigurationEdge *WebhookConfigurationEdge `json:"webhookConfigurationEdge"`
|
||||
}
|
||||
|
||||
type CustomDomain struct {
|
||||
ID gid.GID `json:"id"`
|
||||
Organization *Organization `json:"organization"`
|
||||
@@ -1103,6 +1113,14 @@ type DeleteVendorServicePayload struct {
|
||||
DeletedVendorServiceID gid.GID `json:"deletedVendorServiceId"`
|
||||
}
|
||||
|
||||
type DeleteWebhookConfigurationInput struct {
|
||||
WebhookConfigurationID gid.GID `json:"webhookConfigurationId"`
|
||||
}
|
||||
|
||||
type DeleteWebhookConfigurationPayload struct {
|
||||
DeletedWebhookConfigurationID gid.GID `json:"deletedWebhookConfigurationId"`
|
||||
}
|
||||
|
||||
type Document struct {
|
||||
ID gid.GID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
@@ -1499,6 +1517,7 @@ type Organization struct {
|
||||
TrustCenterFiles *TrustCenterFileConnection `json:"trustCenterFiles"`
|
||||
TrustCenter *TrustCenter `json:"trustCenter,omitempty"`
|
||||
CustomDomain *CustomDomain `json:"customDomain,omitempty"`
|
||||
WebhookConfigurations *WebhookConfigurationConnection `json:"webhookConfigurations"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Permission bool `json:"permission"`
|
||||
@@ -2342,6 +2361,16 @@ type UpdateVendorServicePayload struct {
|
||||
VendorService *VendorService `json:"vendorService"`
|
||||
}
|
||||
|
||||
type UpdateWebhookConfigurationInput struct {
|
||||
ID gid.GID `json:"id"`
|
||||
EndpointURL *string `json:"endpointUrl,omitempty"`
|
||||
SelectedEvents []coredata.WebhookEventType `json:"selectedEvents,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateWebhookConfigurationPayload struct {
|
||||
WebhookConfiguration *WebhookConfiguration `json:"webhookConfiguration"`
|
||||
}
|
||||
|
||||
type UploadAuditReportInput struct {
|
||||
AuditID gid.GID `json:"auditId"`
|
||||
File graphql.Upload `json:"file"`
|
||||
@@ -2593,3 +2622,22 @@ type Viewer struct {
|
||||
SignableDocuments *SignableDocumentConnection `json:"signableDocuments"`
|
||||
SignableDocument *SignableDocument `json:"signableDocument,omitempty"`
|
||||
}
|
||||
|
||||
type WebhookConfiguration struct {
|
||||
ID gid.GID `json:"id"`
|
||||
Organization *Organization `json:"organization,omitempty"`
|
||||
EndpointURL string `json:"endpointUrl"`
|
||||
SigningSecret string `json:"signingSecret"`
|
||||
SelectedEvents []coredata.WebhookEventType `json:"selectedEvents"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Permission bool `json:"permission"`
|
||||
}
|
||||
|
||||
func (WebhookConfiguration) IsNode() {}
|
||||
func (this WebhookConfiguration) GetID() gid.GID { return this.ID }
|
||||
|
||||
type WebhookConfigurationEdge struct {
|
||||
Cursor page.CursorKey `json:"cursor"`
|
||||
Node *WebhookConfiguration `json:"node"`
|
||||
}
|
||||
|
||||
74
pkg/server/api/console/v1/types/webhook_configuration.go
Normal file
74
pkg/server/api/console/v1/types/webhook_configuration.go
Normal file
@@ -0,0 +1,74 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package types
|
||||
|
||||
import (
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
"go.probo.inc/probo/pkg/page"
|
||||
)
|
||||
|
||||
type (
|
||||
WebhookConfigurationOrderBy OrderBy[coredata.WebhookConfigurationOrderField]
|
||||
|
||||
WebhookConfigurationConnection struct {
|
||||
TotalCount int
|
||||
Edges []*WebhookConfigurationEdge
|
||||
PageInfo PageInfo
|
||||
|
||||
Resolver any
|
||||
ParentID gid.GID
|
||||
}
|
||||
)
|
||||
|
||||
func NewWebhookConfigurationConnection(
|
||||
p *page.Page[*coredata.WebhookConfiguration, coredata.WebhookConfigurationOrderField],
|
||||
parentType any,
|
||||
parentID gid.GID,
|
||||
) *WebhookConfigurationConnection {
|
||||
var edges = make([]*WebhookConfigurationEdge, len(p.Data))
|
||||
|
||||
for i := range edges {
|
||||
edges[i] = NewWebhookConfigurationEdge(p.Data[i], p.Cursor.OrderBy.Field)
|
||||
}
|
||||
|
||||
return &WebhookConfigurationConnection{
|
||||
Edges: edges,
|
||||
PageInfo: *NewPageInfo(p),
|
||||
|
||||
Resolver: parentType,
|
||||
ParentID: parentID,
|
||||
}
|
||||
}
|
||||
|
||||
func NewWebhookConfigurationEdge(wc *coredata.WebhookConfiguration, orderBy coredata.WebhookConfigurationOrderField) *WebhookConfigurationEdge {
|
||||
return &WebhookConfigurationEdge{
|
||||
Cursor: wc.CursorKey(orderBy),
|
||||
Node: NewWebhookConfiguration(wc),
|
||||
}
|
||||
}
|
||||
|
||||
func NewWebhookConfiguration(wc *coredata.WebhookConfiguration) *WebhookConfiguration {
|
||||
return &WebhookConfiguration{
|
||||
ID: wc.ID,
|
||||
Organization: &Organization{
|
||||
ID: wc.OrganizationID,
|
||||
},
|
||||
EndpointURL: wc.EndpointURL,
|
||||
SelectedEvents: wc.SelectedEvents,
|
||||
CreatedAt: wc.CreatedAt,
|
||||
UpdatedAt: wc.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -3678,6 +3678,77 @@ func (r *mutationResolver) DeleteMeeting(ctx context.Context, input types.Delete
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateWebhookConfiguration is the resolver for the createWebhookConfiguration field.
|
||||
func (r *mutationResolver) CreateWebhookConfiguration(ctx context.Context, input types.CreateWebhookConfigurationInput) (*types.CreateWebhookConfigurationPayload, error) {
|
||||
if err := r.authorize(ctx, input.OrganizationID, probo.ActionWebhookConfigurationCreate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
prb := r.ProboService(ctx, input.OrganizationID.TenantID())
|
||||
|
||||
wc, err := prb.WebhookConfigurations.Create(
|
||||
ctx,
|
||||
probo.CreateWebhookConfigurationRequest{
|
||||
OrganizationID: input.OrganizationID,
|
||||
EndpointURL: input.EndpointURL,
|
||||
SelectedEvents: input.SelectedEvents,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot create webhook configuration", log.Error(err))
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return &types.CreateWebhookConfigurationPayload{
|
||||
WebhookConfigurationEdge: types.NewWebhookConfigurationEdge(wc, coredata.WebhookConfigurationOrderFieldCreatedAt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateWebhookConfiguration is the resolver for the updateWebhookConfiguration field.
|
||||
func (r *mutationResolver) UpdateWebhookConfiguration(ctx context.Context, input types.UpdateWebhookConfigurationInput) (*types.UpdateWebhookConfigurationPayload, error) {
|
||||
if err := r.authorize(ctx, input.ID, probo.ActionWebhookConfigurationUpdate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
prb := r.ProboService(ctx, input.ID.TenantID())
|
||||
|
||||
wc, err := prb.WebhookConfigurations.Update(
|
||||
ctx,
|
||||
probo.UpdateWebhookConfigurationRequest{
|
||||
WebhookConfigurationID: input.ID,
|
||||
EndpointURL: input.EndpointURL,
|
||||
SelectedEvents: input.SelectedEvents,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot update webhook configuration", log.Error(err))
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return &types.UpdateWebhookConfigurationPayload{
|
||||
WebhookConfiguration: types.NewWebhookConfiguration(wc),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DeleteWebhookConfiguration is the resolver for the deleteWebhookConfiguration field.
|
||||
func (r *mutationResolver) DeleteWebhookConfiguration(ctx context.Context, input types.DeleteWebhookConfigurationInput) (*types.DeleteWebhookConfigurationPayload, error) {
|
||||
if err := r.authorize(ctx, input.WebhookConfigurationID, probo.ActionWebhookConfigurationDelete); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
prb := r.ProboService(ctx, input.WebhookConfigurationID.TenantID())
|
||||
|
||||
err := prb.WebhookConfigurations.Delete(ctx, input.WebhookConfigurationID)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot delete webhook configuration", log.Error(err))
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return &types.DeleteWebhookConfigurationPayload{
|
||||
DeletedWebhookConfigurationID: input.WebhookConfigurationID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateStateOfApplicability is the resolver for the createStateOfApplicability field.
|
||||
func (r *mutationResolver) CreateStateOfApplicability(ctx context.Context, input types.CreateStateOfApplicabilityInput) (*types.CreateStateOfApplicabilityPayload, error) {
|
||||
if err := r.authorize(ctx, input.OrganizationID, probo.ActionStateOfApplicabilityCreate); err != nil {
|
||||
@@ -6313,6 +6384,36 @@ func (r *organizationResolver) CustomDomain(ctx context.Context, obj *types.Orga
|
||||
return types.NewCustomDomain(domain, r.customDomainCname), nil
|
||||
}
|
||||
|
||||
// WebhookConfigurations is the resolver for the webhookConfigurations field.
|
||||
func (r *organizationResolver) WebhookConfigurations(ctx context.Context, obj *types.Organization, first *int, after *page.CursorKey, last *int, before *page.CursorKey, orderBy *types.WebhookConfigurationOrderBy) (*types.WebhookConfigurationConnection, error) {
|
||||
if err := r.authorize(ctx, obj.ID, probo.ActionWebhookConfigurationList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
prb := r.ProboService(ctx, obj.ID.TenantID())
|
||||
|
||||
pageOrderBy := page.OrderBy[coredata.WebhookConfigurationOrderField]{
|
||||
Field: coredata.WebhookConfigurationOrderFieldCreatedAt,
|
||||
Direction: page.OrderDirectionDesc,
|
||||
}
|
||||
if orderBy != nil {
|
||||
pageOrderBy = page.OrderBy[coredata.WebhookConfigurationOrderField]{
|
||||
Field: orderBy.Field,
|
||||
Direction: orderBy.Direction,
|
||||
}
|
||||
}
|
||||
|
||||
cursor := types.NewCursor(first, after, last, before, pageOrderBy)
|
||||
|
||||
page, err := prb.WebhookConfigurations.ListForOrganizationID(ctx, obj.ID, cursor)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot list organization webhook configurations", log.Error(err))
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return types.NewWebhookConfigurationConnection(page, r, obj.ID), nil
|
||||
}
|
||||
|
||||
// Permission is the resolver for the permission field.
|
||||
func (r *organizationResolver) Permission(ctx context.Context, obj *types.Organization, action string) (bool, error) {
|
||||
return r.Resolver.Permission(ctx, obj, action)
|
||||
@@ -6761,6 +6862,15 @@ func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error
|
||||
}
|
||||
return types.NewStateOfApplicability(stateOfApplicability), nil
|
||||
}
|
||||
case coredata.WebhookConfigurationEntityType:
|
||||
action = probo.ActionWebhookConfigurationGet
|
||||
loadNode = func(ctx context.Context, id gid.GID) (types.Node, error) {
|
||||
wc, err := prb.WebhookConfigurations.Get(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return types.NewWebhookConfiguration(wc), nil
|
||||
}
|
||||
default:
|
||||
}
|
||||
|
||||
@@ -8449,6 +8559,67 @@ func (r *viewerResolver) SignableDocument(ctx context.Context, obj *types.Viewer
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Organization is the resolver for the organization field.
|
||||
func (r *webhookConfigurationResolver) Organization(ctx context.Context, obj *types.WebhookConfiguration) (*types.Organization, error) {
|
||||
if err := r.authorize(ctx, obj.ID, probo.ActionOrganizationGet); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
prb := r.ProboService(ctx, obj.ID.TenantID())
|
||||
|
||||
organization, err := prb.Organizations.Get(ctx, obj.Organization.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, coredata.ErrResourceNotFound) {
|
||||
return nil, gqlutils.NotFound(ctx, err)
|
||||
}
|
||||
|
||||
r.logger.ErrorCtx(ctx, "cannot load organization", log.Error(err))
|
||||
return nil, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return types.NewOrganization(organization), nil
|
||||
}
|
||||
|
||||
// SigningSecret is the resolver for the signingSecret field.
|
||||
func (r *webhookConfigurationResolver) SigningSecret(ctx context.Context, obj *types.WebhookConfiguration) (string, error) {
|
||||
prb := r.ProboService(ctx, obj.ID.TenantID())
|
||||
|
||||
signingSecret, err := prb.WebhookConfigurations.GetSigningSecret(ctx, obj.ID)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot get signing secret", log.Error(err))
|
||||
return "", gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
return signingSecret, nil
|
||||
}
|
||||
|
||||
// Permission is the resolver for the permission field.
|
||||
func (r *webhookConfigurationResolver) Permission(ctx context.Context, obj *types.WebhookConfiguration, action string) (bool, error) {
|
||||
return r.Resolver.Permission(ctx, obj, action)
|
||||
}
|
||||
|
||||
// TotalCount is the resolver for the totalCount field.
|
||||
func (r *webhookConfigurationConnectionResolver) TotalCount(ctx context.Context, obj *types.WebhookConfigurationConnection) (int, error) {
|
||||
if err := r.authorize(ctx, obj.ParentID, probo.ActionWebhookConfigurationList); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
prb := r.ProboService(ctx, obj.ParentID.TenantID())
|
||||
|
||||
switch obj.Resolver.(type) {
|
||||
case *organizationResolver:
|
||||
count, err := prb.WebhookConfigurations.CountForOrganizationID(ctx, obj.ParentID)
|
||||
if err != nil {
|
||||
r.logger.ErrorCtx(ctx, "cannot count webhook configurations", log.Error(err))
|
||||
return 0, gqlutils.Internal(ctx)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
r.logger.ErrorCtx(ctx, "unsupported resolver for webhook configuration connection", log.String("resolver", fmt.Sprintf("%T", obj.Resolver)))
|
||||
return 0, gqlutils.Internal(ctx)
|
||||
}
|
||||
|
||||
// ApplicabilityStatement returns schema.ApplicabilityStatementResolver implementation.
|
||||
func (r *Resolver) ApplicabilityStatement() schema.ApplicabilityStatementResolver {
|
||||
return &applicabilityStatementResolver{r}
|
||||
@@ -8751,6 +8922,16 @@ func (r *Resolver) VendorService() schema.VendorServiceResolver { return &vendor
|
||||
// Viewer returns schema.ViewerResolver implementation.
|
||||
func (r *Resolver) Viewer() schema.ViewerResolver { return &viewerResolver{r} }
|
||||
|
||||
// WebhookConfiguration returns schema.WebhookConfigurationResolver implementation.
|
||||
func (r *Resolver) WebhookConfiguration() schema.WebhookConfigurationResolver {
|
||||
return &webhookConfigurationResolver{r}
|
||||
}
|
||||
|
||||
// WebhookConfigurationConnection returns schema.WebhookConfigurationConnectionResolver implementation.
|
||||
func (r *Resolver) WebhookConfigurationConnection() schema.WebhookConfigurationConnectionResolver {
|
||||
return &webhookConfigurationConnectionResolver{r}
|
||||
}
|
||||
|
||||
type applicabilityStatementResolver struct{ *Resolver }
|
||||
type applicabilityStatementConnectionResolver struct{ *Resolver }
|
||||
type assetResolver struct{ *Resolver }
|
||||
@@ -8823,3 +9004,5 @@ type vendorDataPrivacyAgreementResolver struct{ *Resolver }
|
||||
type vendorRiskAssessmentResolver struct{ *Resolver }
|
||||
type vendorServiceResolver struct{ *Resolver }
|
||||
type viewerResolver struct{ *Resolver }
|
||||
type webhookConfigurationResolver struct{ *Resolver }
|
||||
type webhookConfigurationConnectionResolver struct{ *Resolver }
|
||||
|
||||
153
pkg/webhook/data.go
Normal file
153
pkg/webhook/data.go
Normal file
@@ -0,0 +1,153 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
)
|
||||
|
||||
var (
|
||||
jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
|
||||
textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
|
||||
)
|
||||
|
||||
func InsertEvent(
|
||||
ctx context.Context,
|
||||
conn pg.Conn,
|
||||
scope coredata.Scoper,
|
||||
organizationID gid.GID,
|
||||
eventType coredata.WebhookEventType,
|
||||
data any,
|
||||
) error {
|
||||
var configs coredata.WebhookConfigurations
|
||||
exists, err := configs.ExistsByOrganizationIDAndEventType(ctx, conn, scope, organizationID, eventType)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot check webhook configurations: %w", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
raw, err := MarshalData(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot marshal webhook event data: %w", err)
|
||||
}
|
||||
|
||||
event := &coredata.WebhookEvent{
|
||||
ID: gid.New(scope.GetTenantID(), coredata.WebhookEventEntityType),
|
||||
OrganizationID: organizationID,
|
||||
EventType: eventType,
|
||||
Status: coredata.WebhookEventStatusPending,
|
||||
Data: raw,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err = event.Insert(ctx, conn, scope); err != nil {
|
||||
return fmt.Errorf("cannot insert webhook event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func MarshalData(v any) (json.RawMessage, error) {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot marshal webhook data: %w", err)
|
||||
}
|
||||
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, fmt.Errorf("cannot unmarshal webhook data: %w", err)
|
||||
}
|
||||
|
||||
for _, key := range nestedFieldKeys(v) {
|
||||
delete(m, key)
|
||||
}
|
||||
|
||||
delete(m, "permission")
|
||||
|
||||
data, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot re-marshal webhook data: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func nestedFieldKeys(v any) []string {
|
||||
t := reflect.TypeOf(v)
|
||||
for t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
if t.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
|
||||
var keys []string
|
||||
for i := range t.NumField() {
|
||||
field := t.Field(i)
|
||||
|
||||
tag := field.Tag.Get("json")
|
||||
if tag == "" || tag == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
jsonKey, _, _ := strings.Cut(tag, ",")
|
||||
|
||||
if isNestedType(field.Type) {
|
||||
keys = append(keys, jsonKey)
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func isNestedType(t reflect.Type) bool {
|
||||
for t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
if t.Kind() == reflect.Slice {
|
||||
return isNestedType(t.Elem())
|
||||
}
|
||||
|
||||
if t.Kind() != reflect.Struct {
|
||||
return false
|
||||
}
|
||||
|
||||
ptrType := reflect.PointerTo(t)
|
||||
|
||||
if t.Implements(jsonMarshalerType) || ptrType.Implements(jsonMarshalerType) {
|
||||
return false
|
||||
}
|
||||
|
||||
if t.Implements(textMarshalerType) || ptrType.Implements(textMarshalerType) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
352
pkg/webhook/sender.go
Normal file
352
pkg/webhook/sender.go
Normal file
@@ -0,0 +1,352 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.gearno.de/kit/httpclient"
|
||||
"go.gearno.de/kit/log"
|
||||
"go.gearno.de/kit/pg"
|
||||
"go.probo.inc/probo/pkg/coredata"
|
||||
"go.probo.inc/probo/pkg/crypto/cipher"
|
||||
"go.probo.inc/probo/pkg/gid"
|
||||
)
|
||||
|
||||
type (
|
||||
Sender struct {
|
||||
pg *pg.Client
|
||||
logger *log.Logger
|
||||
httpClient *http.Client
|
||||
encryptionKey cipher.EncryptionKey
|
||||
cache sync.Map
|
||||
interval time.Duration
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
Config struct {
|
||||
Interval time.Duration
|
||||
Timeout time.Duration
|
||||
EncryptionKey cipher.EncryptionKey
|
||||
}
|
||||
)
|
||||
|
||||
const maxResponseBodySize = 64 * 1024 // 64KB
|
||||
|
||||
func NewSender(pg *pg.Client, logger *log.Logger, cfg Config) *Sender {
|
||||
if cfg.Interval <= 0 {
|
||||
cfg.Interval = 5 * time.Second
|
||||
}
|
||||
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
return &Sender{
|
||||
pg: pg,
|
||||
logger: logger,
|
||||
httpClient: httpclient.DefaultPooledClient(httpclient.WithLogger(logger)),
|
||||
encryptionKey: cfg.EncryptionKey,
|
||||
interval: cfg.Interval,
|
||||
timeout: cfg.Timeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sender) Run(ctx context.Context) error {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(s.interval):
|
||||
if err := s.processEvents(ctx); err != nil {
|
||||
s.logger.ErrorCtx(ctx, "cannot process webhook events", log.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sender) processEvents(ctx context.Context) error {
|
||||
for {
|
||||
event, err := s.claimNextEvent(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, coredata.ErrResourceNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
s.processEvent(ctx, event)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sender) claimNextEvent(ctx context.Context) (*coredata.WebhookEvent, error) {
|
||||
var event coredata.WebhookEvent
|
||||
|
||||
err := s.pg.WithTx(ctx, func(tx pg.Conn) error {
|
||||
if err := event.LoadNextPendingForUpdate(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
scope := coredata.NewScopeFromObjectID(event.ID)
|
||||
|
||||
event.Status = coredata.WebhookEventStatusProcessing
|
||||
|
||||
if err := event.UpdateStatus(ctx, tx, scope); err != nil {
|
||||
return fmt.Errorf("cannot update webhook event to processing: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &event, nil
|
||||
}
|
||||
|
||||
func (s *Sender) processEvent(ctx context.Context, event *coredata.WebhookEvent) {
|
||||
scope := coredata.NewScopeFromObjectID(event.ID)
|
||||
|
||||
var configs coredata.WebhookConfigurations
|
||||
err := s.pg.WithConn(ctx, func(conn pg.Conn) error {
|
||||
return configs.LoadMatchingByOrganizationIDAndEventType(
|
||||
ctx, conn, scope, event.OrganizationID, event.EventType,
|
||||
)
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.ErrorCtx(ctx, "cannot load matching webhook configurations",
|
||||
log.Error(err),
|
||||
log.String("event_id", event.ID.String()),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
for _, config := range configs {
|
||||
s.deliverToConfiguration(ctx, event, config, scope)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
event.Status = coredata.WebhookEventStatusDelivered
|
||||
event.ProcessedAt = &now
|
||||
|
||||
err = s.pg.WithConn(ctx, func(conn pg.Conn) error {
|
||||
return event.UpdateStatus(ctx, conn, scope)
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.ErrorCtx(ctx, "cannot update webhook event to delivered",
|
||||
log.Error(err),
|
||||
log.String("event_id", event.ID.String()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sender) deliverToConfiguration(
|
||||
ctx context.Context,
|
||||
event *coredata.WebhookEvent,
|
||||
config *coredata.WebhookConfiguration,
|
||||
scope coredata.Scoper,
|
||||
) {
|
||||
callID := gid.New(event.ID.TenantID(), coredata.WebhookCallEntityType)
|
||||
|
||||
signingSecret, err := s.getSigningSecret(config.ID.String(), config.EncryptedSigningSecret)
|
||||
if err != nil {
|
||||
s.logger.ErrorCtx(ctx, "cannot get signing secret",
|
||||
log.Error(err),
|
||||
log.String("event_id", event.ID.String()),
|
||||
log.String("configuration_id", config.ID.String()),
|
||||
)
|
||||
s.recordCall(ctx, callID, event, config, scope, coredata.WebhookCallStatusFailed, nil)
|
||||
return
|
||||
}
|
||||
|
||||
response, sendErr := s.doHTTPCall(ctx, callID, config.EndpointURL, event, config.ID, signingSecret)
|
||||
|
||||
callStatus := coredata.WebhookCallStatusSucceeded
|
||||
if sendErr != nil {
|
||||
callStatus = coredata.WebhookCallStatusFailed
|
||||
s.logger.ErrorCtx(ctx, "error delivering webhook event",
|
||||
log.Error(sendErr),
|
||||
log.String("event_id", event.ID.String()),
|
||||
log.String("endpoint_url", config.EndpointURL),
|
||||
)
|
||||
}
|
||||
|
||||
s.recordCall(ctx, callID, event, config, scope, callStatus, response)
|
||||
}
|
||||
|
||||
func (s *Sender) getSigningSecret(webhookConfigurationID string, encryptedSigningSecret []byte) (string, error) {
|
||||
if cached, ok := s.cache.Load(webhookConfigurationID); ok {
|
||||
return cached.(string), nil
|
||||
}
|
||||
|
||||
plaintext, err := cipher.Decrypt(encryptedSigningSecret, s.encryptionKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot decrypt signing secret: %w", err)
|
||||
}
|
||||
|
||||
signingSecret := string(plaintext)
|
||||
s.cache.Store(webhookConfigurationID, signingSecret)
|
||||
|
||||
return signingSecret, nil
|
||||
}
|
||||
|
||||
func (s *Sender) doHTTPCall(
|
||||
ctx context.Context,
|
||||
callID gid.GID,
|
||||
endpointURL string,
|
||||
event *coredata.WebhookEvent,
|
||||
configurationID gid.GID,
|
||||
signingSecret string,
|
||||
) (json.RawMessage, error) {
|
||||
payload := map[string]any{
|
||||
"eventId": event.ID.String(),
|
||||
"callId": callID.String(),
|
||||
"configurationId": configurationID.String(),
|
||||
"eventType": event.EventType.String(),
|
||||
"createdAt": event.CreatedAt,
|
||||
"data": event.Data,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot marshal webhook payload: %w", err)
|
||||
}
|
||||
|
||||
reqCtx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, endpointURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot create request: %w", err)
|
||||
}
|
||||
|
||||
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
signature := computeSignature(signingSecret, timestamp, body)
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Probo-Webhook-Event", event.EventType.String())
|
||||
req.Header.Set("X-Probo-Webhook-Timestamp", timestamp)
|
||||
req.Header.Set("X-Probo-Webhook-Signature", signature)
|
||||
|
||||
resp, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot send request: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize))
|
||||
|
||||
response := buildResponseJSON(resp, respBody)
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK,
|
||||
http.StatusCreated,
|
||||
http.StatusAccepted,
|
||||
http.StatusNoContent:
|
||||
return response, nil
|
||||
default:
|
||||
return response, fmt.Errorf("webhook endpoint returned status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sender) recordCall(
|
||||
ctx context.Context,
|
||||
callID gid.GID,
|
||||
event *coredata.WebhookEvent,
|
||||
config *coredata.WebhookConfiguration,
|
||||
scope coredata.Scoper,
|
||||
status coredata.WebhookCallStatus,
|
||||
response json.RawMessage,
|
||||
) {
|
||||
call := coredata.WebhookCall{
|
||||
ID: callID,
|
||||
WebhookEventID: event.ID,
|
||||
WebhookConfigurationID: config.ID,
|
||||
EndpointURL: config.EndpointURL,
|
||||
Status: status,
|
||||
Response: response,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
err := s.pg.WithConn(ctx, func(conn pg.Conn) error {
|
||||
return call.Insert(ctx, conn, scope)
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.ErrorCtx(ctx, "cannot insert webhook call",
|
||||
log.Error(err),
|
||||
log.String("event_id", event.ID.String()),
|
||||
log.String("configuration_id", config.ID.String()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func buildResponseJSON(resp *http.Response, body []byte) json.RawMessage {
|
||||
headers := make(map[string]any, len(resp.Header))
|
||||
for k, v := range resp.Header {
|
||||
if len(v) == 1 {
|
||||
headers[k] = v[0]
|
||||
} else {
|
||||
headers[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
var bodyValue any
|
||||
if json.Valid(body) {
|
||||
bodyValue = json.RawMessage(body)
|
||||
} else {
|
||||
bodyValue = string(body)
|
||||
}
|
||||
|
||||
respObj := map[string]any{
|
||||
"proto": resp.Proto,
|
||||
"status_code": resp.StatusCode,
|
||||
"headers": headers,
|
||||
"body": bodyValue,
|
||||
}
|
||||
|
||||
if len(resp.Trailer) > 0 {
|
||||
trailers := make(map[string]any, len(resp.Trailer))
|
||||
for k, v := range resp.Trailer {
|
||||
if len(v) == 1 {
|
||||
trailers[k] = v[0]
|
||||
} else {
|
||||
trailers[k] = v
|
||||
}
|
||||
}
|
||||
respObj["trailers"] = trailers
|
||||
}
|
||||
|
||||
data, _ := json.Marshal(respObj)
|
||||
return data
|
||||
}
|
||||
|
||||
func computeSignature(signingSecret, timestamp string, body []byte) string {
|
||||
h := hmac.New(sha256.New, []byte(signingSecret))
|
||||
_, _ = fmt.Fprintf(h, "%s:%s", timestamp, body)
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
Reference in New Issue
Block a user