Add bridge backend for sync

Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
Bryan Frimin
2026-02-01 21:22:31 +01:00
parent bc5bbdae81
commit 3d4b215b8f
19 changed files with 1038 additions and 145 deletions

View File

@@ -0,0 +1,142 @@
// 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 scimbridge provides a bridge for synchronizing users from identity
// providers to SCIM-compliant systems.
package bridge
import (
"context"
"errors"
"fmt"
"strings"
scimclient "go.probo.inc/probo/pkg/iam/scim/bridge/client"
"go.probo.inc/probo/pkg/iam/scim/bridge/provider"
)
type (
Bridge struct {
provider provider.Provider
scimClient *scimclient.Client
forceUpdate bool
dryRun bool
}
Option func(*Bridge)
)
func WithDryRun(dryRun bool) Option {
return func(s *Bridge) {
s.dryRun = dryRun
}
}
func WithForceUpdate(forceUpdate bool) Option {
return func(s *Bridge) {
s.forceUpdate = forceUpdate
}
}
func NewBridge(provider provider.Provider, scimClient *scimclient.Client, opts ...Option) *Bridge {
s := &Bridge{
provider: provider,
scimClient: scimClient,
}
for _, opt := range opts {
opt(s)
}
return s
}
func (s *Bridge) Run(ctx context.Context) (created, updated, deactivated, skipped int, err error) {
providerUsers, err := s.provider.ListUsers(ctx)
if err != nil {
return 0, 0, 0, 0, fmt.Errorf("cannot list provider users: %w", err)
}
scimUsers, err := s.scimClient.ListUsers(ctx)
if err != nil {
return 0, 0, 0, 0, fmt.Errorf("cannot list scim users: %w", err)
}
scimUsersByEmail := make(map[string]*scimclient.User)
for i := range scimUsers {
email := strings.ToLower(scimUsers[i].UserName)
scimUsersByEmail[email] = &scimUsers[i]
}
providerEmails := make(map[string]bool)
var errs []error
for _, pu := range providerUsers {
email := strings.ToLower(pu.UserName)
providerEmails[email] = true
existingSCIM, exists := scimUsersByEmail[email]
if !exists {
if !s.dryRun {
if err := s.scimClient.CreateUser(ctx, &pu); err != nil {
errs = append(errs, fmt.Errorf("cannot create user %q: %w", pu.UserName, err))
continue
}
}
created++
} else {
needsUpdate := s.forceUpdate
if existingSCIM.Active != pu.Active {
needsUpdate = true
}
if existingSCIM.DisplayName != pu.DisplayName {
needsUpdate = true
}
if needsUpdate {
if !s.dryRun {
if err := s.scimClient.UpdateUser(ctx, existingSCIM.ID, &pu); err != nil {
errs = append(errs, fmt.Errorf("cannot update user %q: %w", pu.UserName, err))
continue
}
}
updated++
} else {
skipped++
}
}
}
for email, scimUser := range scimUsersByEmail {
if providerEmails[email] {
continue
}
if !scimUser.Active {
continue
}
if !s.dryRun {
if err := s.scimClient.DeactivateUser(ctx, scimUser.ID); err != nil {
errs = append(errs, fmt.Errorf("cannot deactivate user %q: %w", email, err))
continue
}
}
deactivated++
}
return created, updated, deactivated, skipped, errors.Join(errs...)
}

View File

@@ -0,0 +1,254 @@
// 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 scimclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
type (
Client struct {
endpoint string
token string
httpClient *http.Client
}
User struct {
ID string `json:"id,omitempty"`
UserName string `json:"userName"`
DisplayName string `json:"displayName"`
GivenName string `json:"-"`
FamilyName string `json:"-"`
Active bool `json:"active"`
}
Users []User
ListResponse struct {
Schemas []string `json:"schemas"`
TotalResults int `json:"totalResults"`
StartIndex int `json:"startIndex"`
ItemsPerPage int `json:"itemsPerPage"`
Resources Users `json:"Resources"`
}
)
func NewClient(httpClient *http.Client, endpoint, token string) *Client {
return &Client{
endpoint: strings.TrimSuffix(endpoint, "/"),
token: token,
httpClient: httpClient,
}
}
func (c *Client) ListUsers(ctx context.Context) (Users, error) {
var allUsers Users
startIndex := 1
count := 100
for {
users, total, err := c.listUsersPage(ctx, startIndex, count)
if err != nil {
return nil, err
}
allUsers = append(allUsers, users...)
if len(allUsers) >= total {
break
}
startIndex += count
}
return allUsers, nil
}
func (c *Client) listUsersPage(ctx context.Context, startIndex, count int) (Users, int, error) {
reqURL := fmt.Sprintf("%s/Users?startIndex=%d&count=%d", c.endpoint, startIndex, count)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
if err != nil {
return nil, 0, fmt.Errorf("cannot create request: %w", err)
}
c.setHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("cannot fetch users: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, 0, fmt.Errorf("SCIM API error: status %d, body: %s", resp.StatusCode, string(body))
}
var listResp ListResponse
if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
return nil, 0, fmt.Errorf("cannot decode response: %w", err)
}
return listResp.Resources, listResp.TotalResults, nil
}
func (c *Client) CreateUser(ctx context.Context, user *User) error {
payload := map[string]any{
"schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
"userName": user.UserName,
"name": map[string]string{
"givenName": user.GivenName,
"familyName": user.FamilyName,
"formatted": user.DisplayName,
},
"displayName": user.DisplayName,
"active": user.Active,
"emails": []map[string]any{
{
"value": user.UserName,
"type": "work",
"primary": true,
},
},
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("cannot marshal user: %w", err)
}
reqURL := fmt.Sprintf("%s/Users", c.endpoint)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("cannot create request: %w", err)
}
c.setHeaders(req)
req.Header.Set("Content-Type", "application/scim+json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("cannot create user: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("SCIM API error: status %d, body: %s", resp.StatusCode, string(respBody))
}
return nil
}
func (c *Client) UpdateUser(ctx context.Context, userID string, user *User) error {
payload := map[string]any{
"schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
"userName": user.UserName,
"name": map[string]string{
"givenName": user.GivenName,
"familyName": user.FamilyName,
"formatted": user.DisplayName,
},
"displayName": user.DisplayName,
"active": user.Active,
"emails": []map[string]any{
{
"value": user.UserName,
"type": "work",
"primary": true,
},
},
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("cannot marshal user: %w", err)
}
reqURL := fmt.Sprintf("%s/Users/%s", c.endpoint, url.PathEscape(userID))
req, err := http.NewRequestWithContext(ctx, http.MethodPut, reqURL, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("cannot create request: %w", err)
}
c.setHeaders(req)
req.Header.Set("Content-Type", "application/scim+json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("cannot update user: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("SCIM API error: status %d, body: %s", resp.StatusCode, string(respBody))
}
return nil
}
func (c *Client) DeactivateUser(ctx context.Context, userID string) error {
payload := map[string]any{
"schemas": []string{"urn:ietf:params:scim:api:messages:2.0:PatchOp"},
"Operations": []map[string]any{
{
"op": "replace",
"path": "active",
"value": false,
},
},
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("cannot marshal patch: %w", err)
}
reqURL := fmt.Sprintf("%s/Users/%s", c.endpoint, url.PathEscape(userID))
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, reqURL, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("cannot create request: %w", err)
}
c.setHeaders(req)
req.Header.Set("Content-Type", "application/scim+json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("cannot deactivate user: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("SCIM API error: status %d, body: %s", resp.StatusCode, string(respBody))
}
return nil
}
func (c *Client) setHeaders(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Accept", "application/scim+json")
}

View 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 googleworkspace provides a Google Workspace identity provider
// for SCIM synchronization using OAuth2.
package googleworkspace
import (
"context"
"fmt"
"net/http"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
scimclient "go.probo.inc/probo/pkg/iam/scim/bridge/client"
"go.probo.inc/probo/pkg/iam/scim/bridge/provider"
)
var _ provider.Provider = (*Provider)(nil)
type Provider struct {
httpClient *http.Client
}
func New(httpClient *http.Client) *Provider {
return &Provider{
httpClient: httpClient,
}
}
func (p *Provider) Name() string {
return "google-workspace"
}
func (p *Provider) ListUsers(ctx context.Context) (scimclient.Users, error) {
adminService, err := admin.NewService(ctx, option.WithHTTPClient(p.httpClient))
if err != nil {
return nil, fmt.Errorf("cannot create admin service: %w", err)
}
var allUsers scimclient.Users
pageToken := ""
for {
call := adminService.Users.List().Customer("my_customer").MaxResults(500).Context(ctx)
if pageToken != "" {
call = call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
return nil, fmt.Errorf("cannot list users: %w", err)
}
for _, u := range resp.Users {
allUsers = append(
allUsers,
scimclient.User{
UserName: u.PrimaryEmail,
DisplayName: u.Name.FullName,
GivenName: u.Name.GivenName,
FamilyName: u.Name.FamilyName,
Active: !u.Suspended && !u.Archived,
},
)
}
pageToken = resp.NextPageToken
if pageToken == "" {
break
}
}
return allUsers, nil
}

View File

@@ -0,0 +1,28 @@
// 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 provider defines the interface for identity providers that can be
// used as a source of truth for SCIM synchronization.
package provider
import (
"context"
scimclient "go.probo.inc/probo/pkg/iam/scim/bridge/client"
)
type Provider interface {
Name() string
ListUsers(ctx context.Context) (scimclient.Users, error)
}