Joaquín Reñé
2025-11-03 64993ff80e90bee69de7a179dc6af8b5b079197b
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
/*
 * Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
 */
package net.curisit.securis.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import net.curisit.integrity.commons.Utils;
import net.curisit.securis.services.ApiResource;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
/**
 * TokenHelper
 * <p>
 * Utility component to generate and validate short-lived authentication tokens
 * for SeCuris services. Tokens are:
 * </p>
 * <ul>
 *   <li>Base64-encoded UTF-8 strings.</li>
 *   <li>Composed as: {@code <secret> <username> <iso8601-timestamp>} (space-separated).</li>
 *   <li>Where {@code secret} is a deterministic SHA-256 HMAC-like hash built from a static seed,
 *       the username, and the issuance timestamp.</li>
 * </ul>
 *
 * <p><b>Lifecycle & scope:</b> {@code @ApplicationScoped}. Stateless and thread-safe.</p>
 *
 * <p><b>Security notes:</b>
 *   The {@code seed} acts like a shared secret. Keep it private and rotate if compromised.
 *   Tokens expire after {@link #VALID_TOKEN_PERIOD} hours except a special client token
 *   defined by {@link ApiResource#API_CLIENT_USERNAME} issued at epoch-1 (see {@link #isTokenValid(String)}).
 * </p>
 *
 * <p><b>Format details:</b>
 *   <pre>
 *   token = Base64( secret + " " + user + " " + Utils.toIsoFormat(date) )
 *   secret = hex(SHA-256(seed || user || isoDate))
 *   </pre>
 * </p>
 *
 * @author JRA
 * Last reviewed by JRA on Oct 6, 2025.
 */
@ApplicationScoped
public class TokenHelper {
    private static final Logger LOG = LogManager.getLogger(TokenHelper.class);
    /**
     * Validity window for standard tokens, in hours.
     * <p>
     * Any token with a creation date older than this window will be rejected
     * (unless it matches the special API client rule documented in
     * {@link #isTokenValid(String)}).
     * </p>
     */
    private static int VALID_TOKEN_PERIOD = 24;
    /** Standard HTTP header used by SeCuris clients to carry the token. */
    public static final String TOKEN_HEADER_PÀRAM = "X-SECURIS-TOKEN";
    /**
     * TokenHelper<p>
     * CDI no-arg constructor.
     * <p>
     * Kept for dependency injection. No initialization logic is required.
     * </p>
     */
    @Inject
    public TokenHelper() {
    }
    /**
     * Static secret seed used to derive the token {@code secret} portion.
     * <p>
     * Treat this as confidential. Changing it invalidates all outstanding tokens.
     * </p>
     */
    private static byte[] seed = "S3Cur15S33dForT0k3nG3n3r@tion".getBytes();
    // ---------------------------------------------------------------------
    // Token generation
    // ---------------------------------------------------------------------
    /**
     * generateToken
     * <p>
     * Convenience overload that generates a token for {@code user} using the current
     * system time as the issuance timestamp.
     * </p>
     *
     * @param user Username to embed in the token (must be non-null/non-empty).
     * @return Base64-encoded token string, or {@code null} if a cryptographic error occurs.
     */
    public String generateToken(String user) {
        return generateToken(user, new Date());
    }
    /**
     * generateToken
     * <p>
     * Builds a token for a given user and issuance date. The token body is:
     * </p>
     * <pre>
     * secret + " " + user + " " + Utils.toIsoFormat(date)
     * </pre>
     * <p>
     * and then Base64-encoded in UTF-8.
     * </p>
     *
     * @param user Username to embed.
     * @param date Issuance date to include in the token (affects expiry and secret derivation).
     * @return Base64 token, or {@code null} upon failure.
     */
    public String generateToken(String user, Date date) {
        try {
            String secret = generateSecret(user, date);
            StringBuilder sb = new StringBuilder();
            sb.append(secret);
            sb.append(' ');
            sb.append(user);
            sb.append(' ');
            sb.append(Utils.toIsoFormat(date));
            // Standard UTF-8 encoding before Base64
            return Base64.getEncoder().encodeToString(sb.toString().getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Error generating SHA-256 hash", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("Error generating SHA-256 hash", e);
        }
        return null;
    }
    /**
     * generateSecret
     * <p>
     * Derives the deterministic secret (a 64-hex-character SHA-256 digest) used to
     * authenticate a token. Inputs are concatenated in the following order:
     * </p>
     * <ol>
     *   <li>{@link #seed}</li>
     *   <li>{@code user} (UTF-8 bytes)</li>
     *   <li>{@code Utils.toIsoFormat(date)}</li>
     * </ol>
     *
     * @param user Username to mix in the digest.
     * @param date Token issuance date to mix in the digest.
     * @return 64-char hex string.
     * @throws UnsupportedEncodingException If UTF-8 is unavailable (unexpected).
     * @throws NoSuchAlgorithmException     If SHA-256 is unavailable (unexpected).
     */
    private String generateSecret(String user, Date date) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
        mDigest.update(seed, 0, seed.length);
        byte[] userbytes = user.getBytes("utf-8");
        mDigest.update(userbytes, 0, userbytes.length);
        byte[] isodate = Utils.toIsoFormat(date).getBytes();
        mDigest.update(isodate, 0, isodate.length);
        BigInteger i = new BigInteger(1, mDigest.digest());
        String secret = String.format("%1$064x", i);
        return secret;
    }
    // ---------------------------------------------------------------------
    // Token validation & parsing
    // ---------------------------------------------------------------------
    /**
     * isTokenValid
     * <p>
     * Validates the structure, signature and expiry of the given token.
     * Steps performed:
     * </p>
     * <ol>
     *   <li>Base64-decode the token into {@code "secret user isoDate"}.</li>
     *   <li>Parse {@code user} and {@code isoDate}; recompute the expected secret via
     *       {@link #generateSecret(String, Date)} and compare with the provided one.</li>
     *   <li>Check expiry: if the token's timestamp is older than
     *       {@link #VALID_TOKEN_PERIOD} hours, it's invalid.</li>
     *   <li>Special-case: if {@code user} equals {@link ApiResource#API_CLIENT_USERNAME}
     *       and the date returns a non-positive epoch time (e.g., created with {@code new Date(-1)}),
     *       the expiry check is skipped (client integration token).</li>
     * </ol>
     *
     * @param token Base64 token string.
     * @return {@code true} if valid and not expired; {@code false} otherwise.
     */
    public boolean isTokenValid(String token) {
        try {
            String tokenDecoded = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
            String[] parts = StringUtils.split(tokenDecoded, ' ');
            if (parts == null || parts.length < 3) {
                return false;
            }
            String secret = parts[0];
            String user = parts[1];
            Date date = Utils.toDateFromIso(parts[2]);
            // Expiry check (unless special client token rule applies)
            if (date.getTime() > 0 || !user.equals(ApiResource.API_CLIENT_USERNAME)) {
                if (new Date().after(new Date(date.getTime() + VALID_TOKEN_PERIOD * 60 * 60 * 1000))) {
                    return false;
                }
            }
            // Signature check
            String newSecret = generateSecret(user, date);
            return newSecret.equals(secret);
        } catch (IOException e) {
            LOG.error("Error decoding Base64 token", e);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Error generation secret to compare with", e);
        }
        return false;
    }
    /**
     * extractUserFromToken
     * <p>
     * Extracts the username portion from a validly structured token.
     * </p>
     *
     * @param token Base64 token string (may be {@code null}).
     * @return Username if the token has at least three space-separated fields after decoding;
     *         {@code null} on error or malformed input.
     */
    public String extractUserFromToken(String token) {
        try {
            if (token == null) {
                return null;
            }
            String tokenDecoded = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
            String[] parts = StringUtils.split(tokenDecoded, ' ');
            if (parts == null || parts.length < 3) {
                return null;
            }
            String user = parts[1];
            return user;
        } catch (Exception e) {
            LOG.error("Error decoding Base64 token", e);
        }
        return null;
    }
    /**
     * extractDateCreationFromToken
     * <p>
     * Parses and returns the issuance {@link Date} embedded in the token, without
     * performing validation or expiry checks.
     * </p>
     *
     * @param token Base64 token string.
     * @return Issuance {@link Date}, or {@code null} if the token is malformed or cannot be decoded.
     */
    public Date extractDateCreationFromToken(String token) {
        try {
            String tokenDecoded = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
            String[] parts = StringUtils.split(tokenDecoded, ' ');
            if (parts == null || parts.length < 3) {
                return null;
            }
            Date date = Utils.toDateFromIso(parts[2]);
            return date;
        } catch (Exception e) {
            LOG.error("Error decoding Base64 token", e);
        }
        return null;
    }
    // ---------------------------------------------------------------------
    // Demo / manual test
    // ---------------------------------------------------------------------
    /**
     * main
     * <p>
     * Simple manual test demonstrating generation and validation of a special
     * "_client" token that bypasses expiry via a negative epoch date.
     * </p>
     *
     * @param args CLI args (unused).
     * @throws IOException If something goes wrong while encoding/decoding Base64 (unlikely).
     */
    public static void main(String[] args) throws IOException {
        // client token:
        // OTk3ODRiMzY5NzQ5MWI5NmYyZGQyODRiYjY2ZTU2YzdmMTZjYzM3YTY3N2ExM2M3ODI2MjU5ZTMzOTIyYjUzNSBfY2xpZW50IDE5NzAtMDEtMDFUMDA6NTk6NTkuOTk5KzAxMDA=
        // OTk3ODRiMzY5NzQ5MWI5NmYyZGQyODRiYjY2ZTU2YzdmMTZjYzM3YTY3N2ExM2M3ODI2MjU5ZTMzOTIyYjUzNSBfY2xpZW50IDE5NzAtMDEtMDFUMDA6NTk6NTkuOTk5KzAxMDA=
        String t = new TokenHelper().generateToken("_client", new Date(-1));
        System.out.println("client token: " + t);
        System.out.println("client token: " + new String(Base64.getDecoder().decode(t), StandardCharsets.UTF_8));
        System.out.println("is valid client token: " + new TokenHelper().isTokenValid(t));
    }
}