-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
1910 lines (1708 loc) · 66.1 KB
/
client.go
File metadata and controls
1910 lines (1708 loc) · 66.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package client
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"sync"
"time"
ory "github.com/ory/client-go"
"github.com/ory/x/urlx"
)
// ErrCustomDomainNotFound is returned when a custom domain ID is not found in the project's domain list.
var ErrCustomDomainNotFound = errors.New("custom domain not found")
// ErrConsoleClientNotConfigured is returned when a console API method is called
// without a workspace API key configured. Callers can check with errors.Is.
var ErrConsoleClientNotConfigured = errors.New("console API client not configured")
const (
// maxRetries is the maximum number of retry attempts for rate-limited requests.
maxRetries = 3
// initialBackoff is the initial backoff duration before first retry.
initialBackoff = 1 * time.Second
)
const (
// DefaultConsoleAPIURL is the default Ory Console API URL.
DefaultConsoleAPIURL = "https://api.console.ory.sh"
// DefaultProjectAPIURL is the default Ory Project API URL template.
// The %s placeholder is replaced with the project slug.
DefaultProjectAPIURL = "https://%s.projects.oryapis.com"
// schemeHTTPS and schemeHTTP are used in URL scheme validation.
schemeHTTPS = "https"
schemeHTTP = "http"
)
// oryAPIError represents the error structure returned by Ory APIs.
type oryAPIError struct {
Error struct {
ID string `json:"id"`
Code int `json:"code"`
Status string `json:"status"`
Request string `json:"request"`
Reason string `json:"reason"`
Message string `json:"message"`
Details struct {
Feature string `json:"feature"`
} `json:"details"`
} `json:"error"`
}
// OryErrorDebugInfo contains comprehensive debug information for API errors.
type OryErrorDebugInfo struct {
StatusCode int
ErrorID string
ErrorMessage string
ErrorReason string
RequestID string
Feature string
RawBody string
ErrorType string
}
// String formats the debug info for logging.
func (d OryErrorDebugInfo) String() string {
return fmt.Sprintf(`
======================================================================
ORY API ERROR DEBUG INFO
======================================================================
Error Type: %s
Status Code: %d
Error ID: %s
Error Message: %s
Error Reason: %s
Request ID: %s
Feature: %s
----------------------------------------------------------------------
Raw Response Body:
%s
----------------------------------------------------------------------
NOTE: Provide the Request ID to Ory support for debugging.
======================================================================`,
d.ErrorType, d.StatusCode, d.ErrorID, d.ErrorMessage,
d.ErrorReason, d.RequestID, d.Feature, d.RawBody)
}
// extractDebugInfo extracts comprehensive debug information from an error.
func extractDebugInfo(err error) OryErrorDebugInfo {
info := OryErrorDebugInfo{
ErrorType: fmt.Sprintf("%T", err),
}
if err == nil {
return info
}
// Try to extract the error body from GenericOpenAPIError
var bodyStr string
var apiErr *ory.GenericOpenAPIError
if errors.As(err, &apiErr) {
bodyStr = string(apiErr.Body())
info.RawBody = bodyStr
} else {
// Try to find JSON in the error string
errStr := err.Error()
info.RawBody = errStr
if idx := strings.Index(errStr, "{"); idx >= 0 {
bodyStr = errStr[idx:]
}
}
if bodyStr == "" {
return info
}
var parsed oryAPIError
if jsonErr := json.Unmarshal([]byte(bodyStr), &parsed); jsonErr == nil {
info.StatusCode = parsed.Error.Code
info.ErrorID = parsed.Error.ID
info.ErrorMessage = parsed.Error.Message
info.ErrorReason = parsed.Error.Reason
info.RequestID = parsed.Error.Request
info.Feature = parsed.Error.Details.Feature
}
return info
}
// parseFeatureError attempts to extract feature availability info from an error.
// Returns the feature name and reason if this is a feature_not_available error.
func parseFeatureError(err error) (feature string, reason string, requestID string, ok bool) {
if err == nil {
return "", "", "", false
}
// Try to extract the error body from GenericOpenAPIError
var bodyStr string
var apiErr *ory.GenericOpenAPIError
if errors.As(err, &apiErr) {
bodyStr = string(apiErr.Body())
} else {
// Try to find JSON in the error string
errStr := err.Error()
if idx := strings.Index(errStr, "{"); idx >= 0 {
bodyStr = errStr[idx:]
}
}
if bodyStr == "" {
return "", "", "", false
}
var parsed oryAPIError
if jsonErr := json.Unmarshal([]byte(bodyStr), &parsed); jsonErr != nil {
return "", "", "", false
}
if parsed.Error.ID == "feature_not_available" {
return parsed.Error.Details.Feature, parsed.Error.Reason, parsed.Error.Request, true
}
return "", "", parsed.Error.Request, false
}
// wrapAPIError enhances API errors with more helpful context.
// It extracts debug information and provides actionable error messages.
func wrapAPIError(err error, operation string) error {
if err == nil {
return nil
}
// Extract debug info for all errors
debugInfo := extractDebugInfo(err)
// Check for feature availability errors first
if feature, reason, requestID, ok := parseFeatureError(err); ok {
return fmt.Errorf("%s: feature '%s' not available on current plan.\n"+
"Reason: %s\n"+
"Request ID: %s (provide this to Ory support)\n"+
"\nDebug Info:%s",
operation, feature, reason, requestID, debugInfo.String())
}
errStr := err.Error()
// EOF errors typically mean the API closed the connection without a response.
// This often happens when a feature requires an enterprise plan.
if errors.Is(err, io.EOF) || strings.Contains(errStr, "EOF") || strings.Contains(errStr, "error reading from server") {
return fmt.Errorf("%s: connection closed by server (EOF). This may indicate:\n"+
" - The feature requires an Ory Network enterprise plan (e.g., B2B Organizations)\n"+
" - Invalid or expired API credentials\n"+
" - Network connectivity issues\n"+
"Request ID: %s\n"+
"Original error: %w",
operation, debugInfo.RequestID, err)
}
// Check for common HTTP error patterns
if strings.Contains(errStr, "401") || strings.Contains(errStr, "Unauthorized") {
return fmt.Errorf("%s: unauthorized (401).\n"+
"Check that your API key is valid and has the required permissions.\n"+
"Request ID: %s\n"+
"Original error: %w",
operation, debugInfo.RequestID, err)
}
if strings.Contains(errStr, "403") || strings.Contains(errStr, "Forbidden") {
return fmt.Errorf("%s: forbidden (403).\n"+
"Your API key may not have permission for this operation, or the feature may require an enterprise plan.\n"+
"Request ID: %s\n"+
"Error Reason: %s\n"+
"Original error: %w",
operation, debugInfo.RequestID, debugInfo.ErrorReason, err)
}
if strings.Contains(errStr, "404") || strings.Contains(errStr, "Not Found") {
return fmt.Errorf("%s: resource not found (404).\n"+
"Verify the resource ID and project configuration.\n"+
"Request ID: %s\n"+
"Original error: %w",
operation, debugInfo.RequestID, err)
}
// For any other error, include the request ID if available
if debugInfo.RequestID != "" {
return fmt.Errorf("%s: %w (Request ID: %s)", operation, err, debugInfo.RequestID)
}
return err
}
// isRateLimitError checks if the error is a rate limit (429) error.
func isRateLimitError(err error) bool {
if err == nil {
return false
}
errStr := err.Error()
return strings.Contains(errStr, "429") || strings.Contains(errStr, "Too Many Requests")
}
// isRetryableError checks if the error is a server error (5xx) that should be retried.
func isRetryableError(err error) bool {
if err == nil {
return false
}
errStr := err.Error()
return strings.Contains(errStr, "500") ||
strings.Contains(errStr, "502") ||
strings.Contains(errStr, "503") ||
strings.Contains(errStr, "504") ||
strings.Contains(errStr, "Internal Server Error") ||
strings.Contains(errStr, "Bad Gateway") ||
strings.Contains(errStr, "Service Unavailable") ||
strings.Contains(errStr, "Gateway Timeout")
}
// IsTransientError reports whether err is a transient API error (5xx or 429)
// that is safe to retry, as opposed to a permanent error (4xx auth/permission)
// that should fail fast.
func IsTransientError(err error) bool {
return isRetryableError(err) || isRateLimitError(err)
}
// retryWithBackoff executes a function with exponential backoff on rate limit errors.
func retryWithBackoff[T any](ctx context.Context, operation string, fn func() (T, error)) (T, error) {
var result T
var err error
backoff := initialBackoff
for attempt := 0; attempt <= maxRetries; attempt++ {
result, err = fn()
if err == nil {
return result, nil
}
if !isRateLimitError(err) {
return result, err
}
if attempt == maxRetries {
return result, fmt.Errorf("%s: rate limit exceeded after %d retries: %w", operation, maxRetries, err)
}
// Wait before retrying
select {
case <-ctx.Done():
return result, ctx.Err()
case <-time.After(backoff):
backoff *= 2 // Exponential backoff
}
}
return result, err
}
// OryClientConfig holds configuration for the Ory API client.
type OryClientConfig struct {
WorkspaceAPIKey string
ProjectAPIKey string
ProjectID string
ProjectSlug string
WorkspaceID string
ConsoleAPIURL string
ProjectAPIURL string // URL template with %s placeholder for slug (e.g., "https://%s.projects.oryapis.com")
UserAgent string
}
// OryClient wraps the Ory SDK clients.
// Ory Network uses two different APIs:
// 1. Console API (api.console.ory.sh) - for projects, workspaces, organizations
// 2. Project API ({slug}.projects.oryapis.com) - for identities, OAuth2 clients
type OryClient struct {
config OryClientConfig
// Console API client (for organizations, projects, workspaces)
consoleClient *ory.APIClient
// Project API client (for identities, OAuth2)
projectClient *ory.APIClient
projectClientMu sync.Mutex
// cachedProjects stores PatchProject responses to avoid stale GetProject reads.
// The Ory API has eventual consistency: GetProject may return stale data
// immediately after PatchProject. This cache ensures Read operations
// see the latest state after Create/Update.
cachedProjects sync.Map
// cachedSlugs caches project ID -> slug mappings resolved via the console API.
// This avoids redundant API calls when multiple CRUD operations resolve the
// same project_id within a single Terraform run.
cachedSlugs sync.Map
}
// NewOryClient creates a new Ory API client.
func NewOryClient(cfg OryClientConfig) (*OryClient, error) {
client := &OryClient{config: cfg}
// Initialize console client if workspace API key is provided
if cfg.WorkspaceAPIKey != "" {
// Validate the console API URL
parsedURL, err := urlx.Parse(cfg.ConsoleAPIURL)
if err != nil {
return nil, fmt.Errorf("invalid console API URL %q: %w", cfg.ConsoleAPIURL, err)
}
if parsedURL.Scheme != schemeHTTPS && parsedURL.Scheme != schemeHTTP {
return nil, fmt.Errorf("invalid console API URL %q: must use http or https scheme", cfg.ConsoleAPIURL)
}
consoleCfg := ory.NewConfiguration()
consoleCfg.UserAgent = cfg.UserAgent
consoleCfg.Host = parsedURL.Host
consoleCfg.Scheme = parsedURL.Scheme
consoleCfg.Servers = ory.ServerConfigurations{
{URL: cfg.ConsoleAPIURL},
}
consoleCfg.AddDefaultHeader("Authorization", "Bearer "+cfg.WorkspaceAPIKey)
// CRITICAL: The SDK has hardcoded operation-specific server URLs for all
// console API operations (ProjectAPI, WorkspaceAPI, EventsAPI). These override
// the main Servers config. We must override each operation to use our custom URL.
consoleServer := ory.ServerConfigurations{{URL: cfg.ConsoleAPIURL}}
consoleCfg.OperationServers = map[string]ory.ServerConfigurations{
// ProjectAPI operations
"ProjectAPIService.CreateProject": consoleServer,
"ProjectAPIService.GetProject": consoleServer,
"ProjectAPIService.ListProjects": consoleServer,
"ProjectAPIService.PatchProject": consoleServer,
"ProjectAPIService.PatchProjectWithRevision": consoleServer,
"ProjectAPIService.PurgeProject": consoleServer,
"ProjectAPIService.SetProject": consoleServer,
"ProjectAPIService.GetProjectMembers": consoleServer,
"ProjectAPIService.RemoveProjectMember": consoleServer,
"ProjectAPIService.CreateProjectApiKey": consoleServer,
"ProjectAPIService.DeleteProjectApiKey": consoleServer,
"ProjectAPIService.ListProjectApiKeys": consoleServer,
"ProjectAPIService.CreateOrganization": consoleServer,
"ProjectAPIService.DeleteOrganization": consoleServer,
"ProjectAPIService.GetOrganization": consoleServer,
"ProjectAPIService.ListOrganizations": consoleServer,
"ProjectAPIService.UpdateOrganization": consoleServer,
"ProjectAPIService.CreateOrganizationOnboardingPortalLink": consoleServer,
"ProjectAPIService.DeleteOrganizationOnboardingPortalLink": consoleServer,
"ProjectAPIService.GetOrganizationOnboardingPortalLinks": consoleServer,
"ProjectAPIService.UpdateOrganizationOnboardingPortalLink": consoleServer,
// WorkspaceAPI operations
"WorkspaceAPIService.CreateWorkspace": consoleServer,
"WorkspaceAPIService.GetWorkspace": consoleServer,
"WorkspaceAPIService.ListWorkspaces": consoleServer,
"WorkspaceAPIService.UpdateWorkspace": consoleServer,
"WorkspaceAPIService.ListWorkspaceProjects": consoleServer,
// EventsAPI operations
"EventsAPIService.CreateEventStream": consoleServer,
"EventsAPIService.DeleteEventStream": consoleServer,
"EventsAPIService.ListEventStreams": consoleServer,
"EventsAPIService.SetEventStream": consoleServer,
}
client.consoleClient = ory.NewAPIClient(consoleCfg)
}
// Initialize project client if project API key and slug are provided
if cfg.ProjectAPIKey != "" && cfg.ProjectSlug != "" {
// Use configurable URL template, defaulting to production
projectAPIURL := cfg.ProjectAPIURL
if projectAPIURL == "" {
projectAPIURL = DefaultProjectAPIURL
}
// Format the URL template with the project slug and validate it
formattedURL := fmt.Sprintf(projectAPIURL, cfg.ProjectSlug)
parsedURL, err := urlx.Parse(formattedURL)
if err != nil {
return nil, fmt.Errorf("invalid project API URL %q: %w", formattedURL, err)
}
if parsedURL.Scheme != schemeHTTPS && parsedURL.Scheme != schemeHTTP {
return nil, fmt.Errorf("invalid project API URL %q: must use http or https scheme", formattedURL)
}
projectCfg := ory.NewConfiguration()
projectCfg.UserAgent = cfg.UserAgent
projectCfg.Host = parsedURL.Host
projectCfg.Scheme = parsedURL.Scheme
projectCfg.Servers = ory.ServerConfigurations{
{URL: formattedURL},
}
projectCfg.AddDefaultHeader("Authorization", "Bearer "+cfg.ProjectAPIKey)
client.projectClient = ory.NewAPIClient(projectCfg)
}
return client, nil
}
// ConsoleAPI returns the console API client.
func (c *OryClient) ConsoleAPI() *ory.APIClient {
return c.consoleClient
}
// ProjectAPI returns the project API client.
func (c *OryClient) ProjectAPI() *ory.APIClient {
return c.projectClient
}
// Config returns the client configuration.
func (c *OryClient) Config() OryClientConfig {
return c.config
}
// ProjectID returns the configured project ID.
func (c *OryClient) ProjectID() string {
return c.config.ProjectID
}
// WorkspaceID returns the configured workspace ID.
func (c *OryClient) WorkspaceID() string {
return c.config.WorkspaceID
}
// ResolveProjectSlug resolves a project ID to its slug via the console API.
// Results are cached to avoid redundant API calls within a single Terraform run.
func (c *OryClient) ResolveProjectSlug(ctx context.Context, projectID string) (string, error) {
if projectID == "" {
return "", fmt.Errorf("project_id must not be empty")
}
if slug, ok := c.cachedSlugs.Load(projectID); ok {
return slug.(string), nil
}
if c.consoleClient == nil {
return "", fmt.Errorf("console API client not configured: workspace_api_key is required to resolve project_id to slug")
}
project, err := c.GetProject(ctx, projectID)
if err != nil {
return "", fmt.Errorf("resolving project slug for project %s: %w", projectID, err)
}
slug := project.GetSlug()
c.cachedSlugs.Store(projectID, slug)
return slug, nil
}
// ProjectClientForProject returns a project-scoped client for the given project ID.
// It resolves the project slug via the console API and uses the provider's project API key.
func (c *OryClient) ProjectClientForProject(ctx context.Context, projectID string) (*OryClient, error) {
slug, err := c.ResolveProjectSlug(ctx, projectID)
if err != nil {
return nil, err
}
apiKey := c.config.ProjectAPIKey
if apiKey == "" {
return nil, fmt.Errorf("project_api_key is required for project API operations (JWK, OAuth2, etc.): " +
"set it on the provider or via ORY_PROJECT_API_KEY environment variable")
}
return c.WithProjectCredentials(slug, apiKey), nil
}
// WithProjectCredentials returns a new OryClient that uses the given project
// credentials. The returned client shares the console client with the parent
// but has its own isolated project client (lazily initialized).
// This avoids race conditions from mutating shared state and is safe for
// concurrent use by multiple resources with different credentials.
func (c *OryClient) WithProjectCredentials(slug, apiKey string) *OryClient {
newConfig := c.config
newConfig.ProjectSlug = slug
newConfig.ProjectAPIKey = apiKey
return &OryClient{
config: newConfig,
consoleClient: c.consoleClient,
// projectClient is nil — ensureProjectClient will lazily initialize it
// projectClientMu and cachedProjects are zero-valued (valid)
}
}
// ensureProjectClient lazily initializes the project API client.
// Returns an error with a helpful message if credentials are missing.
func (c *OryClient) ensureProjectClient() error {
c.projectClientMu.Lock()
defer c.projectClientMu.Unlock()
if c.projectClient != nil {
return nil
}
if c.config.ProjectSlug == "" || c.config.ProjectAPIKey == "" {
return fmt.Errorf("project API client not configured: project_slug and project_api_key are required. " +
"Set them on the provider or pass them as resource-level attributes (project_slug, project_api_key)")
}
projectAPIURL := c.config.ProjectAPIURL
if projectAPIURL == "" {
projectAPIURL = DefaultProjectAPIURL
}
formattedURL := fmt.Sprintf(projectAPIURL, c.config.ProjectSlug)
parsedURL, err := urlx.Parse(formattedURL)
if err != nil {
return fmt.Errorf("invalid project API URL %q: %w", formattedURL, err)
}
if parsedURL.Scheme != schemeHTTPS && parsedURL.Scheme != schemeHTTP {
return fmt.Errorf("invalid project API URL %q: must use http or https scheme", formattedURL)
}
projectCfg := ory.NewConfiguration()
projectCfg.UserAgent = c.config.UserAgent
projectCfg.Host = parsedURL.Host
projectCfg.Scheme = parsedURL.Scheme
projectCfg.Servers = ory.ServerConfigurations{
{URL: formattedURL},
}
projectCfg.AddDefaultHeader("Authorization", "Bearer "+c.config.ProjectAPIKey)
c.projectClient = ory.NewAPIClient(projectCfg)
return nil
}
// requireConsoleClient returns an error wrapping ErrConsoleClientNotConfigured
// if the console API client is not initialized (no workspace API key).
// This prevents nil pointer panics when methods are called without credentials.
func (c *OryClient) requireConsoleClient(operation string) error {
if c.consoleClient == nil {
return fmt.Errorf("%s: %w. "+
"Set workspace_api_key (ORY_WORKSPACE_API_KEY) in the provider configuration",
operation, ErrConsoleClientNotConfigured)
}
return nil
}
// =============================================================================
// Project Operations (Console API)
// =============================================================================
// CreateProject creates a new Ory project.
// Returns the project, HTTP response (for status code inspection), and any error.
func (c *OryClient) CreateProject(ctx context.Context, name, environment, homeRegion string) (*ory.Project, *http.Response, error) {
if err := c.requireConsoleClient("creating project"); err != nil {
return nil, nil, err
}
body := ory.CreateProjectBody{
Name: name,
Environment: environment,
}
if c.config.WorkspaceID != "" {
body.WorkspaceId = ory.PtrString(c.config.WorkspaceID)
}
if homeRegion != "" {
body.HomeRegion = &homeRegion
}
project, httpResp, err := c.consoleClient.ProjectAPI.CreateProject(ctx).CreateProjectBody(body).Execute()
return project, httpResp, err
}
// GetProject retrieves a project by ID.
func (c *OryClient) GetProject(ctx context.Context, projectID string) (*ory.Project, error) {
if err := c.requireConsoleClient("getting project"); err != nil {
return nil, err
}
project, httpResp, err := c.consoleClient.ProjectAPI.GetProject(ctx, projectID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return project, err
}
// DeleteProject purges a project.
func (c *OryClient) DeleteProject(ctx context.Context, projectID string) error {
if err := c.requireConsoleClient("deleting project"); err != nil {
return err
}
httpResp, err := c.consoleClient.ProjectAPI.PurgeProject(ctx, projectID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return err
}
// PatchProject applies JSON Patch operations to a project.
// The response is automatically cached to avoid stale GetProject reads.
func (c *OryClient) PatchProject(ctx context.Context, projectID string, patches []ory.JsonPatch) (*ory.SuccessfulProjectUpdate, error) {
if err := c.requireConsoleClient("patching project"); err != nil {
return nil, err
}
result, httpResp, err := c.consoleClient.ProjectAPI.PatchProject(ctx, projectID).
JsonPatch(patches).
Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
if err == nil && result != nil {
project := result.GetProject()
c.cachedProjects.Store(projectID, &project)
}
return result, err
}
// GetCachedProject returns the cached project state from the last PatchProject call.
// Returns nil if no cached state exists for this project.
func (c *OryClient) GetCachedProject(projectID string) *ory.Project {
if v, ok := c.cachedProjects.Load(projectID); ok {
return v.(*ory.Project)
}
return nil
}
// =============================================================================
// Workspace Operations (Console API)
// =============================================================================
// CreateWorkspace creates a new workspace.
func (c *OryClient) CreateWorkspace(ctx context.Context, name string) (*ory.Workspace, error) {
if err := c.requireConsoleClient("creating workspace"); err != nil {
return nil, err
}
body := ory.CreateWorkspaceBody{
Name: name,
}
workspace, httpResp, err := c.consoleClient.WorkspaceAPI.CreateWorkspace(ctx).CreateWorkspaceBody(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return workspace, err
}
// GetWorkspace retrieves a workspace by ID.
// Note: Due to Ory API permission limitations, some API keys can list workspaces
// but not get a specific workspace. We fall back to listing and filtering if
// the direct GET fails with 403.
func (c *OryClient) GetWorkspace(ctx context.Context, workspaceID string) (*ory.Workspace, error) {
if err := c.requireConsoleClient("getting workspace"); err != nil {
return nil, err
}
workspace, httpResp, err := c.consoleClient.WorkspaceAPI.GetWorkspace(ctx, workspaceID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
if err != nil {
// Check if it's a 403 error - try fallback to list
errStr := err.Error()
if strings.Contains(errStr, "403") || strings.Contains(errStr, "Forbidden") {
// Fall back to listing workspaces and finding by ID
listResp, listHttpResp, listErr := c.consoleClient.WorkspaceAPI.ListWorkspaces(ctx).Execute()
if listHttpResp != nil {
_ = listHttpResp.Body.Close()
}
if listErr != nil {
return nil, err // Return original error
}
for _, w := range listResp.Workspaces {
if w.GetId() == workspaceID {
return &w, nil
}
}
return nil, fmt.Errorf("workspace %s not found", workspaceID)
}
return nil, err
}
return workspace, nil
}
// UpdateWorkspace updates a workspace.
func (c *OryClient) UpdateWorkspace(ctx context.Context, workspaceID, name string) (*ory.Workspace, error) {
if err := c.requireConsoleClient("updating workspace"); err != nil {
return nil, err
}
body := ory.UpdateWorkspaceBody{
Name: name,
}
workspace, httpResp, err := c.consoleClient.WorkspaceAPI.UpdateWorkspace(ctx, workspaceID).UpdateWorkspaceBody(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return workspace, err
}
// GetProjectEnvironment retrieves the environment (prod, stage, dev) for a project.
func (c *OryClient) GetProjectEnvironment(ctx context.Context, projectID string) (string, error) {
if c.consoleClient == nil {
return "", fmt.Errorf("console API client not configured")
}
project, httpResp, err := c.consoleClient.ProjectAPI.GetProject(ctx, projectID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
if err != nil {
return "", err
}
return project.GetEnvironment(), nil
}
// =============================================================================
// Organization Operations (Console API with workspace key)
// Organizations require B2B features and a prod/stage project environment.
// =============================================================================
// CreateOrganization creates a new organization.
// Note: Organizations require:
// - An Ory Network plan with B2B features
// - Project environment set to "prod" or "stage" (NOT "dev")
func (c *OryClient) CreateOrganization(ctx context.Context, projectID, label string, domains []string) (*ory.Organization, error) {
if c.consoleClient == nil {
return nil, fmt.Errorf("creating organization: console API client not configured. " +
"Organizations require workspace_api_key (ORY_WORKSPACE_API_KEY) to be set")
}
// Ory API requires domains to be an array, not null
if domains == nil {
domains = []string{}
}
body := ory.OrganizationBody{
Label: ory.PtrString(label),
Domains: domains,
}
org, httpResp, err := c.consoleClient.ProjectAPI.CreateOrganization(ctx, projectID).OrganizationBody(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
if err != nil {
return nil, wrapAPIError(err, "creating organization")
}
return org, nil
}
// GetOrganization retrieves an organization by ID.
// Includes retry logic to handle eventual consistency after organization creation.
func (c *OryClient) GetOrganization(ctx context.Context, projectID, orgID string) (*ory.Organization, error) {
if c.consoleClient == nil {
return nil, fmt.Errorf("reading organization: console API client not configured. " +
"Set workspace_api_key (ORY_WORKSPACE_API_KEY)")
}
// Retry with backoff for 404 errors (eventual consistency)
// Use 5 attempts with delays: 1s, 2s, 4s, 8s to handle slow propagation
var lastErr error
for attempt := 0; attempt < 5; attempt++ {
resp, httpResp, err := c.consoleClient.ProjectAPI.GetOrganization(ctx, projectID, orgID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
if err == nil {
return &resp.Organization, nil
}
lastErr = err
errStr := err.Error()
// Only retry on 404 errors (eventual consistency)
if !strings.Contains(errStr, "404") && !strings.Contains(errStr, "Not Found") {
return nil, wrapAPIError(err, "reading organization")
}
// Wait before retry (exponential backoff: 1s, 2s, 4s, 8s)
if attempt < 4 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Duration(1<<attempt) * time.Second):
}
}
}
return nil, wrapAPIError(lastErr, "reading organization")
}
// UpdateOrganization updates an organization.
func (c *OryClient) UpdateOrganization(ctx context.Context, projectID, orgID, label string, domains []string) (*ory.Organization, error) {
if c.consoleClient == nil {
return nil, fmt.Errorf("updating organization: console API client not configured. " +
"Set workspace_api_key (ORY_WORKSPACE_API_KEY)")
}
// Ory API requires domains to be an array, not null
if domains == nil {
domains = []string{}
}
body := ory.OrganizationBody{
Label: ory.PtrString(label),
Domains: domains,
}
// Retry with backoff for 404 errors (eventual consistency)
// Use 5 attempts with delays: 1s, 2s, 4s, 8s to handle slow propagation
var lastErr error
for attempt := 0; attempt < 5; attempt++ {
org, httpResp, err := c.consoleClient.ProjectAPI.UpdateOrganization(ctx, projectID, orgID).OrganizationBody(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
if err == nil {
return org, nil
}
lastErr = err
errStr := err.Error()
// Only retry on 404 errors (eventual consistency)
if !strings.Contains(errStr, "404") && !strings.Contains(errStr, "Not Found") {
return nil, wrapAPIError(err, "updating organization")
}
// Wait before retry (exponential backoff: 1s, 2s, 4s, 8s)
if attempt < 4 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Duration(1<<attempt) * time.Second):
}
}
}
return nil, wrapAPIError(lastErr, "updating organization")
}
// DeleteOrganization deletes an organization.
func (c *OryClient) DeleteOrganization(ctx context.Context, projectID, orgID string) error {
if c.consoleClient == nil {
return fmt.Errorf("deleting organization: console API client not configured. " +
"Set workspace_api_key (ORY_WORKSPACE_API_KEY)")
}
httpResp, err := c.consoleClient.ProjectAPI.DeleteOrganization(ctx, projectID, orgID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return wrapAPIError(err, "deleting organization")
}
// =============================================================================
// Identity Operations (Project API)
// =============================================================================
// CreateIdentity creates a new identity with retry on rate limit.
func (c *OryClient) CreateIdentity(ctx context.Context, body ory.CreateIdentityBody) (*ory.Identity, error) {
if err := c.ensureProjectClient(); err != nil {
return nil, fmt.Errorf("creating identity: %w", err)
}
return retryWithBackoff(ctx, "creating identity", func() (*ory.Identity, error) {
identity, httpResp, err := c.projectClient.IdentityAPI.CreateIdentity(ctx).CreateIdentityBody(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return identity, err
})
}
// GetIdentity retrieves an identity by ID with retry on rate limit.
func (c *OryClient) GetIdentity(ctx context.Context, identityID string) (*ory.Identity, error) {
if err := c.ensureProjectClient(); err != nil {
return nil, fmt.Errorf("getting identity: %w", err)
}
return retryWithBackoff(ctx, "getting identity", func() (*ory.Identity, error) {
identity, httpResp, err := c.projectClient.IdentityAPI.GetIdentity(ctx, identityID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return identity, err
})
}
// UpdateIdentity updates an identity with retry on rate limit.
func (c *OryClient) UpdateIdentity(ctx context.Context, identityID string, body ory.UpdateIdentityBody) (*ory.Identity, error) {
if err := c.ensureProjectClient(); err != nil {
return nil, fmt.Errorf("updating identity: %w", err)
}
return retryWithBackoff(ctx, "updating identity", func() (*ory.Identity, error) {
identity, httpResp, err := c.projectClient.IdentityAPI.UpdateIdentity(ctx, identityID).UpdateIdentityBody(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return identity, err
})
}
// DeleteIdentity deletes an identity with retry on rate limit.
func (c *OryClient) DeleteIdentity(ctx context.Context, identityID string) error {
if err := c.ensureProjectClient(); err != nil {
return fmt.Errorf("deleting identity: %w", err)
}
_, err := retryWithBackoff(ctx, "deleting identity", func() (struct{}, error) {
httpResp, err := c.projectClient.IdentityAPI.DeleteIdentity(ctx, identityID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return struct{}{}, err
})
return err
}
// =============================================================================
// OAuth2 Client Operations (Project API)
// =============================================================================
// CreateOAuth2Client creates a new OAuth2 client.
func (c *OryClient) CreateOAuth2Client(ctx context.Context, oauthClient ory.OAuth2Client) (*ory.OAuth2Client, error) {
if err := c.ensureProjectClient(); err != nil {
return nil, fmt.Errorf("creating OAuth2 client: %w", err)
}
result, httpResp, err := c.projectClient.OAuth2API.CreateOAuth2Client(ctx).OAuth2Client(oauthClient).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return result, err
}
// GetOAuth2Client retrieves an OAuth2 client by ID.
func (c *OryClient) GetOAuth2Client(ctx context.Context, clientID string) (*ory.OAuth2Client, error) {
if err := c.ensureProjectClient(); err != nil {
return nil, fmt.Errorf("reading OAuth2 client: %w", err)
}
oauthClient, httpResp, err := c.projectClient.OAuth2API.GetOAuth2Client(ctx, clientID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return oauthClient, err
}
// UpdateOAuth2Client updates an OAuth2 client.
func (c *OryClient) UpdateOAuth2Client(ctx context.Context, clientID string, oauthClient ory.OAuth2Client) (*ory.OAuth2Client, error) {
if err := c.ensureProjectClient(); err != nil {
return nil, fmt.Errorf("updating OAuth2 client: %w", err)
}
result, httpResp, err := c.projectClient.OAuth2API.SetOAuth2Client(ctx, clientID).OAuth2Client(oauthClient).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return result, err
}
// DeleteOAuth2Client deletes an OAuth2 client.
func (c *OryClient) DeleteOAuth2Client(ctx context.Context, clientID string) error {
if err := c.ensureProjectClient(); err != nil {
return fmt.Errorf("deleting OAuth2 client: %w", err)
}
httpResp, err := c.projectClient.OAuth2API.DeleteOAuth2Client(ctx, clientID).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()
}
return err
}
// =============================================================================
// Project API Key Operations (Console API)
// =============================================================================
// CreateProjectAPIKey creates a new API key for a project.
func (c *OryClient) CreateProjectAPIKey(ctx context.Context, projectID string, body ory.CreateProjectApiKeyRequest) (*ory.ProjectApiKey, error) {
if err := c.requireConsoleClient("creating project API key"); err != nil {
return nil, err
}
key, httpResp, err := c.consoleClient.ProjectAPI.CreateProjectApiKey(ctx, projectID).CreateProjectApiKeyRequest(body).Execute()
if httpResp != nil {
_ = httpResp.Body.Close()