Verify Crisp website ownership before connecting

Crisp is a managed (Model B) connector: Probo holds one plugin token
server-side and each connection carries only a Website ID. Nothing
stops one organization from entering another organization's Website
ID, so prove control of the website before creating the connection.

Probo derives a per-(organization, website) verification code as an
HMAC over the token secret and exposes it through a new
crispVerificationCode query. The customer pastes it into the Probo
plugin's per-website settings; at connect time the resolver reads the
setting back through the managed plugin token and requires a
constant-time match before any row is written. The managed key and
plugin ID come from bootstrap, so the connector stays hidden until the
deployment configures them.

The settings fetch is injected so the create-time gate's branch wiring
is unit-tested (mismatch and not-subscribed reject, internal errors
stay generic, a matching code passes), and the managed-versus-client
key resolution is covered too.

Signed-off-by: Aurélien Sibiril <81782+aureliensibiril@users.noreply.github.com>
This commit is contained in:
Aurélien Sibiril
2026-07-11 16:50:32 +02:00
parent 6435a52f47
commit 37121e7bac
24 changed files with 1294 additions and 18 deletions

View File

@@ -17,6 +17,7 @@ package drivers
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@@ -25,6 +26,32 @@ import (
"go.probo.inc/probo/pkg/coredata"
)
// ErrCrispPluginNotSubscribed is returned by GetCrispSubscriptionSettings when
// Crisp answers 404: the plugin is not subscribed to the given website, so no
// per-website settings exist yet. It is an expected verification state (the
// customer has not installed/configured the plugin on that website) rather than
// a failure, and callers distinguish it with errors.Is.
var ErrCrispPluginNotSubscribed = errors.New("crisp plugin not subscribed to website")
// CrispSubscriptionSettings is the schema-defined, per-website configuration of
// the Probo Crisp plugin. Only the field Probo relies on for ownership
// verification is modeled; unknown schema properties are ignored on decode.
type CrispSubscriptionSettings struct {
ProboVerificationCode string `json:"probo_verification_code"`
}
// crispSubscriptionSettingsResponse is the envelope of
// GET /v1/plugins/subscription/{website_id}/{plugin_id}/settings. The active
// per-website configuration lives at data.settings; data itself also carries
// subscription metadata (ids, secret token, JSONSchema, form/callback URLs)
// that verification does not need.
type crispSubscriptionSettingsResponse struct {
Error bool `json:"error"`
Data struct {
Settings CrispSubscriptionSettings `json:"settings"`
} `json:"data"`
}
const (
crispAPIBaseURL = "https://api.crisp.chat/v1"
// crispTierHeader selects the token tier on every Crisp request. A Probo
@@ -124,6 +151,65 @@ func (d *CrispDriver) ListAccounts(ctx context.Context) ([]AccountRecord, error)
return records, nil
}
// GetCrispSubscriptionSettings reads the Probo plugin's per-website
// subscription settings so the create-connector resolver can verify website
// ownership (matching probo_verification_code). The httpClient must already
// attach the plugin Basic credential (identifier:key); this helper only sets
// the Accept and X-Crisp-Tier headers, mirroring ListAccounts. A 404 (plugin
// not subscribed to the website) is reported as ErrCrispPluginNotSubscribed so
// callers can message it distinctly from a hard failure.
func GetCrispSubscriptionSettings(
ctx context.Context,
httpClient *http.Client,
websiteID string,
pluginID string,
) (*CrispSubscriptionSettings, error) {
endpoint, err := url.JoinPath(
crispAPIBaseURL,
"plugins", "subscription",
url.PathEscape(websiteID),
url.PathEscape(pluginID),
"settings",
)
if err != nil {
return nil, fmt.Errorf("cannot build crisp subscription settings URL: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("cannot create crisp subscription settings request: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set(crispTierHeader, crispTierValue)
httpResp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("cannot execute crisp subscription settings request: %w", err)
}
defer func() { _ = httpResp.Body.Close() }()
if httpResp.StatusCode == http.StatusNotFound {
return nil, ErrCrispPluginNotSubscribed
}
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
return nil, fmt.Errorf("cannot fetch crisp subscription settings: unexpected status %d", httpResp.StatusCode)
}
var resp crispSubscriptionSettingsResponse
if err := json.NewDecoder(httpResp.Body).Decode(&resp); err != nil {
return nil, fmt.Errorf("cannot decode crisp subscription settings response: %w", err)
}
if resp.Error {
return nil, fmt.Errorf("cannot fetch crisp subscription settings: crisp reported an error")
}
return &resp.Data.Settings, nil
}
func crispFullName(details crispOperatorDetails, fallback string) string {
if name := strings.TrimSpace(details.FirstName + " " + details.LastName); name != "" {
return name

View File

@@ -0,0 +1,124 @@
// Copyright (c) 2026 Probo Inc <hello@probo.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 drivers
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetCrispSubscriptionSettings(t *testing.T) {
t.Parallel()
const (
websiteID = "e8592878-c0d0-4632-b2f7-7d882f288d43"
pluginID = "e979a1c3-2c41-4e93-a8ed-410ace27318e"
)
t.Run("200 returns the verification code from data.settings", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The plugin subscription-settings endpoint is plugins (plural)
// with both website_id and plugin_id in the path.
assert.Equal(t, http.MethodGet, r.Method)
assert.Equal(t, "/v1/plugins/subscription/"+websiteID+"/"+pluginID+"/settings", r.URL.Path)
assert.Equal(t, "plugin", r.Header.Get("X-Crisp-Tier"))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"error":false,"reason":"resolved","data":{"plugin_id":"` + pluginID + `","settings":{"probo_verification_code":"ABC234DEF567"}}}`))
}))
defer srv.Close()
client := &http.Client{Transport: &hostRewriter{target: srv.URL}}
settings, err := GetCrispSubscriptionSettings(context.Background(), client, websiteID, pluginID)
require.NoError(t, err)
require.NotNil(t, settings)
assert.Equal(t, "ABC234DEF567", settings.ProboVerificationCode)
})
t.Run("200 without the code returns empty (mismatch handled by caller)", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"error":false,"data":{"settings":{}}}`))
}))
defer srv.Close()
client := &http.Client{Transport: &hostRewriter{target: srv.URL}}
settings, err := GetCrispSubscriptionSettings(context.Background(), client, websiteID, pluginID)
require.NoError(t, err)
require.NotNil(t, settings)
assert.Empty(t, settings.ProboVerificationCode)
})
t.Run("404 reports the plugin is not subscribed", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":true,"reason":"subscription_not_found"}`))
}))
defer srv.Close()
client := &http.Client{Transport: &hostRewriter{target: srv.URL}}
settings, err := GetCrispSubscriptionSettings(context.Background(), client, websiteID, pluginID)
require.ErrorIs(t, err, ErrCrispPluginNotSubscribed)
assert.Nil(t, settings)
})
t.Run("non-2xx returns an error", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":true,"reason":"server_error"}`))
}))
defer srv.Close()
client := &http.Client{Transport: &hostRewriter{target: srv.URL}}
settings, err := GetCrispSubscriptionSettings(context.Background(), client, websiteID, pluginID)
require.Error(t, err)
assert.False(t, errors.Is(err, ErrCrispPluginNotSubscribed))
assert.Nil(t, settings)
})
t.Run("2xx with error:true returns an error", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"error":true,"reason":"route_forbidden","data":{}}`))
}))
defer srv.Close()
client := &http.Client{Transport: &hostRewriter{target: srv.URL}}
settings, err := GetCrispSubscriptionSettings(context.Background(), client, websiteID, pluginID)
require.Error(t, err)
assert.Nil(t, settings)
})
}

View File

@@ -236,6 +236,12 @@ func (s *Service) connectorHTTPClient(
return s.oauthClient(ctx, oauth2Conn, dbConnector.Provider)
}
// Inject the Probo-held key for ManagedAPIKey providers (no-op otherwise),
// resolving it fresh at use time rather than from the connection row.
if err := s.providerRegistry.ApplyManagedAPIKey(dbConnector); err != nil {
return nil, err
}
return dbConnector.Connection.Client(ctx)
}

View File

@@ -236,6 +236,12 @@ func (h *sourceNameHandler) connectorHTTPClient(
) (*http.Client, error) {
oauth2Conn, ok := dbConnector.Connection.(*connector.OAuth2Connection)
if !ok {
// Inject the Probo-held key for ManagedAPIKey providers (no-op
// otherwise) before building the client.
if err := h.providerRegistry.ApplyManagedAPIKey(dbConnector); err != nil {
return nil, err
}
return dbConnector.Connection.Client(ctx)
}

View File

@@ -364,6 +364,13 @@ func (s *Service) ConnectorHTTPClient(
}
if httpClient == nil {
// Inject the Probo-held key for ManagedAPIKey providers (no-op
// otherwise), resolving it fresh at use time rather than from the
// connection row.
if err := s.providerRegistry.ApplyManagedAPIKey(&dbConnector); err != nil {
return nil, nil, err
}
var err error
httpClient, err = dbConnector.Connection.Client(ctx)