-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathresource_okta_app_signon_policy_rules.go
More file actions
1804 lines (1753 loc) · 72.8 KB
/
Copy pathresource_okta_app_signon_policy_rules.go
File metadata and controls
1804 lines (1753 loc) · 72.8 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 idaas
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"time"
"github.com/cenkalti/backoff/v5"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/okta/terraform-provider-okta/okta/config"
"github.com/okta/terraform-provider-okta/okta/utils"
"github.com/okta/terraform-provider-okta/sdk"
)
const (
// apiRetryTimeout is the maximum time to wait for API operations with retries.
apiRetryTimeout = 30 * time.Second
// ruleTypeAccessPolicy is the Okta API type for access policy rules.
ruleTypeAccessPolicy = "ACCESS_POLICY"
)
// Validation values for rule attributes.
var (
validStatuses = []string{"ACTIVE", "INACTIVE"}
validNetworkConnections = []string{"ANYWHERE", "ZONE", "ON_NETWORK", "OFF_NETWORK"}
validAccessTypes = []string{"ALLOW", "DENY"}
validFactorModes = []string{"1FA", "2FA"}
validRiskScores = []string{"ANY", "LOW", "MEDIUM", "HIGH"}
validPlatformTypes = []string{"ANY", "MOBILE", "DESKTOP"}
// NOTE: ANY is intentionally excluded. The API silently maps os_type=ANY to
// OTHER on read, which causes a post-apply inconsistency. Users should set
// os_type = "OTHER" directly (with or without os_expression).
validOSTypes = []string{"IOS", "ANDROID", "WINDOWS", "OSX", "MACOS", "CHROMEOS", "OTHER", "LINUX"}
)
var (
_ resource.Resource = &appSignOnPolicyRulesResource{}
_ resource.ResourceWithConfigure = &appSignOnPolicyRulesResource{}
_ resource.ResourceWithImportState = &appSignOnPolicyRulesResource{}
_ resource.ResourceWithValidateConfig = &appSignOnPolicyRulesResource{}
)
// NewAppSignOnPolicyRulesResource creates a new instance of the resource.
func NewAppSignOnPolicyRulesResource() resource.Resource {
return &appSignOnPolicyRulesResource{}
}
// For backward compatibility with existing registration code.
func newAppSignOnPolicyRulesResource() resource.Resource {
return NewAppSignOnPolicyRulesResource()
}
type appSignOnPolicyRulesResource struct {
*config.Config
}
// appSignOnPolicyRulesModel represents the Terraform state for this resource.
type appSignOnPolicyRulesModel struct {
ID types.String `tfsdk:"id"`
PolicyID types.String `tfsdk:"policy_id"`
Rules types.List `tfsdk:"rule"`
}
// policyRuleModel represents a single policy rule in the Terraform state.
type policyRuleModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
System types.Bool `tfsdk:"system"`
Status types.String `tfsdk:"status"`
Priority types.Int64 `tfsdk:"priority"`
GroupsIncluded types.Set `tfsdk:"groups_included"`
GroupsExcluded types.Set `tfsdk:"groups_excluded"`
UsersIncluded types.Set `tfsdk:"users_included"`
UsersExcluded types.Set `tfsdk:"users_excluded"`
NetworkConnection types.String `tfsdk:"network_connection"`
NetworkIncludes types.List `tfsdk:"network_includes"`
NetworkExcludes types.List `tfsdk:"network_excludes"`
DeviceIsRegistered types.Bool `tfsdk:"device_is_registered"`
DeviceIsManaged types.Bool `tfsdk:"device_is_managed"`
DeviceAssurancesIncluded types.Set `tfsdk:"device_assurances_included"`
UserTypesIncluded types.Set `tfsdk:"user_types_included"`
UserTypesExcluded types.Set `tfsdk:"user_types_excluded"`
CustomExpression types.String `tfsdk:"custom_expression"`
Access types.String `tfsdk:"access"`
FactorMode types.String `tfsdk:"factor_mode"`
Type types.String `tfsdk:"type"`
ReAuthenticationFrequency types.String `tfsdk:"re_authentication_frequency"`
InactivityPeriod types.String `tfsdk:"inactivity_period"`
Constraints types.List `tfsdk:"constraints"`
Chains types.List `tfsdk:"chains"`
RiskScore types.String `tfsdk:"risk_score"`
PlatformInclude []platformIncludeModel `tfsdk:"platform_include"`
KeepMeSignedIn []keepMeSignedInModel `tfsdk:"keep_me_signed_in"`
}
// platformIncludeModel represents platform conditions in the rule.
type platformIncludeModel struct {
Type types.String `tfsdk:"type"`
OsType types.String `tfsdk:"os_type"`
OsExpression types.String `tfsdk:"os_expression"`
}
type keepMeSignedInModel struct {
PostAuth types.String `tfsdk:"post_auth"`
PostAuthPromptFrequency types.String `tfsdk:"post_auth_prompt_frequency"`
}
// reauthFrequencyModifier is a plan modifier that suppresses changes to
// re_authentication_frequency when chains contain reauthenticateIn.
type reauthFrequencyModifier struct{}
func (m reauthFrequencyModifier) Description(ctx context.Context) string {
return "Suppresses re_authentication_frequency changes when chains contain reauthenticateIn"
}
func (m reauthFrequencyModifier) MarkdownDescription(ctx context.Context) string {
return "Suppresses re_authentication_frequency changes when chains contain reauthenticateIn"
}
func (m reauthFrequencyModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) {
// Get the parent rule object from the plan
var planRule policyRuleModel
resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, req.Path.ParentPath(), &planRule)...)
if resp.Diagnostics.HasError() {
return
}
// Check if chains contain reauthenticateIn
if !planRule.Chains.IsNull() && !planRule.Chains.IsUnknown() {
var chainStrings []string
planRule.Chains.ElementsAs(ctx, &chainStrings, false)
for _, chainStr := range chainStrings {
if strings.Contains(chainStr, "reauthenticateIn") {
// When chains have reauthenticateIn, the API computes re_authentication_frequency
// If we have a state value, use it to suppress diff (like DiffSuppressFunc)
// Otherwise mark as unknown so first apply accepts whatever API returns
if !req.StateValue.IsNull() && !req.StateValue.IsUnknown() {
resp.PlanValue = req.StateValue
} else {
resp.PlanValue = types.StringUnknown()
}
return
}
}
}
}
// ChainsPlanModifier normalizes the JSON key order of each chains element during
// planning so the plan value always matches the post-apply canonical form.
type ChainsPlanModifier struct{}
func (m ChainsPlanModifier) Description(_ context.Context) string {
return "Normalizes JSON key order in chains elements to prevent inconsistent result after apply"
}
func (m ChainsPlanModifier) MarkdownDescription(ctx context.Context) string {
return m.Description(ctx)
}
func (m ChainsPlanModifier) PlanModifyList(ctx context.Context, req planmodifier.ListRequest, resp *planmodifier.ListResponse) {
if req.PlanValue.IsNull() || req.PlanValue.IsUnknown() {
return
}
var chainStrings []string
resp.Diagnostics.Append(req.PlanValue.ElementsAs(ctx, &chainStrings, false)...)
if resp.Diagnostics.HasError() {
return
}
normalized := make([]string, len(chainStrings))
for i, s := range chainStrings {
var raw map[string]interface{}
if err := json.Unmarshal([]byte(s), &raw); err != nil {
resp.Diagnostics.AddAttributeError(
req.Path,
"Invalid chains JSON",
fmt.Sprintf("chains[%d] is not valid JSON: %s", i, err),
)
return
}
b, _ := json.Marshal(raw)
normalized[i] = string(b)
}
listVal, diags := types.ListValueFrom(ctx, types.StringType, normalized)
resp.Diagnostics.Append(diags...)
if !resp.Diagnostics.HasError() {
resp.PlanValue = listVal
}
}
// ruleIndex provides efficient lookups for rules by name and ID.
type ruleIndex struct {
byName map[string]policyRuleModel
byID map[string]policyRuleModel
}
// newRuleIndex creates a new rule index from a slice of rules.
func newRuleIndex(rules []policyRuleModel) *ruleIndex {
idx := &ruleIndex{
byName: make(map[string]policyRuleModel, len(rules)),
byID: make(map[string]policyRuleModel, len(rules)),
}
for _, rule := range rules {
idx.byName[rule.Name.ValueString()] = rule
if !rule.ID.IsNull() && !rule.ID.IsUnknown() {
idx.byID[rule.ID.ValueString()] = rule
}
}
return idx
}
// findRule looks up a rule by name first, then by ID.
// Name is used as the primary key because it is a Required attribute set
// explicitly by the user in config. The ID is a Computed attribute that
// Terraform injects positionally from state, which can be wrong when the
// state order differs from the config order (e.g. after a rule is added or
// deleted). Falling back to ID handles the rename case where the name has
// changed but the same rule ID is referenced by the plan.
func (idx *ruleIndex) findRule(id, name string) (policyRuleModel, bool) {
if name != "" {
if rule, ok := idx.byName[name]; ok {
return rule, true
}
}
if id != "" {
if rule, ok := idx.byID[id]; ok {
return rule, true
}
}
return policyRuleModel{}, false
}
// nameTracker tracks current name-to-ID mappings for conflict detection.
type nameTracker struct {
nameToID map[string]string
idToName map[string]string
}
// newNameTracker creates a tracker from existing rules.
func newNameTracker(rules []policyRuleModel) *nameTracker {
t := &nameTracker{
nameToID: make(map[string]string, len(rules)),
idToName: make(map[string]string, len(rules)),
}
for _, rule := range rules {
if rule.ID.IsNull() || rule.ID.IsUnknown() {
continue
}
if rule.Name.IsNull() || rule.Name.IsUnknown() {
continue
}
id := rule.ID.ValueString()
name := rule.Name.ValueString()
if name != "" {
t.nameToID[name] = id
t.idToName[id] = name
}
}
return t
}
// hasConflict checks if the target name is held by a different rule.
func (t *nameTracker) hasConflict(targetName, ruleID string) (conflictingID string, hasConflict bool) {
if existingID, ok := t.nameToID[targetName]; ok && existingID != ruleID {
return existingID, true
}
return "", false
}
// updateMapping updates the tracker after a rule rename.
func (t *nameTracker) updateMapping(ruleID, newName string) {
if oldName, ok := t.idToName[ruleID]; ok {
delete(t.nameToID, oldName)
}
t.idToName[ruleID] = newName
t.nameToID[newName] = ruleID
}
func (r *appSignOnPolicyRulesResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
r.Config = resourceConfiguration(req, resp)
}
func (r *appSignOnPolicyRulesResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_app_signon_policy_rules"
}
func (r *appSignOnPolicyRulesResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = r.buildSchema()
}
func (r *appSignOnPolicyRulesResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var data appSignOnPolicyRulesModel
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
var rules []policyRuleModel
resp.Diagnostics.Append(data.Rules.ElementsAs(ctx, &rules, true)...)
if resp.Diagnostics.HasError() {
return
}
seen := make(map[string]int, len(rules))
seenPriority := make(map[int64]int, len(rules))
for i, rule := range rules {
name := rule.Name.ValueString()
if name == "" {
continue
}
if prevIdx, exists := seen[name]; exists {
resp.Diagnostics.AddError(
"Duplicate rule name",
fmt.Sprintf(
"Rule name %q is used by both rule[%d] and rule[%d]. Each rule within a policy must have a unique name.",
name, prevIdx, i,
),
)
} else {
seen[name] = i
}
if !rule.Priority.IsNull() && !rule.Priority.IsUnknown() {
p := rule.Priority.ValueInt64()
if prevIdx, exists := seenPriority[p]; exists {
resp.Diagnostics.AddError(
"Duplicate rule priority",
fmt.Sprintf(
"Priority %d is used by both rule[%d] and rule[%d]. Each rule must have a unique priority.",
p, prevIdx, i,
),
)
} else {
seenPriority[p] = i
}
}
// Warn if conditions are set on a system rule (Catch-all Rule).
// The API rejects condition modifications on system rules.
if name == "Catch-all Rule" && r.hasConditionsSet(rule) {
resp.Diagnostics.AddWarning(
"Conditions ignored for system rule",
fmt.Sprintf(
"rule[%d] %q is a system (Catch-all) rule. Conditions (network, platform, groups, users, "+
"user_types, device, risk_score, custom_expression) cannot be modified on system rules "+
"and will be ignored. Only actions (access, factor_mode, type, re_authentication_frequency, "+
"inactivity_period, constraints) can be configured.",
i, name,
),
)
}
}
}
// hasConditionsSet returns true if any condition attributes are set on the rule.
func (r *appSignOnPolicyRulesResource) hasConditionsSet(rule policyRuleModel) bool {
return (!rule.NetworkConnection.IsNull() && !rule.NetworkConnection.IsUnknown()) ||
(!rule.NetworkIncludes.IsNull() && !rule.NetworkIncludes.IsUnknown()) ||
(!rule.NetworkExcludes.IsNull() && !rule.NetworkExcludes.IsUnknown()) ||
(!rule.GroupsIncluded.IsNull() && !rule.GroupsIncluded.IsUnknown()) ||
(!rule.GroupsExcluded.IsNull() && !rule.GroupsExcluded.IsUnknown()) ||
(!rule.UsersIncluded.IsNull() && !rule.UsersIncluded.IsUnknown()) ||
(!rule.UsersExcluded.IsNull() && !rule.UsersExcluded.IsUnknown()) ||
(!rule.UserTypesIncluded.IsNull() && !rule.UserTypesIncluded.IsUnknown()) ||
(!rule.UserTypesExcluded.IsNull() && !rule.UserTypesExcluded.IsUnknown()) ||
(!rule.DeviceIsRegistered.IsNull() && !rule.DeviceIsRegistered.IsUnknown()) ||
(!rule.DeviceIsManaged.IsNull() && !rule.DeviceIsManaged.IsUnknown()) ||
(!rule.DeviceAssurancesIncluded.IsNull() && !rule.DeviceAssurancesIncluded.IsUnknown()) ||
(!rule.RiskScore.IsNull() && !rule.RiskScore.IsUnknown()) ||
(!rule.CustomExpression.IsNull() && !rule.CustomExpression.IsUnknown()) ||
len(rule.PlatformInclude) > 0
}
func (r *appSignOnPolicyRulesResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan appSignOnPolicyRulesModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
var rules []policyRuleModel
plan.Rules.ElementsAs(ctx, &rules, false)
policyID := plan.PolicyID.ValueString()
client := r.OktaIDaaSClient.OktaSDKSupplementClient()
// Pre-fetch any rules that already exist in Okta for this policy.
// This recovers from a previous interrupted apply where some rules were
// created but state was never written. Without this, re-running apply
// would hit 409 name conflicts on the already-created rules.
existingByName, diags := r.fetchExistingRulesByName(ctx, client, policyID)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Process rules in priority order to ensure correct ordering in Okta.
sortedRules := r.sortRulesByPriority(rules)
createdRules := make([]policyRuleModel, 0, len(sortedRules))
for _, rule := range sortedRules {
// If an existing rule was found by name, inject its ID so createOrAdoptRule
// will update it rather than attempting to create a duplicate.
// Check both IsNull() and IsUnknown() because during a fresh Create (no prior state),
// Computed attributes come through as Unknown, not Null.
if info, found := existingByName[rule.Name.ValueString()]; found {
if rule.ID.IsNull() || rule.ID.IsUnknown() {
rule.ID = types.StringValue(info.ID)
}
}
resultRule, diags := r.createOrAdoptRule(ctx, client, policyID, rule)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
createdRules = append(createdRules, resultRule)
}
// Reorder to match config order (Terraform expects state order to match plan order).
reorderedRules := r.reorderRulesToMatchPlan(createdRules, rules)
plan.ID = plan.PolicyID
// Marshal back to types.List
plan.Rules, diags = types.ListValueFrom(ctx, r.policyRuleObjectType(), reorderedRules)
resp.Diagnostics.Append(diags...)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *appSignOnPolicyRulesResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state appSignOnPolicyRulesModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var rules []policyRuleModel
resp.Diagnostics.Append(state.Rules.ElementsAs(ctx, &rules, false)...)
if resp.Diagnostics.HasError() {
return
}
policyID := state.PolicyID.ValueString()
client := r.OktaIDaaSClient.OktaSDKSupplementClient()
updatedRules := make([]policyRuleModel, 0, len(rules))
for _, rule := range rules {
if rule.ID.IsNull() || rule.ID.IsUnknown() {
continue
}
apiRule, err := r.readRuleFromAPI(ctx, client, policyID, rule.ID.ValueString())
if err != nil {
if strings.Contains(err.Error(), "not found") {
// Rule was deleted outside Terraform - skip it.
continue
}
resp.Diagnostics.AddError("Error reading app sign-on policy rule",
fmt.Sprintf("Could not read rule '%s': %s", rule.ID.ValueString(), err.Error()))
return
}
updatedRules = append(updatedRules, r.updateRuleModelFromAPI(ctx, rule, apiRule))
}
// Marshal back to types.List
state.Rules, resp.Diagnostics = types.ListValueFrom(ctx, r.policyRuleObjectType(), updatedRules)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *appSignOnPolicyRulesResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var state, plan appSignOnPolicyRulesModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
var stateRules, planRules []policyRuleModel
resp.Diagnostics.Append(state.Rules.ElementsAs(ctx, &stateRules, false)...)
resp.Diagnostics.Append(plan.Rules.ElementsAs(ctx, &planRules, false)...)
if resp.Diagnostics.HasError() {
return
}
policyID := plan.PolicyID.ValueString()
client := r.OktaIDaaSClient.OktaSDKSupplementClient()
// Build lookup structures.
stateIndex := newRuleIndex(stateRules)
nameTracker := newNameTracker(stateRules)
plannedNames := r.buildPlannedNamesSet(planRules)
plannedIDs := r.buildPlannedIDsSet(planRules)
// Delete rules removed from plan.
resp.Diagnostics.Append(r.deleteRemovedRules(ctx, client, policyID, stateRules, plannedNames, plannedIDs)...)
if resp.Diagnostics.HasError() {
return
}
// Process rules in priority order.
sortedPlanRules := r.sortRulesByPriority(planRules)
updatedRules := make([]policyRuleModel, 0, len(sortedPlanRules))
for _, planRule := range sortedPlanRules {
resultRule, diags := r.processRuleUpdate(ctx, client, policyID, planRule, stateIndex, nameTracker)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
updatedRules = append(updatedRules, resultRule)
}
// Reorder to match config order.
reorderedRules := r.reorderRulesToMatchPlan(updatedRules, planRules)
plan.ID = plan.PolicyID
// Marshal back to types.List
var diags diag.Diagnostics
plan.Rules, diags = types.ListValueFrom(ctx, r.policyRuleObjectType(), reorderedRules)
resp.Diagnostics.Append(diags...)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *appSignOnPolicyRulesResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state appSignOnPolicyRulesModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var rules []policyRuleModel
resp.Diagnostics.Append(state.Rules.ElementsAs(ctx, &rules, false)...)
if resp.Diagnostics.HasError() {
return
}
policyID := state.PolicyID.ValueString()
client := r.OktaIDaaSClient.OktaSDKSupplementClient()
for _, rule := range rules {
// System rules cannot be deleted.
if rule.System.ValueBool() || rule.ID.IsNull() || rule.ID.IsUnknown() {
continue
}
if err := r.deleteRule(ctx, client, policyID, rule.ID.ValueString()); err != nil {
resp.Diagnostics.AddError("Error deleting app sign-on policy rule",
fmt.Sprintf("Could not delete rule '%s': %s", rule.Name.ValueString(), err.Error()))
return
}
}
}
func (r *appSignOnPolicyRulesResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
policyID := req.ID
client := r.OktaIDaaSClient.OktaSDKSupplementClient()
sdkRules, apiResp, err := client.ListPolicyRules(ctx, policyID)
if err != nil {
resp.Diagnostics.AddError("Error importing app sign-on policy rules",
fmt.Sprintf("Could not list rules for policy '%s': %s", policyID, err.Error()))
return
}
if apiResp != nil && apiResp.StatusCode == http.StatusNotFound {
resp.Diagnostics.AddError("Policy not found",
fmt.Sprintf("Policy '%s' was not found", policyID))
return
}
// Fetch each rule individually to get full AccessPolicyRule details.
importedRules := make([]policyRuleModel, 0, len(sdkRules))
for _, sdkRule := range sdkRules {
apiRule, err := r.readRuleFromAPI(ctx, client, policyID, sdkRule.Id)
if err != nil {
resp.Diagnostics.AddError("Error importing app sign-on policy rule",
fmt.Sprintf("Could not read rule '%s': %s", sdkRule.Name, err.Error()))
return
}
importedRules = append(importedRules, r.convertAPIRuleToModel(ctx, apiRule))
}
state := appSignOnPolicyRulesModel{
ID: types.StringValue(policyID),
PolicyID: types.StringValue(policyID),
}
// Marshal to types.List
state.Rules, resp.Diagnostics = types.ListValueFrom(ctx, r.policyRuleObjectType(), importedRules)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *appSignOnPolicyRulesResource) policyRuleObjectType() types.ObjectType {
return types.ObjectType{
AttrTypes: map[string]attr.Type{
"id": types.StringType,
"name": types.StringType,
"system": types.BoolType,
"status": types.StringType,
"priority": types.Int64Type,
"groups_included": types.SetType{ElemType: types.StringType},
"groups_excluded": types.SetType{ElemType: types.StringType},
"users_included": types.SetType{ElemType: types.StringType},
"users_excluded": types.SetType{ElemType: types.StringType},
"network_connection": types.StringType,
"network_includes": types.ListType{ElemType: types.StringType},
"network_excludes": types.ListType{ElemType: types.StringType},
"device_is_registered": types.BoolType,
"device_is_managed": types.BoolType,
"device_assurances_included": types.SetType{ElemType: types.StringType},
"user_types_included": types.SetType{ElemType: types.StringType},
"user_types_excluded": types.SetType{ElemType: types.StringType},
"custom_expression": types.StringType,
"access": types.StringType,
"factor_mode": types.StringType,
"type": types.StringType,
"re_authentication_frequency": types.StringType,
"inactivity_period": types.StringType,
"constraints": types.ListType{ElemType: types.StringType},
"chains": types.ListType{ElemType: types.StringType},
"risk_score": types.StringType,
"platform_include": types.ListType{
ElemType: types.ObjectType{
AttrTypes: map[string]attr.Type{
"type": types.StringType,
"os_type": types.StringType,
"os_expression": types.StringType,
},
},
},
"keep_me_signed_in": types.ListType{
ElemType: types.ObjectType{
AttrTypes: map[string]attr.Type{
"post_auth": types.StringType,
"post_auth_prompt_frequency": types.StringType,
},
},
},
},
}
}
func (r *appSignOnPolicyRulesResource) buildSchema() schema.Schema {
return schema.Schema{
Description: "Manages multiple app sign-on policy rules for a single policy. " +
"This resource allows you to define all rules for a policy in a single configuration block, " +
"ensuring consistent priority ordering and avoiding drift issues.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
Description: "The ID of this resource (same as policy_id).",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"policy_id": schema.StringAttribute{
Required: true,
Description: "ID of the policy to manage rules for.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
Blocks: map[string]schema.Block{
"rule": schema.ListNestedBlock{
Description: "List of policy rules. Rules are processed in priority order (lowest number = highest priority).",
NestedObject: schema.NestedBlockObject{
Attributes: r.buildRuleAttributes(),
Blocks: map[string]schema.Block{
"platform_include": r.buildPlatformIncludeBlock(),
"keep_me_signed_in": r.buildKeepMeSignedInBlock(),
},
},
},
},
}
}
func (r *appSignOnPolicyRulesResource) buildPlatformIncludeBlock() schema.ListNestedBlock {
return schema.ListNestedBlock{
Description: "Platform conditions to include.",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Optional: true,
Description: "Platform type: ANY, MOBILE, or DESKTOP.",
Validators: []validator.String{stringvalidator.OneOf(validPlatformTypes...)},
},
"os_type": schema.StringAttribute{
Optional: true,
Description: "OS type: ANY, IOS, ANDROID, WINDOWS, OSX, MACOS, CHROMEOS, or OTHER.",
Validators: []validator.String{stringvalidator.OneOf(validOSTypes...)},
},
"os_expression": schema.StringAttribute{
Optional: true,
Computed: true,
// Default to "" so that omitting os_expression in config is equivalent
// to os_expression = "". The Okta API requires the field to be present
// (non-null) when os_type = "OTHER" but always returns null/empty on
// read — mirroring the SDKv2 resource which stored "" implicitly.
Default: stringdefault.StaticString(""),
Description: "Custom OS expression for advanced matching. Required by the API when os_type is OTHER " +
"(leave empty or omit to match any OTHER OS). " +
"The API normalizes empty and wildcard values to null on read; the provider preserves \"\" in state.",
},
},
},
}
}
func (r *appSignOnPolicyRulesResource) buildKeepMeSignedInBlock() schema.ListNestedBlock {
return schema.ListNestedBlock{
Description: "Controls the post-authentication Keep Me Signed In (KMSI) prompt, also known as the \"Option to stay signed in\". Requires the KMSI feature to be enabled on the Okta org.",
Validators: []validator.List{listvalidator.SizeAtMost(1)},
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"post_auth": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("NOT_ALLOWED"),
Description: "Whether the post-authentication KMSI flow is allowed. Valid values: `ALLOWED`, `NOT_ALLOWED`.",
Validators: []validator.String{stringvalidator.OneOf("ALLOWED", "NOT_ALLOWED")},
},
"post_auth_prompt_frequency": schema.StringAttribute{
Optional: true,
Description: "How often the post-auth prompt is presented, as an ISO-8601 duration (e.g. `PT168H`).",
},
},
},
}
}
func (r *appSignOnPolicyRulesResource) buildRuleAttributes() map[string]schema.Attribute {
return map[string]schema.Attribute{
"id": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "ID of the rule. Can be specified to adopt an existing rule during migration.",
},
"name": schema.StringAttribute{
Required: true,
Description: "Policy Rule Name. Must be unique within the policy.",
},
"system": schema.BoolAttribute{
Computed: true,
Description: "Whether this is a system rule (e.g., Catch-all Rule). System rules cannot be modified.",
},
"status": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("ACTIVE"),
Description: "Status of the rule: ACTIVE or INACTIVE.",
Validators: []validator.String{stringvalidator.OneOf(validStatuses...)},
},
"priority": schema.Int64Attribute{
Optional: true,
Description: "Priority of the rule. Lower numbers are evaluated first.",
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"groups_included": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of group IDs to include in this rule.",
},
"groups_excluded": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of group IDs to exclude from this rule.",
},
"users_included": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of user IDs to include in this rule.",
},
"users_excluded": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of user IDs to exclude from this rule.",
},
"network_connection": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "Network selection mode: ANYWHERE, ZONE, ON_NETWORK, or OFF_NETWORK.",
Default: stringdefault.StaticString("ANYWHERE"),
Validators: []validator.String{stringvalidator.OneOf(validNetworkConnections...)},
},
"network_includes": schema.ListAttribute{
Optional: true,
ElementType: types.StringType,
Description: "List of network zone IDs to include.",
},
"network_excludes": schema.ListAttribute{
Optional: true,
ElementType: types.StringType,
Description: "List of network zone IDs to exclude.",
},
"device_is_registered": schema.BoolAttribute{
Optional: true,
Description: "Require device to be registered with Okta Verify.",
},
"device_is_managed": schema.BoolAttribute{
Optional: true,
Description: "Require device to be managed by a device management system.",
},
"device_assurances_included": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of device assurance policy IDs to include.",
},
"user_types_included": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of user type IDs to include.",
},
"user_types_excluded": schema.SetAttribute{
Optional: true,
ElementType: types.StringType,
Description: "Set of user type IDs to exclude.",
},
"custom_expression": schema.StringAttribute{
Optional: true,
Description: "Custom Okta Expression Language condition for advanced matching.",
},
"access": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("ALLOW"),
Description: "Access decision: ALLOW or DENY.",
Validators: []validator.String{stringvalidator.OneOf(validAccessTypes...)},
},
"factor_mode": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("2FA"),
Description: "Number of factors required: 1FA or 2FA.",
Validators: []validator.String{stringvalidator.OneOf(validFactorModes...)},
},
"type": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("ASSURANCE"),
Description: "Verification method type.",
},
"re_authentication_frequency": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "Re-authentication frequency in ISO 8601 duration format (e.g., PT2H for 2 hours). When using authentication chains with reauthenticateIn, this value is computed by the API based on the chain configuration.",
PlanModifiers: []planmodifier.String{
reauthFrequencyModifier{},
},
},
"inactivity_period": schema.StringAttribute{
Optional: true,
Description: "Inactivity period before re-authentication in ISO 8601 duration format.",
},
"constraints": schema.ListAttribute{
Optional: true,
ElementType: types.StringType,
Description: "List of authenticator constraints as JSON-encoded strings.",
},
"chains": schema.ListAttribute{
Optional: true,
ElementType: types.StringType,
Description: "List of authentication method chain objects as JSON-encoded strings. Use with `type = \"AUTH_METHOD_CHAIN\"` only.",
PlanModifiers: []planmodifier.List{
ChainsPlanModifier{},
},
},
"risk_score": schema.StringAttribute{
Optional: true,
Computed: true,
// No static default. Sending a riskScore condition to an org that does
// not have the risk scoring feature causes the API to reject the rule
// with "Invalid condition type specified: riskScore". The condition is
// only sent when the user explicitly configures it (see setAPIRiskScore),
// mirroring the singular okta_app_signon_policy_rule resource.
Description: "Risk score level to match: ANY, LOW, MEDIUM, or HIGH. Only sent to the API when explicitly configured; omit on orgs without the risk scoring feature.",
Validators: []validator.String{stringvalidator.OneOf(validRiskScores...)},
},
}
}
// sortRulesByPriority returns rules sorted by priority (ascending).
// Rules without priority are placed at the end.
func (r *appSignOnPolicyRulesResource) sortRulesByPriority(rules []policyRuleModel) []policyRuleModel {
sorted := make([]policyRuleModel, len(rules))
copy(sorted, rules)
sort.Slice(sorted, func(i, j int) bool {
iPriority := sorted[i].Priority
jPriority := sorted[j].Priority
if iPriority.IsNull() || iPriority.IsUnknown() {
return false
}
if jPriority.IsNull() || jPriority.IsUnknown() {
return true
}
return iPriority.ValueInt64() < jPriority.ValueInt64()
})
return sorted
}
// reorderRulesToMatchPlan reorders processed rules to match the plan's list order.
// This is critical because Terraform expects state order to match plan order.
func (r *appSignOnPolicyRulesResource) reorderRulesToMatchPlan(processedRules, planRules []policyRuleModel) []policyRuleModel {
rulesByName := make(map[string]policyRuleModel, len(processedRules))
for _, rule := range processedRules {
rulesByName[rule.Name.ValueString()] = rule
}
result := make([]policyRuleModel, 0, len(planRules))
for _, planRule := range planRules {
if rule, ok := rulesByName[planRule.Name.ValueString()]; ok {
result = append(result, rule)
}
}
return result
}
// buildPlannedNamesSet creates a set of rule names from the plan.
func (r *appSignOnPolicyRulesResource) buildPlannedNamesSet(rules []policyRuleModel) map[string]bool {
names := make(map[string]bool, len(rules))
for _, rule := range rules {
names[rule.Name.ValueString()] = true
}
return names
}
// existingRuleInfo holds identification data for an existing rule in Okta.
type existingRuleInfo struct {
ID string
IsSystem bool
}
// fetchExistingRulesByName lists all rules currently in Okta for the policy
// and returns a map of rule name → existingRuleInfo. This is used in Create to
// detect rules that were partially created by an interrupted previous apply,
// and to discover system rules (e.g. Catch-all Rule) for adoption.
func (r *appSignOnPolicyRulesResource) fetchExistingRulesByName(ctx context.Context, client *sdk.APISupplement, policyID string) (map[string]existingRuleInfo, diag.Diagnostics) {
var diags diag.Diagnostics
sdkRules, _, err := client.ListPolicyRules(ctx, policyID)
if err != nil {
diags.AddError("Error listing existing policy rules",
fmt.Sprintf("Could not list rules for policy '%s': %s", policyID, err.Error()))
return nil, diags
}
byName := make(map[string]existingRuleInfo, len(sdkRules))
for _, rule := range sdkRules {
byName[rule.Name] = existingRuleInfo{
ID: rule.Id,
IsSystem: rule.System != nil && *rule.System,
}
}
return byName, diags
}
// createOrAdoptRule creates a new rule or adopts an existing one if ID is specified.
func (r *appSignOnPolicyRulesResource) createOrAdoptRule(ctx context.Context, client *sdk.APISupplement, policyID string, rule policyRuleModel) (policyRuleModel, diag.Diagnostics) {
var diags diag.Diagnostics
// If ID is provided, adopt existing rule by updating it.
if !rule.ID.IsNull() && !rule.ID.IsUnknown() && rule.ID.ValueString() != "" {
ruleID := rule.ID.ValueString()
// Read the existing rule from the API to check if it's a system rule.
// This mirrors how okta_app_signon_policy_rule handles system rules:
// build the full payload, then nil out Conditions for system rules.
existingRule, err := r.readRuleFromAPI(ctx, client, policyID, ruleID)
if err != nil {
diags.AddError("Error adopting existing app sign-on policy rule",
fmt.Sprintf("Could not read rule '%s' (ID: %s): %s", rule.Name.ValueString(), ruleID, err.Error()))
return policyRuleModel{}, diags
}
isSystem := existingRule.System != nil && *existingRule.System
apiRule := r.buildAPIRuleFromModel(ctx, rule)
if isSystem {
// System rules (e.g. Catch-all Rule) reject condition changes.
// The API requires name, priority, and system=true to be present.
apiRule.Conditions = nil
apiRule.System = utils.BoolPtr(true)
// Preserve the actual name and priority from the API (they can't be changed).
apiRule.Name = existingRule.Name
if existingRule.PriorityPtr != nil {
apiRule.PriorityPtr = existingRule.PriorityPtr
}
}
updatedRule, err := r.updateRuleInAPI(ctx, client, policyID, ruleID, apiRule)
if err != nil {
diags.AddError("Error adopting existing app sign-on policy rule",
fmt.Sprintf("Could not adopt rule '%s' (ID: %s, isSystem: %t): %s", rule.Name.ValueString(), ruleID, isSystem, err.Error()))
return policyRuleModel{}, diags
}
if err := r.syncRuleStatus(ctx, client, policyID, ruleID, updatedRule.Status, rule.Status.ValueString()); err != nil {
diags.AddError("Error setting status on app sign-on policy rule",
fmt.Sprintf("Could not set status for rule '%s': %s", rule.Name.ValueString(), err.Error()))
return policyRuleModel{}, diags
}
result := r.updateRuleModelFromAPI(ctx, rule, updatedRule)
result.Status = rule.Status
return result, diags
}
// Create new rule.
apiRule := r.buildAPIRuleFromModel(ctx, rule)
createdRule, err := r.createRuleInAPI(ctx, client, policyID, apiRule)
if err != nil {
diags.AddError("Error creating app sign-on policy rule",
fmt.Sprintf("Could not create rule '%s': %s", rule.Name.ValueString(), err.Error()))
return policyRuleModel{}, diags
}
if err := r.syncRuleStatus(ctx, client, policyID, createdRule.Id, createdRule.Status, rule.Status.ValueString()); err != nil {
diags.AddError("Error setting status on app sign-on policy rule",
fmt.Sprintf("Could not set status for rule '%s': %s", rule.Name.ValueString(), err.Error()))
return policyRuleModel{}, diags
}
result := r.updateRuleModelFromAPI(ctx, rule, createdRule)
result.Status = rule.Status
return result, diags
}
// normalizeAPIRuleForSystem strips conditions and preserves name/priority for system rules
func (r *appSignOnPolicyRulesResource) normalizeAPIRuleForSystem(
apiRule *sdk.AccessPolicyRule,
systemRule *sdk.AccessPolicyRule,
) {
if systemRule.System == nil || !*systemRule.System {
return
}
// System rules cannot have conditions modified
apiRule.Conditions = nil
apiRule.System = utils.BoolPtr(true)
// Preserve immutable fields from API
apiRule.Name = systemRule.Name
apiRule.PriorityPtr = systemRule.PriorityPtr
}
// processRuleUpdate handles updating or creating a single rule during Update.