Skip to content

Commit 7bf8cc4

Browse files
committed
Restore Original Entry on Failed Rebind
When the bind step of a rebind fails after the existing entry was renamed to its temporary DN, the executor was never recorded for rollback, leaving the entry at the temporary DN and nothing at the original DN. RebindOperationExecutor now tracks which steps completed. If the bind fails, the entry is renamed back before the exception is rethrown, and rollback only compensates steps that actually completed. Closes gh-1928 Signed-off-by: Josh Cummings <3627351+jzheaux@users.noreply.github.com>
1 parent adefb7e commit 7bf8cc4

3 files changed

Lines changed: 255 additions & 2 deletions

File tree

‎core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutor.java‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@
3434
* location and binds a new entry to the original location using the attributes supplied
3535
* to the original rebind opertaion.
3636
*
37+
* <p>
38+
* Instances are not thread-safe. Like the rest of the compensating transaction support,
39+
* an instance is confined to the thread that owns the transaction, from
40+
* {@link #performOperation()} until {@link #commit()} or {@link #rollback()}.
41+
*
3742
* @author Mattias Hellborg Arthursson
3843
* @since 1.2
3944
*/
@@ -51,6 +56,10 @@ public class RebindOperationExecutor implements CompensatingTransactionOperation
5156

5257
private Attributes originalAttributes;
5358

59+
private boolean renamed;
60+
61+
private boolean bound;
62+
5463
/**
5564
* Constructor.
5665
* @param ldapOperations the {@link LdapOperations} to use to perform the rollback.
@@ -84,8 +93,9 @@ LdapOperations getLdapOperations() {
8493
public void rollback() {
8594
log.debug("Rolling back rebind operation");
8695
try {
87-
this.ldapOperations.unbind(this.originalDn);
88-
this.ldapOperations.rename(this.temporaryDn, this.originalDn);
96+
// Only steps that actually completed are compensated, in reverse order
97+
maybeRollbackBind();
98+
maybeRollbackRename();
8999
}
90100
catch (Exception ex) {
91101
log.warn(
@@ -109,8 +119,51 @@ public void commit() {
109119
*/
110120
public void performOperation() {
111121
log.debug("Performing rebind operation - " + "renaming original entry and " + "binding new contents to entry.");
122+
performRename();
123+
try {
124+
performBind();
125+
}
126+
catch (RuntimeException ex) {
127+
// This executor is only recorded for rollback if this method returns
128+
// normally, so restore the original entry here. The temporary DN is only
129+
// renamed back (never unbound), and only because this executor renamed the
130+
// entry there; the rename itself fails if something occupies the original DN.
131+
try {
132+
maybeRollbackRename();
133+
}
134+
catch (Exception rollbackEx) {
135+
log.warn("Failed to restore entry after failed rebind, dn: " + this.originalDn + "; temporary DN: "
136+
+ this.temporaryDn, rollbackEx);
137+
}
138+
throw ex;
139+
}
140+
}
141+
142+
// Each flag is read and written only by its perform/rollback pair below, so that the
143+
// flags and the operations they describe cannot get out of sync.
144+
145+
private void performRename() {
112146
this.ldapOperations.rename(this.originalDn, this.temporaryDn);
147+
this.renamed = true;
148+
}
149+
150+
private void performBind() {
113151
this.ldapOperations.bind(this.originalDn, this.originalObject, this.originalAttributes);
152+
this.bound = true;
153+
}
154+
155+
private void maybeRollbackRename() {
156+
if (this.renamed) {
157+
this.ldapOperations.rename(this.temporaryDn, this.originalDn);
158+
this.renamed = false;
159+
}
160+
}
161+
162+
private void maybeRollbackBind() {
163+
if (this.bound) {
164+
this.ldapOperations.unbind(this.originalDn);
165+
this.bound = false;
166+
}
114167
}
115168

116169
Attributes getOriginalAttributes() {

‎core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTests.java‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,34 @@
1616

1717
package org.springframework.ldap.transaction.compensating;
1818

19+
import javax.naming.Name;
1920
import javax.naming.directory.BasicAttributes;
2021
import javax.naming.ldap.LdapName;
2122

2223
import org.junit.jupiter.api.BeforeEach;
2324
import org.junit.jupiter.api.Test;
2425

26+
import org.springframework.ldap.NameAlreadyBoundException;
27+
import org.springframework.ldap.SchemaViolationException;
2528
import org.springframework.ldap.core.LdapOperations;
2629
import org.springframework.ldap.support.LdapUtils;
2730

31+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
32+
import static org.mockito.ArgumentMatchers.any;
33+
import static org.mockito.ArgumentMatchers.eq;
34+
import static org.mockito.BDDMockito.willThrow;
2835
import static org.mockito.Mockito.mock;
36+
import static org.mockito.Mockito.never;
37+
import static org.mockito.Mockito.times;
2938
import static org.mockito.Mockito.verify;
39+
import static org.mockito.Mockito.verifyNoInteractions;
3040

3141
public class RebindOperationExecutorTests {
3242

43+
private static final LdapName ORIGINAL = LdapUtils.newLdapName("cn=john doe");
44+
45+
private static final LdapName TEMP = LdapUtils.newLdapName("cn=john doe_temp");
46+
3347
private LdapOperations ldapOperationsMock;
3448

3549
@BeforeEach
@@ -76,10 +90,79 @@ public void testRollback() {
7690
expectedTempDn, expectedObject, expectedAttributes);
7791

7892
// perform test
93+
tested.performOperation();
7994
tested.rollback();
8095

8196
verify(this.ldapOperationsMock).unbind(expectedOriginalDn);
8297
verify(this.ldapOperationsMock).rename(expectedTempDn, expectedOriginalDn);
8398
}
8499

100+
@Test
101+
public void testRollbackWithoutPerformDoesNothing() {
102+
RebindOperationExecutor tested = executor();
103+
104+
tested.rollback();
105+
106+
verifyNoInteractions(this.ldapOperationsMock);
107+
}
108+
109+
@Test
110+
public void testFailedRenameCompensatesNothing() {
111+
RebindOperationExecutor tested = executor();
112+
willThrow(new NameAlreadyBoundException(new javax.naming.NameAlreadyBoundException(("temp exists"))))
113+
.given(this.ldapOperationsMock)
114+
.rename(ORIGINAL, TEMP);
115+
116+
assertThatExceptionOfType(NameAlreadyBoundException.class).isThrownBy(tested::performOperation);
117+
tested.rollback();
118+
119+
verify(this.ldapOperationsMock, never()).bind(any(Name.class), any(), any());
120+
verify(this.ldapOperationsMock, never()).unbind(any(Name.class));
121+
verify(this.ldapOperationsMock, never()).rename(TEMP, ORIGINAL);
122+
}
123+
124+
@Test
125+
public void testFailedBindRenamesTemporaryEntryBack() {
126+
RebindOperationExecutor tested = executor();
127+
RuntimeException failure = new SchemaViolationException(
128+
new javax.naming.directory.SchemaViolationException(("bad entry")));
129+
willThrow(failure).given(this.ldapOperationsMock).bind(eq(ORIGINAL), any(), any());
130+
131+
assertThatExceptionOfType(SchemaViolationException.class).isThrownBy(tested::performOperation)
132+
.isSameAs(failure);
133+
134+
verify(this.ldapOperationsMock).rename(TEMP, ORIGINAL);
135+
verify(this.ldapOperationsMock, never()).unbind(any(Name.class));
136+
137+
// a later rollback must not compensate anything a second time
138+
tested.rollback();
139+
verify(this.ldapOperationsMock, times(1)).rename(TEMP, ORIGINAL);
140+
verify(this.ldapOperationsMock, never()).unbind(any(Name.class));
141+
}
142+
143+
@Test
144+
public void testFailedBindWithFailedRestoreStillRethrowsOriginal() {
145+
RebindOperationExecutor tested = executor();
146+
RuntimeException failure = new SchemaViolationException(
147+
new javax.naming.directory.SchemaViolationException(("bad entry")));
148+
willThrow(failure).given(this.ldapOperationsMock).bind(eq(ORIGINAL), any(), any());
149+
willThrow(new NameAlreadyBoundException(new javax.naming.NameAlreadyBoundException(("occupied"))))
150+
.given(this.ldapOperationsMock)
151+
.rename(TEMP, ORIGINAL);
152+
153+
assertThatExceptionOfType(SchemaViolationException.class).isThrownBy(tested::performOperation)
154+
.isSameAs(failure);
155+
156+
// the restore is attempted exactly once, and only by performOperation: the
157+
// transaction manager never records an executor whose performOperation threw,
158+
// so rollback() is not invoked for it and the failed rename is not retried
159+
verify(this.ldapOperationsMock, times(1)).rename(TEMP, ORIGINAL);
160+
verify(this.ldapOperationsMock, never()).unbind(any(Name.class));
161+
}
162+
163+
private RebindOperationExecutor executor() {
164+
return new RebindOperationExecutor(this.ldapOperationsMock, ORIGINAL, TEMP, new Object(),
165+
new BasicAttributes());
166+
}
167+
85168
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
/*
2+
* Copyright 2006-present the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.ldap.itest.manager;
18+
19+
import javax.naming.directory.Attributes;
20+
import javax.naming.directory.BasicAttribute;
21+
import javax.naming.directory.BasicAttributes;
22+
23+
import org.junit.After;
24+
import org.junit.Before;
25+
import org.junit.Test;
26+
27+
import org.springframework.ldap.core.LdapTemplate;
28+
import org.springframework.ldap.core.support.LdapContextSource;
29+
import org.springframework.ldap.test.unboundid.EmbeddedLdapServer;
30+
import org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager;
31+
import org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy;
32+
import org.springframework.ldap.transaction.compensating.support.DefaultTempEntryRenamingStrategy;
33+
import org.springframework.transaction.support.TransactionTemplate;
34+
35+
import static org.assertj.core.api.Assertions.assertThat;
36+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
37+
38+
/**
39+
* Verifies that a rebind whose bind step (or rename step) fails inside a compensating
40+
* transaction leaves the directory as it was before the transaction started.
41+
*/
42+
public class RebindRollbackIntegrationTests {
43+
44+
private static final String DN = "cn=John Doe";
45+
46+
// DefaultTempEntryRenamingStrategy appends "_temp" to the leftmost RDN value
47+
private static final String TEMP_DN = "cn=John Doe_temp";
48+
49+
private EmbeddedLdapServer server;
50+
51+
private LdapTemplate ldapTemplate;
52+
53+
private TransactionTemplate tx;
54+
55+
@Before
56+
public void setUp() throws Exception {
57+
this.server = EmbeddedLdapServer.withPartitionSuffix("dc=example,dc=org").port(10389).build();
58+
this.server.start();
59+
60+
LdapContextSource contextSource = new LdapContextSource();
61+
contextSource.setUrl("ldap://localhost:10389");
62+
contextSource.setBase("dc=example,dc=org");
63+
contextSource.setUserDn("uid=admin,ou=system");
64+
contextSource.setPassword("secret");
65+
contextSource.afterPropertiesSet();
66+
this.ldapTemplate = new LdapTemplate(new TransactionAwareContextSourceProxy(contextSource));
67+
68+
ContextSourceTransactionManager txManager = new ContextSourceTransactionManager();
69+
txManager.setContextSource(contextSource);
70+
txManager.setRenamingStrategy(new DefaultTempEntryRenamingStrategy());
71+
txManager.afterPropertiesSet();
72+
this.tx = new TransactionTemplate(txManager);
73+
}
74+
75+
@After
76+
public void tearDown() {
77+
this.server.close();
78+
}
79+
80+
@Test
81+
public void failedBindAfterRenameIsRolledBack() throws Exception {
82+
this.ldapTemplate.bind(DN, null, person("Doe"));
83+
84+
// a person entry without the required "sn" attribute violates the schema
85+
Attributes invalid = person(null);
86+
87+
assertThatExceptionOfType(RuntimeException.class)
88+
.isThrownBy(() -> this.tx.executeWithoutResult((status) -> this.ldapTemplate.rebind(DN, null, invalid)));
89+
90+
assertThat(this.ldapTemplate.lookup(DN, (Attributes a) -> a)).isNotNull();
91+
assertThat(this.ldapTemplate.lookup(DN, (Attributes a) -> a).get("sn").get()).isEqualTo("Doe");
92+
assertThatExceptionOfType(org.springframework.ldap.NameNotFoundException.class)
93+
.isThrownBy(() -> this.ldapTemplate.lookup(TEMP_DN));
94+
}
95+
96+
@Test
97+
public void rebindWithPreexistingTemporaryEntryLeavesBothEntriesUntouched() throws Exception {
98+
this.ldapTemplate.bind(DN, null, person("Doe"));
99+
this.ldapTemplate.bind(TEMP_DN, null, person("Attacker"));
100+
101+
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
102+
() -> this.tx.executeWithoutResult((status) -> this.ldapTemplate.rebind(DN, null, person("New"))));
103+
104+
assertThat(this.ldapTemplate.lookup(DN, (Attributes a) -> a).get("sn").get()).isEqualTo("Doe");
105+
assertThat(this.ldapTemplate.lookup(TEMP_DN, (Attributes a) -> a).get("sn").get()).isEqualTo("Attacker");
106+
}
107+
108+
private static Attributes person(String sn) {
109+
BasicAttributes person = new BasicAttributes("objectClass", "person", true);
110+
person.put(new BasicAttribute("cn", "John Doe"));
111+
if (sn != null) {
112+
person.put(new BasicAttribute("sn", sn));
113+
}
114+
return person;
115+
}
116+
117+
}

0 commit comments

Comments
 (0)