mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
java client: sign filer JWTs and hold [filer.basic_auth] credentials
FilerSecurityContext reads jwt.filer_signing.key, jwt.filer_signing.read.key (with their expires_after_seconds, defaulting to 10 and 60 like the Go clients) and [filer.basic_auth] from security.toml, with setters to set them in code. getFilerAuthorizationHeaderValue returns the credential for a request to the filer's HTTP port: an HS256 token for the access level, minted like security.GenJwtForFilerServer, else the filer Basic Auth, else the existing [basic_auth] value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b77ec4723
commit
cd06df103a
3 files changed
+181
-1
No files matched your search
@@ -19,6 +19,8 @@ import java.security.KeyStore;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Base64;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public abstract class FilerSecurityContext extends SslContext {
|
||||
//extends Netty SslContext to access its protected static utility methods in
|
||||
@@ -43,6 +45,14 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
|
||||
private static volatile String basicAuthHeaderValue;
|
||||
|
||||
// Credentials for the filer's own HTTP port ([filer.basic_auth], [jwt.filer_signing],
|
||||
// [jwt.filer_signing.read]), sent only on requests addressed to the filer.
|
||||
private static volatile String filerBasicAuthHeaderValue;
|
||||
private static volatile FilerSigningKey filerSigningKey;
|
||||
private static volatile FilerSigningKey filerReadSigningKey;
|
||||
private static final long DEFAULT_FILER_SIGNING_EXPIRES_AFTER_SECONDS = 10;
|
||||
private static final long DEFAULT_FILER_READ_SIGNING_EXPIRES_AFTER_SECONDS = 60;
|
||||
|
||||
|
||||
static {
|
||||
String securityFileName = "security.toml";
|
||||
@@ -64,6 +74,11 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
|
||||
basicAuthHeaderValue = computeBasicAuthHeaderValue(
|
||||
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
|
||||
setFilerBasicAuth(toml.getString("filer.basic_auth.user"), toml.getString("filer.basic_auth.password"));
|
||||
setFilerJwtSigningKey(toml.getString("jwt.filer_signing.key"),
|
||||
toml.getLong("jwt.filer_signing.expires_after_seconds", 0L));
|
||||
setFilerJwtReadSigningKey(toml.getString("jwt.filer_signing.read.key"),
|
||||
toml.getLong("jwt.filer_signing.read.expires_after_seconds", 0L));
|
||||
|
||||
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
|
||||
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
|
||||
@@ -146,6 +161,68 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
return basicAuthHeaderValue;
|
||||
}
|
||||
|
||||
// Configure the filer's [filer.basic_auth] credentials programmatically.
|
||||
public static void setFilerBasicAuth(String username, String password) {
|
||||
filerBasicAuthHeaderValue = computeBasicAuthHeaderValue(username, password);
|
||||
}
|
||||
|
||||
// Configure jwt.filer_signing.key programmatically; expiresAfterSeconds <= 0 uses 10.
|
||||
public static void setFilerJwtSigningKey(String key, long expiresAfterSeconds) {
|
||||
filerSigningKey = FilerSigningKey.of(key, expiresAfterSeconds, DEFAULT_FILER_SIGNING_EXPIRES_AFTER_SECONDS);
|
||||
}
|
||||
|
||||
// Configure jwt.filer_signing.read.key programmatically; expiresAfterSeconds <= 0 uses 60.
|
||||
public static void setFilerJwtReadSigningKey(String key, long expiresAfterSeconds) {
|
||||
filerReadSigningKey = FilerSigningKey.of(key, expiresAfterSeconds, DEFAULT_FILER_READ_SIGNING_EXPIRES_AFTER_SECONDS);
|
||||
}
|
||||
|
||||
// Returns the Authorization header value for an HTTP request addressed to the filer:
|
||||
// a filer JWT for the access level when its key is set, else [filer.basic_auth], else
|
||||
// [basic_auth]; null when none is configured. The filer reads GET and HEAD with the read key.
|
||||
public static String getFilerAuthorizationHeaderValue(boolean isWrite) {
|
||||
FilerSigningKey key = isWrite ? filerSigningKey : filerReadSigningKey;
|
||||
if (key != null) {
|
||||
return "BEARER " + genJwtForFilerServer(key.key, key.expiresAfterSeconds);
|
||||
}
|
||||
if (filerBasicAuthHeaderValue != null) {
|
||||
return filerBasicAuthHeaderValue;
|
||||
}
|
||||
return basicAuthHeaderValue;
|
||||
}
|
||||
|
||||
// Mints an HS256 token with only an "exp" claim, like security.GenJwtForFilerServer.
|
||||
static String genJwtForFilerServer(byte[] signingKey, long expiresAfterSeconds) {
|
||||
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
|
||||
long exp = System.currentTimeMillis() / 1000 + expiresAfterSeconds;
|
||||
String signingInput = encoder.encodeToString("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8))
|
||||
+ "." + encoder.encodeToString(("{\"exp\":" + exp + "}").getBytes(StandardCharsets.UTF_8));
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
|
||||
return signingInput + "." + encoder.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("cannot sign filer jwt", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class FilerSigningKey {
|
||||
final byte[] key;
|
||||
final long expiresAfterSeconds;
|
||||
|
||||
private FilerSigningKey(byte[] key, long expiresAfterSeconds) {
|
||||
this.key = key;
|
||||
this.expiresAfterSeconds = expiresAfterSeconds;
|
||||
}
|
||||
|
||||
static FilerSigningKey of(String key, long expiresAfterSeconds, long defaultExpiresAfterSeconds) {
|
||||
if (Strings.isNullOrEmpty(key)) {
|
||||
return null;
|
||||
}
|
||||
return new FilerSigningKey(key.getBytes(StandardCharsets.UTF_8),
|
||||
expiresAfterSeconds > 0 ? expiresAfterSeconds : defaultExpiresAfterSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
private static String computeBasicAuthHeaderValue(String username, String password) {
|
||||
if (Strings.isNullOrEmpty(username)) {
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class FilerJwtTest {
|
||||
|
||||
@Before
|
||||
@After
|
||||
public void clearCredentials() {
|
||||
FilerSecurityContext.setBasicAuth(null, null);
|
||||
FilerSecurityContext.setFilerBasicAuth(null, null);
|
||||
FilerSecurityContext.setFilerJwtSigningKey(null, 0);
|
||||
FilerSecurityContext.setFilerJwtReadSigningKey(null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filerJwtIsSignedHs256WithExp() throws Exception {
|
||||
long before = System.currentTimeMillis() / 1000;
|
||||
String token = FilerSecurityContext.genJwtForFilerServer("write-key".getBytes(StandardCharsets.UTF_8), 10);
|
||||
long after = System.currentTimeMillis() / 1000;
|
||||
|
||||
String[] parts = token.split("\\.");
|
||||
assertEquals(3, parts.length);
|
||||
assertEquals("{\"alg\":\"HS256\",\"typ\":\"JWT\"}", decode(parts[0]));
|
||||
long exp = exp(decode(parts[1]));
|
||||
assertTrue(exp >= before + 10 && exp <= after + 10);
|
||||
assertEquals(sign("write-key", parts[0] + "." + parts[1]), parts[2]);
|
||||
assertFalse(token.contains("="));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noCredentialsMeansNoFilerHeader() {
|
||||
assertNull(FilerSecurityContext.getFilerAuthorizationHeaderValue(true));
|
||||
assertNull(FilerSecurityContext.getFilerAuthorizationHeaderValue(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessLevelPicksItsSigningKey() throws Exception {
|
||||
FilerSecurityContext.setFilerJwtSigningKey("write-key", 0);
|
||||
FilerSecurityContext.setFilerJwtReadSigningKey("read-key", 0);
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
|
||||
String[] write = bearer(FilerSecurityContext.getFilerAuthorizationHeaderValue(true));
|
||||
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
|
||||
assertTrue(exp(decode(write[1])) - now <= 11);
|
||||
|
||||
String[] read = bearer(FilerSecurityContext.getFilerAuthorizationHeaderValue(false));
|
||||
assertEquals(sign("read-key", read[0] + "." + read[1]), read[2]);
|
||||
assertTrue(exp(decode(read[1])) - now >= 60);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicAuthCoversAccessLevelsWithoutKey() {
|
||||
FilerSecurityContext.setBasicAuth("proxy", "proxy-pass");
|
||||
assertEquals(FilerSecurityContext.getBasicAuthHeaderValue(),
|
||||
FilerSecurityContext.getFilerAuthorizationHeaderValue(false));
|
||||
|
||||
FilerSecurityContext.setFilerBasicAuth("filer", "filer-pass");
|
||||
String filerBasic = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("filer:filer-pass".getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals(filerBasic, FilerSecurityContext.getFilerAuthorizationHeaderValue(false));
|
||||
|
||||
FilerSecurityContext.setFilerJwtSigningKey("write-key", 5);
|
||||
assertTrue(FilerSecurityContext.getFilerAuthorizationHeaderValue(true).startsWith("BEARER "));
|
||||
assertEquals(filerBasic, FilerSecurityContext.getFilerAuthorizationHeaderValue(false));
|
||||
}
|
||||
|
||||
private static String[] bearer(String header) {
|
||||
assertTrue(header.startsWith("BEARER "));
|
||||
return header.substring("BEARER ".length()).split("\\.");
|
||||
}
|
||||
|
||||
private static String decode(String part) {
|
||||
return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static long exp(String payload) {
|
||||
Matcher m = Pattern.compile("^\\{\"exp\":(\\d+)\\}$").matcher(payload);
|
||||
assertTrue(payload, m.matches());
|
||||
return Long.parseLong(m.group(1));
|
||||
}
|
||||
|
||||
private static String sign(String key, String signingInput) throws Exception {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user