Skip to content

Commit 21ce840

Browse files
committed
Add encription for oauth token.
1 parent 3671c32 commit 21ce840

7 files changed

Lines changed: 300 additions & 10 deletions

File tree

‎wise-api/src/main/java/com/wisemapping/dao/UserManager.java‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import org.jetbrains.annotations.Nullable;
2828

2929
import java.util.Calendar;
30+
import java.util.Collection;
3031
import java.util.List;
3132

3233
public interface UserManager {
@@ -154,11 +155,16 @@ List<Account> getUsersWithFilters(String search, Boolean filterActive, Boolean f
154155

155156
/**
156157
* Find a Facebook OAuth2 user by their Facebook user ID (stored in oauth_token).
157-
* @param facebookId the Facebook user ID from a data deletion request
158+
* Accepts a collection of candidate token values so that both the legacy plaintext
159+
* form and the new encrypted form can be matched in a single query, preserving
160+
* backward compatibility during the transition period.
161+
*
162+
* @param candidateTokens one or more token values to match against oauth_token
163+
* (typically the raw Facebook ID plus its encrypted form)
158164
* @return the matching account, or null if not found
159165
*/
160166
@Nullable
161-
Account getUserByFacebookId(@NotNull String facebookId);
167+
Account getUserByFacebookId(@NotNull Collection<String> candidateTokens);
162168

163169
/**
164170
* Count users matching advanced filtering criteria

‎wise-api/src/main/java/com/wisemapping/dao/UserManagerImpl.java‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
import org.springframework.transaction.annotation.Transactional;
4343

4444
import java.util.Calendar;
45+
import java.util.Collection;
4546
import java.util.List;
4647
import java.util.Set;
4748
import java.util.concurrent.CopyOnWriteArraySet;
@@ -242,12 +243,14 @@ public Account getUserByActivationCode(long code) {
242243

243244
@Override
244245
@Nullable
245-
public Account getUserByFacebookId(@NotNull String facebookId) {
246+
public Account getUserByFacebookId(@NotNull Collection<String> candidateTokens) {
247+
// Query with IN so both the legacy plaintext value and the new encrypted form
248+
// ({enc}...) are matched in a single round-trip, preserving backward compatibility.
246249
final TypedQuery<Account> query = entityManager.createQuery(
247-
"SELECT a FROM Account a WHERE a.authenticationTypeCode = :authType AND a.oauthToken = :facebookId",
250+
"SELECT a FROM Account a WHERE a.authenticationTypeCode = :authType AND a.oauthToken IN :tokens",
248251
Account.class);
249252
query.setParameter("authType", AuthenticationType.FACEBOOK_OAUTH2.getCode());
250-
query.setParameter("facebookId", facebookId);
253+
query.setParameter("tokens", candidateTokens);
251254
final List<Account> results = query.getResultList();
252255
return results.isEmpty() ? null : results.get(0);
253256
}

‎wise-api/src/main/java/com/wisemapping/security/OAuth2AuthenticationSuccessHandler.java‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ public class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccess
5757

5858
@Autowired
5959
private MetricsService metricsService;
60+
61+
@Autowired
62+
private OAuthTokenEncryptionService oauthTokenEncryptionService;
6063

6164
@Value("${app.site.ui-base-url:}")
6265
private String uiBaseUrl;
@@ -247,7 +250,7 @@ private Account createNewOAuthUser(String email, String firstName, String lastNa
247250
newUser.setFirstname(firstName);
248251
newUser.setLastname(lastName);
249252
newUser.setAuthenticationType(authType);
250-
newUser.setOauthToken(providerId); // store provider user ID for data deletion lookups
253+
newUser.setOauthToken(oauthTokenEncryptionService.encrypt(providerId)); // store encrypted provider user ID for data deletion lookups
251254
newUser.setPassword("");
252255
newUser.setOauthSync(true);
253256

@@ -266,9 +269,12 @@ private Account handleExistingUser(Account existingUser, AuthenticationType auth
266269
// For existing OAuth users with same auth type, update if needed
267270
if (existingAuthType == authType) {
268271
boolean needsUpdate = (existingUser.getOauthSync() == null || !existingUser.getOauthSync());
269-
// Refresh provider ID if it was never stored or has changed
270-
if (providerId != null && !providerId.equals(existingUser.getOauthToken())) {
271-
existingUser.setOauthToken(providerId);
272+
// Refresh provider ID if it was never stored or has changed.
273+
// Decrypt the stored value first so we compare plain IDs regardless of
274+
// whether the row was written before or after encryption was enabled.
275+
final String storedProviderId = oauthTokenEncryptionService.decrypt(existingUser.getOauthToken());
276+
if (providerId != null && !providerId.equals(storedProviderId)) {
277+
existingUser.setOauthToken(oauthTokenEncryptionService.encrypt(providerId));
272278
needsUpdate = true;
273279
}
274280
if (needsUpdate) {
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/*
2+
* Copyright [2007-2025] [wisemapping]
3+
*
4+
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
5+
* It is basically the Apache License, Version 2.0 (the "License") plus the
6+
* "powered by wisemapping" text requirement on every single page;
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the license at
9+
*
10+
* https://github.com/wisemapping/wisemapping-open-source/blob/main/LICENSE.md
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
package com.wisemapping.security;
19+
20+
import org.jetbrains.annotations.NotNull;
21+
import org.jetbrains.annotations.Nullable;
22+
import org.slf4j.Logger;
23+
import org.slf4j.LoggerFactory;
24+
import org.springframework.beans.factory.annotation.Value;
25+
import org.springframework.stereotype.Service;
26+
27+
import javax.crypto.Cipher;
28+
import javax.crypto.SecretKey;
29+
import javax.crypto.spec.IvParameterSpec;
30+
import javax.crypto.spec.SecretKeySpec;
31+
import java.nio.charset.StandardCharsets;
32+
import java.security.MessageDigest;
33+
import java.util.Base64;
34+
35+
/**
36+
* Service for encrypting and decrypting OAuth provider user IDs (stored in the
37+
* {@code oauth_token} database column).
38+
*
39+
* <h3>Backward-compatibility</h3>
40+
* <p>Encrypted values carry an <b>{@value #ENC_PREFIX}</b> prefix. Any value that
41+
* lacks this prefix is treated as legacy plaintext and returned unchanged by
42+
* {@link #decrypt}. This allows old rows and new rows to coexist in the same table
43+
* without a schema migration.
44+
*
45+
* <h3>Deterministic encryption</h3>
46+
* <p>AES-256-CBC is used with a <em>fixed</em> IV derived from the secret key.
47+
* The same plaintext therefore always produces the same ciphertext for a given key.
48+
* This is intentional: it lets JPQL {@code IN} queries match both the plaintext and
49+
* encrypted forms of a provider ID without requiring an extra hash column.
50+
*
51+
* <h3>Disabled mode</h3>
52+
* <p>When {@code app.oauth.token.secret} is empty (the default) the service acts as
53+
* a no-op: {@link #encrypt} returns the original value and {@link #decrypt} returns
54+
* the stored value unchanged. This preserves existing behaviour for deployments that
55+
* have not yet opted in to encryption.
56+
*/
57+
@Service
58+
public class OAuthTokenEncryptionService {
59+
60+
/** Prefix prepended to every encrypted value to distinguish it from plaintext. */
61+
public static final String ENC_PREFIX = "{enc}";
62+
63+
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
64+
private static final Logger logger = LoggerFactory.getLogger(OAuthTokenEncryptionService.class);
65+
66+
@Value("${app.oauth.token.secret:}")
67+
private String secretKey;
68+
69+
// Derived lazily and cached after first use (guarded by synchronized helpers).
70+
private volatile SecretKey aesKey;
71+
private volatile IvParameterSpec iv;
72+
73+
// -------------------------------------------------------------------------
74+
// Public API
75+
// -------------------------------------------------------------------------
76+
77+
/**
78+
* Encrypt a plaintext OAuth provider user ID.
79+
*
80+
* @param plaintext the raw provider ID (e.g. a Google subject or Facebook user ID)
81+
* @return {@code {enc}<base64-ciphertext>} when encryption is enabled,
82+
* or {@code plaintext} unchanged when no secret key is configured
83+
*/
84+
@Nullable
85+
public String encrypt(@Nullable String plaintext) {
86+
if (plaintext == null) return null;
87+
if (!isEnabled()) return plaintext;
88+
try {
89+
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
90+
cipher.init(Cipher.ENCRYPT_MODE, resolveKey(), resolveIv());
91+
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
92+
return ENC_PREFIX + Base64.getEncoder().encodeToString(encrypted);
93+
} catch (Exception e) {
94+
logger.error("Failed to encrypt OAuth token", e);
95+
throw new IllegalStateException("OAuth token encryption failed", e);
96+
}
97+
}
98+
99+
/**
100+
* Decrypt a value previously produced by {@link #encrypt}.
101+
*
102+
* <p>If the value does not start with the {@value #ENC_PREFIX} prefix it is
103+
* returned as-is (legacy plaintext / already-decrypted value).
104+
*
105+
* @param value the stored column value
106+
* @return the original provider ID, or {@code value} unchanged for plaintext rows
107+
*/
108+
@Nullable
109+
public String decrypt(@Nullable String value) {
110+
if (value == null || !value.startsWith(ENC_PREFIX)) return value;
111+
if (!isEnabled()) {
112+
logger.warn("Encountered an encrypted OAuth token but no secret key is configured — returning raw value");
113+
return value;
114+
}
115+
try {
116+
byte[] cipherBytes = Base64.getDecoder().decode(value.substring(ENC_PREFIX.length()));
117+
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
118+
cipher.init(Cipher.DECRYPT_MODE, resolveKey(), resolveIv());
119+
return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
120+
} catch (Exception e) {
121+
logger.error("Failed to decrypt OAuth token", e);
122+
throw new IllegalStateException("OAuth token decryption failed", e);
123+
}
124+
}
125+
126+
/**
127+
* Returns {@code true} when the value carries the encrypted prefix.
128+
*/
129+
public boolean isEncrypted(@Nullable String value) {
130+
return value != null && value.startsWith(ENC_PREFIX);
131+
}
132+
133+
/**
134+
* Returns {@code true} when a non-empty secret key has been configured.
135+
*/
136+
public boolean isEnabled() {
137+
return secretKey != null && !secretKey.isBlank();
138+
}
139+
140+
// -------------------------------------------------------------------------
141+
// Key / IV derivation
142+
// -------------------------------------------------------------------------
143+
144+
private SecretKey resolveKey() throws Exception {
145+
if (aesKey == null) {
146+
synchronized (this) {
147+
if (aesKey == null) {
148+
aesKey = deriveKey(secretKey);
149+
}
150+
}
151+
}
152+
return aesKey;
153+
}
154+
155+
private IvParameterSpec resolveIv() throws Exception {
156+
if (iv == null) {
157+
synchronized (this) {
158+
if (iv == null) {
159+
iv = deriveIv(secretKey);
160+
}
161+
}
162+
}
163+
return iv;
164+
}
165+
166+
/**
167+
* Derive a 256-bit AES key from the secret string via SHA-256.
168+
*/
169+
private static SecretKey deriveKey(@NotNull String secret) throws Exception {
170+
MessageDigest sha = MessageDigest.getInstance("SHA-256");
171+
byte[] keyBytes = sha.digest(secret.getBytes(StandardCharsets.UTF_8));
172+
return new SecretKeySpec(keyBytes, "AES");
173+
}
174+
175+
/**
176+
* Derive a deterministic 128-bit IV from the secret via MD5.
177+
*
178+
* <p>The IV is intentionally fixed for a given key so that encryption is
179+
* deterministic (same plaintext → same ciphertext). This is a deliberate
180+
* trade-off that makes JPQL equality and IN-list lookups possible without
181+
* storing a separate hash column.
182+
*/
183+
private static IvParameterSpec deriveIv(@NotNull String secret) throws Exception {
184+
MessageDigest md5 = MessageDigest.getInstance("MD5");
185+
byte[] ivBytes = md5.digest(secret.getBytes(StandardCharsets.UTF_8));
186+
return new IvParameterSpec(ivBytes);
187+
}
188+
}

‎wise-api/src/main/java/com/wisemapping/service/UserServiceImpl.java‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import com.wisemapping.model.*;
2727
import com.wisemapping.rest.model.RestResetPasswordAction;
2828
import com.wisemapping.rest.model.RestResetPasswordResponse;
29+
import com.wisemapping.security.OAuthTokenEncryptionService;
2930
import com.wisemapping.util.VelocityEngineUtils;
3031
import com.wisemapping.util.VelocityEngineWrapper;
3132
import org.slf4j.LoggerFactory;
@@ -59,6 +60,8 @@ public class UserServiceImpl
5960
private VelocityEngineWrapper velocityEngineWrapper;
6061
@Autowired
6162
private MetricsService metricsService;
63+
@Autowired
64+
private OAuthTokenEncryptionService oauthTokenEncryptionService;
6265

6366
final private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
6467

@@ -130,7 +133,16 @@ private int rand(int lo, int hi) {
130133
@Override
131134
@Nullable
132135
public Account getUserByFacebookId(@NotNull String facebookId) {
133-
return userManager.getUserByFacebookId(facebookId);
136+
// Build a candidate list containing both the plaintext and encrypted forms so
137+
// that the query matches legacy rows (stored as plain IDs) and new rows (stored
138+
// with the {enc} prefix) without requiring a schema migration.
139+
final List<String> candidates = new ArrayList<>();
140+
candidates.add(facebookId);
141+
final String encrypted = oauthTokenEncryptionService.encrypt(facebookId);
142+
if (encrypted != null && !encrypted.equals(facebookId)) {
143+
candidates.add(encrypted);
144+
}
145+
return userManager.getUserByFacebookId(candidates);
134146
}
135147

136148
@Override

‎wise-api/src/main/resources/application.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,13 @@ app:
206206
jwt:
207207
secret: dlqxKAg685SaKhsQXIMeM=JWCw3bkl3Ei3Tb7LMlnd19oMd66burPNlJ0Po1qguyjgpakQTk2CN3
208208
expirationMin: 10080 # One week
209+
# OAuth provider-ID encryption. Set a strong random secret (≥ 32 chars) to encrypt
210+
# OAuth provider user IDs at rest. Leave empty to keep storing them as plaintext
211+
# (legacy behaviour). New values will be prefixed with {enc}; old plaintext rows
212+
# continue to work unchanged (backward-compatible).
213+
oauth:
214+
token:
215+
secret: dlqxKAg685SaKhsQXIMeM$JWCw3bkl3Ei3Tb7LMlnd19oMd66xxxPNlJ0Po1qguyjgpakQTk2CN3
209216
# Admin account with super admin permissions on the API.
210217
admin:
211218
user: admin@wisemapping.org
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.wisemapping.security;
2+
3+
import org.junit.jupiter.api.BeforeEach;
4+
import org.junit.jupiter.api.Test;
5+
import org.springframework.test.util.ReflectionTestUtils;
6+
7+
import static org.junit.jupiter.api.Assertions.*;
8+
9+
class OAuthTokenEncryptionServiceTest {
10+
11+
private OAuthTokenEncryptionService service;
12+
13+
@BeforeEach
14+
void setUp() {
15+
service = new OAuthTokenEncryptionService();
16+
// Inject a fixed secret so the test is deterministic and self-contained.
17+
ReflectionTestUtils.setField(service, "secretKey", "test-secret-for-oauth-encryption-32ch");
18+
}
19+
20+
/** New values are encrypted (carry the prefix) and decrypt back to the original. */
21+
@Test
22+
void encryptThenDecrypt_roundTripsProviderIdCorrectly() {
23+
String facebookId = "123456789012345";
24+
25+
String encrypted = service.encrypt(facebookId);
26+
27+
assertTrue(service.isEncrypted(encrypted),
28+
"Encrypted value should start with " + OAuthTokenEncryptionService.ENC_PREFIX);
29+
assertNotEquals(facebookId, encrypted,
30+
"Encrypted value must differ from plaintext");
31+
32+
String decrypted = service.decrypt(encrypted);
33+
assertEquals(facebookId, decrypted,
34+
"Decrypting the encrypted value should recover the original provider ID");
35+
}
36+
37+
/**
38+
* Legacy rows stored without the {enc} prefix must be returned unchanged by
39+
* decrypt(), so old accounts keep working without any data migration.
40+
*/
41+
@Test
42+
void decrypt_legacyPlaintextValue_returnedUnchanged() {
43+
String legacyToken = "987654321098765";
44+
45+
String result = service.decrypt(legacyToken);
46+
47+
assertEquals(legacyToken, result,
48+
"A plaintext value without the {enc} prefix must pass through decrypt() unchanged");
49+
}
50+
51+
/**
52+
* When no secret key is configured (empty string) the service acts as a no-op:
53+
* encrypt() returns the raw value and decrypt() returns the stored value as-is.
54+
* This preserves the original behaviour for deployments that have not opted in.
55+
*/
56+
@Test
57+
void encryptAndDecrypt_whenDisabled_areNoOps() {
58+
ReflectionTestUtils.setField(service, "secretKey", "");
59+
60+
String providerId = "111222333444555";
61+
62+
assertFalse(service.isEnabled(), "Service should report disabled when secret is blank");
63+
assertEquals(providerId, service.encrypt(providerId),
64+
"encrypt() should be a no-op when disabled");
65+
assertEquals(providerId, service.decrypt(providerId),
66+
"decrypt() should be a no-op when disabled");
67+
}
68+
}

0 commit comments

Comments
 (0)