diff --git a/.github/workflows/java_unit_tests.yml b/.github/workflows/java_unit_tests.yml index ed29f8dab3..7e9639c15c 100644 --- a/.github/workflows/java_unit_tests.yml +++ b/.github/workflows/java_unit_tests.yml @@ -44,7 +44,7 @@ jobs: - name: Run Client Unit Tests working-directory: other/java/client run: | - mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest + mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest,FilerJwtTest - name: Run HDFS3 Configuration Tests working-directory: other/java/hdfs3 diff --git a/other/java/client/src/main/java/seaweedfs/client/FilerCredentials.java b/other/java/client/src/main/java/seaweedfs/client/FilerCredentials.java new file mode 100644 index 0000000000..3f97d81ff7 --- /dev/null +++ b/other/java/client/src/main/java/seaweedfs/client/FilerCredentials.java @@ -0,0 +1,102 @@ +package seaweedfs.client; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Base64; + +// Credentials for a filer's own HTTP port: [filer.basic_auth], [jwt.filer_signing] and +// [jwt.filer_signing.read]. Each FilerClient starts from its own copy of the security.toml values. +public final class FilerCredentials { + + private static final long DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS = 10; + private static final long DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS = 60; + + private volatile String basicAuthUser = ""; + private volatile String basicAuthPassword = ""; + private volatile String basicAuthHeaderValue; + private volatile String signingKey = ""; + private volatile long signingExpiresAfterSeconds = DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS; + private volatile String readSigningKey = ""; + private volatile long readSigningExpiresAfterSeconds = DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS; + + public FilerCredentials() { + } + + public FilerCredentials(FilerCredentials other) { + synchronized (other) { + basicAuthUser = other.basicAuthUser; + basicAuthPassword = other.basicAuthPassword; + basicAuthHeaderValue = other.basicAuthHeaderValue; + signingKey = other.signingKey; + signingExpiresAfterSeconds = other.signingExpiresAfterSeconds; + readSigningKey = other.readSigningKey; + readSigningExpiresAfterSeconds = other.readSigningExpiresAfterSeconds; + } + } + + // A null argument keeps the current value. Like the filer, an empty password turns + // Basic Auth off and an empty user is allowed. + public synchronized void setBasicAuth(String user, String password) { + if (user != null) { + basicAuthUser = user; + } + if (password != null) { + basicAuthPassword = password; + } + basicAuthHeaderValue = basicAuthPassword.isEmpty() ? null + : FilerSecurityContext.encodeBasicAuth(basicAuthUser, basicAuthPassword); + } + + // A null key or expiresAfterSeconds <= 0 keeps the current value; an empty key turns signing off. + public synchronized void setJwtSigningKey(String key, long expiresAfterSeconds) { + if (key != null) { + signingKey = key; + } + if (expiresAfterSeconds > 0) { + signingExpiresAfterSeconds = expiresAfterSeconds; + } + } + + // Same as setJwtSigningKey, for the read key. + public synchronized void setJwtReadSigningKey(String key, long expiresAfterSeconds) { + if (key != null) { + readSigningKey = key; + } + if (expiresAfterSeconds > 0) { + readSigningExpiresAfterSeconds = expiresAfterSeconds; + } + } + + // 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 String getAuthorizationHeaderValue(boolean isWrite) { + String key = isWrite ? signingKey : readSigningKey; + if (!key.isEmpty()) { + return "BEARER " + genJwtForFilerServer(key.getBytes(StandardCharsets.UTF_8), + isWrite ? signingExpiresAfterSeconds : readSigningExpiresAfterSeconds); + } + String basicAuth = basicAuthHeaderValue; + if (basicAuth != null) { + return basicAuth; + } + return FilerSecurityContext.getBasicAuthHeaderValue(); + } + + // 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); + } + } +} diff --git a/other/java/client/src/main/java/seaweedfs/client/FilerGrpcClient.java b/other/java/client/src/main/java/seaweedfs/client/FilerGrpcClient.java index 7a06bb5268..ac33464ea7 100644 --- a/other/java/client/src/main/java/seaweedfs/client/FilerGrpcClient.java +++ b/other/java/client/src/main/java/seaweedfs/client/FilerGrpcClient.java @@ -50,6 +50,7 @@ public class FilerGrpcClient { private String replication = ""; private int volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT; private String filerAddress; + private final FilerCredentials filerCredentials = new FilerCredentials(FilerSecurityContext.getFilerCredentials()); public FilerGrpcClient(String host, int port, int grpcPort, String cn) { this(host, port, grpcPort, cn, sslContext); @@ -154,6 +155,11 @@ public class FilerGrpcClient { return SeaweedFilerGrpc.newFutureStub(getChannel()); } + // Credentials for this client's requests to the filer's HTTP port; changes affect only this client. + public FilerCredentials getFilerCredentials() { + return filerCredentials; + } + public void setAccessVolumeServerDirectly() { this.volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT; } @@ -183,9 +189,18 @@ public class FilerGrpcClient { case VOLUME_SERVER_ACCESS_PUBLIC_URL: return String.format("%s://%s/%s", protocol, publicUrl, chunkId); case VOLUME_SERVER_ACCESS_FILER_PROXY: - return String.format("%s://%s/?proxyChunkId=%s", protocol, this.filerAddress, chunkId); + return proxyChunkUrlPrefix() + chunkId; default: return String.format("%s://%s/%s", protocol, url, chunkId); } } + + // Reports whether a chunk URL addresses this client's filer chunk proxy rather than a volume server. + public boolean isProxyChunkUrl(String url) { + return isAccessVolumeServerByFilerProxy() && url != null && url.startsWith(proxyChunkUrlPrefix()); + } + + private String proxyChunkUrlPrefix() { + return String.format("%s://%s/?proxyChunkId=", protocol, this.filerAddress); + } } diff --git a/other/java/client/src/main/java/seaweedfs/client/FilerSecurityContext.java b/other/java/client/src/main/java/seaweedfs/client/FilerSecurityContext.java index 64a6f13df8..d8fb098bf7 100644 --- a/other/java/client/src/main/java/seaweedfs/client/FilerSecurityContext.java +++ b/other/java/client/src/main/java/seaweedfs/client/FilerSecurityContext.java @@ -43,6 +43,8 @@ public abstract class FilerSecurityContext extends SslContext { // volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode. private static volatile String basicAuthHeaderValue; + private static final FilerCredentials filerCredentials = new FilerCredentials(); + static { String securityFileName = "security.toml"; @@ -64,6 +66,11 @@ public abstract class FilerSecurityContext extends SslContext { basicAuthHeaderValue = computeBasicAuthHeaderValue( toml.getString("basic_auth.username"), toml.getString("basic_auth.password")); + filerCredentials.setBasicAuth(toml.getString("filer.basic_auth.user"), toml.getString("filer.basic_auth.password")); + filerCredentials.setJwtSigningKey(toml.getString("jwt.filer_signing.key"), + toml.getLong("jwt.filer_signing.expires_after_seconds", 0L)); + filerCredentials.setJwtReadSigningKey(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); @@ -86,7 +93,7 @@ public abstract class FilerSecurityContext extends SslContext { } } - if (toml.getBoolean("https.client.enabled")) { + if (toml.getBoolean("https.client.enabled", false)) { httpTrustCertCollectionFilePath = toml.getString("https.client.ca"); logger.debug("loading HTTP ca from {}", httpTrustCertCollectionFilePath); httpClientCertChainFilePath = toml.getString("https.client.cert"); @@ -146,11 +153,20 @@ public abstract class FilerSecurityContext extends SslContext { return basicAuthHeaderValue; } + // The filer credentials read from security.toml; each FilerClient copies them. + static FilerCredentials getFilerCredentials() { + return filerCredentials; + } + private static String computeBasicAuthHeaderValue(String username, String password) { if (Strings.isNullOrEmpty(username)) { return null; } - String credentials = username + ":" + (password == null ? "" : password); + return encodeBasicAuth(username, password == null ? "" : password); + } + + static String encodeBasicAuth(String username, String password) { + String credentials = username + ":" + password; return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); } diff --git a/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java b/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java index ad22cac8f0..c7afc5a040 100644 --- a/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java +++ b/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java @@ -136,7 +136,7 @@ public class SeaweedRead { for (FilerProto.Location location : locations.getLocationsList()) { String url = filerClient.getChunkUrl(chunkView.fileId, location.getUrl(), location.getPublicUrl()); try { - byte[] fetched = doFetchOneFullChunkData(chunkView, url); + byte[] fetched = doFetchOneFullChunkData(filerClient, chunkView, url); // An empty (or null) body for a chunk we are reading from is never // valid; treat it as a transient failure so the retry loop tries // another location and backs off, rather than caching an empty chunk. @@ -171,15 +171,19 @@ public class SeaweedRead { } - private static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException { + private static byte[] doFetchOneFullChunkData(FilerClient filerClient, ChunkView chunkView, String url) throws IOException { HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"); - String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue(); - if (basicAuthHeader != null) { - request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); + String authHeader = FilerSecurityContext.getBasicAuthHeaderValue(); + if (filerClient.isProxyChunkUrl(url)) { + authHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(false); + request.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG); + } + if (authHeader != null) { + request.setHeader(HttpHeaders.AUTHORIZATION, authHeader); } byte[] data = null; @@ -187,6 +191,11 @@ public class SeaweedRead { CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request); try { + int status = response.getStatusLine().getStatusCode(); + if (status / 100 != 2) { + throw new IOException("fetch " + url + ": " + response.getStatusLine()); + } + HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); diff --git a/other/java/client/src/main/java/seaweedfs/client/SeaweedUtil.java b/other/java/client/src/main/java/seaweedfs/client/SeaweedUtil.java index 3628a10d16..1c03bb70dd 100644 --- a/other/java/client/src/main/java/seaweedfs/client/SeaweedUtil.java +++ b/other/java/client/src/main/java/seaweedfs/client/SeaweedUtil.java @@ -1,5 +1,6 @@ package seaweedfs.client; +import org.apache.http.client.config.RequestConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; @@ -90,4 +91,7 @@ public class SeaweedUtil { } return host + ":" + port; } + + // Redirects would carry the filer credential to the redirect target. + static final RequestConfig PROXY_CHUNK_REQUEST_CONFIG = RequestConfig.custom().setRedirectsEnabled(false).build(); } diff --git a/other/java/client/src/main/java/seaweedfs/client/SeaweedWrite.java b/other/java/client/src/main/java/seaweedfs/client/SeaweedWrite.java index 9c639d2133..e2c42e386b 100644 --- a/other/java/client/src/main/java/seaweedfs/client/SeaweedWrite.java +++ b/other/java/client/src/main/java/seaweedfs/client/SeaweedWrite.java @@ -135,7 +135,7 @@ public class SeaweedWrite { cipherKeyString = ByteString.copyFrom(cipherKey); } - String etag = multipartUpload(targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey); + String etag = multipartUpload(filerClient, targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey); return FilerProto.FileChunk.newBuilder() .setFileId(fileId) @@ -167,7 +167,8 @@ public class SeaweedWrite { } } - private static String multipartUpload(String targetUrl, + private static String multipartUpload(FilerClient filerClient, + String targetUrl, String auth, final byte[] bytes, final long bytesOffset, final long bytesLength, @@ -193,7 +194,14 @@ public class SeaweedWrite { } HttpPost post = new HttpPost(targetUrl); - if (auth != null && auth.length() != 0) { + String filerAuthHeader = null; + if (filerClient.isProxyChunkUrl(targetUrl)) { + filerAuthHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(true); + post.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG); + } + if (filerAuthHeader != null) { + post.addHeader("Authorization", filerAuthHeader); + } else if (auth != null && auth.length() != 0) { // Volume JWT and Basic Auth both use the Authorization header; the JWT wins // when present. Front the volume with a JWT-free path to use Basic Auth here. post.addHeader("Authorization", "BEARER " + auth); diff --git a/other/java/client/src/test/java/seaweedfs/client/FilerJwtTest.java b/other/java/client/src/test/java/seaweedfs/client/FilerJwtTest.java new file mode 100644 index 0000000000..7458080a93 --- /dev/null +++ b/other/java/client/src/test/java/seaweedfs/client/FilerJwtTest.java @@ -0,0 +1,244 @@ +package seaweedfs.client; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.stub.StreamObserver; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +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 { + + private FilerCredentials credentials; + + @Before + public void clearCredentials() { + FilerSecurityContext.setBasicAuth(null, null); + credentials = new FilerCredentials(); + } + + @After + public void clearProxyBasicAuth() { + FilerSecurityContext.setBasicAuth(null, null); + } + + @Test + public void filerJwtIsSignedHs256WithExp() throws Exception { + long before = System.currentTimeMillis() / 1000; + String token = FilerCredentials.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(credentials.getAuthorizationHeaderValue(true)); + assertNull(credentials.getAuthorizationHeaderValue(false)); + } + + @Test + public void accessLevelPicksItsSigningKey() throws Exception { + credentials.setJwtSigningKey("write-key", 0); + credentials.setJwtReadSigningKey("read-key", 0); + long now = System.currentTimeMillis() / 1000; + + String[] write = bearer(credentials.getAuthorizationHeaderValue(true)); + assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]); + assertTrue(exp(decode(write[1])) - now <= 11); + + String[] read = bearer(credentials.getAuthorizationHeaderValue(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(), + credentials.getAuthorizationHeaderValue(false)); + + credentials.setBasicAuth("filer", "filer-pass"); + String filerBasic = "Basic " + Base64.getEncoder() + .encodeToString("filer:filer-pass".getBytes(StandardCharsets.UTF_8)); + assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false)); + + credentials.setJwtSigningKey("write-key", 5); + assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("BEARER ")); + assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false)); + } + + @Test + public void filerBasicAuthFollowsThePassword() { + credentials.setBasicAuth("filer", ""); + assertNull(credentials.getAuthorizationHeaderValue(false)); + + credentials.setBasicAuth("", "only-pass"); + assertEquals("Basic " + Base64.getEncoder().encodeToString(":only-pass".getBytes(StandardCharsets.UTF_8)), + credentials.getAuthorizationHeaderValue(false)); + } + + @Test + public void nullKeepsTheCurrentValue() throws Exception { + credentials.setBasicAuth("filer", "old-pass"); + credentials.setBasicAuth(null, "new-pass"); + assertEquals("Basic " + Base64.getEncoder().encodeToString("filer:new-pass".getBytes(StandardCharsets.UTF_8)), + credentials.getAuthorizationHeaderValue(false)); + + credentials.setJwtSigningKey("write-key", 0); + credentials.setJwtSigningKey(null, 300); + long now = System.currentTimeMillis() / 1000; + String[] write = bearer(credentials.getAuthorizationHeaderValue(true)); + assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]); + assertTrue(exp(decode(write[1])) - now >= 300); + + credentials.setJwtSigningKey("", 0); + assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("Basic ")); + } + + @Test + public void copiesSignIndependently() throws Exception { + credentials.setJwtSigningKey("shared-key", 0); + FilerCredentials a = new FilerCredentials(credentials); + FilerCredentials b = new FilerCredentials(credentials); + b.setJwtSigningKey("b-key", 0); + + String[] fromA = bearer(a.getAuthorizationHeaderValue(true)); + String[] fromB = bearer(b.getAuthorizationHeaderValue(true)); + assertEquals(sign("shared-key", fromA[0] + "." + fromA[1]), fromA[2]); + assertEquals(sign("b-key", fromB[0] + "." + fromB[1]), fromB[2]); + String[] fromDefaults = bearer(credentials.getAuthorizationHeaderValue(true)); + assertEquals(sign("shared-key", fromDefaults[0] + "." + fromDefaults[1]), fromDefaults[2]); + } + + @Test + public void onlyFilerProxyUrlsAreFilerRequests() throws Exception { + Server filerGrpc = startFilerGrpc(); + FilerClient filerClient = new FilerClient("127.0.0.1", 8888, filerGrpc.getPort(), ""); + try { + String proxyUrl = "http://127.0.0.1:8888/?proxyChunkId=3,01637037d6"; + assertFalse(filerClient.isProxyChunkUrl(proxyUrl)); + + filerClient.setAccessVolumeServerByFilerProxy(); + assertEquals(proxyUrl, filerClient.getChunkUrl("3,01637037d6", "volume:8080", "volume:8080")); + assertTrue(filerClient.isProxyChunkUrl(proxyUrl)); + assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/3,01637037d6")); + assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/?proxyChunkId=/3,01637037d6")); + assertFalse(filerClient.isProxyChunkUrl("http://127.0.0.1:8888.example/?proxyChunkId=3,01637037d6")); + assertFalse(filerClient.isProxyChunkUrl(null)); + } finally { + filerClient.shutdown(); + filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + public void proxyChunkReadDoesNotFollowRedirects() throws Exception { + AtomicInteger targetHits = new AtomicInteger(); + HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + target.createContext("/", exchange -> { + targetHits.incrementAndGet(); + respond(exchange, 200, "leaked"); + }); + List filerAuth = new CopyOnWriteArrayList<>(); + HttpServer filer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + filer.createContext("/", exchange -> { + filerAuth.add(exchange.getRequestHeaders().getFirst("Authorization")); + if (filerAuth.size() == 1) { + exchange.getResponseHeaders().set("Location", "http://127.0.0.1:" + target.getAddress().getPort() + "/"); + respond(exchange, 302, ""); + } else { + respond(exchange, 200, "chunk"); + } + }); + Server filerGrpc = startFilerGrpc(); + target.start(); + filer.start(); + FilerClient filerClient = new FilerClient("127.0.0.1", filer.getAddress().getPort(), filerGrpc.getPort(), ""); + try { + filerClient.setAccessVolumeServerByFilerProxy(); + filerClient.getFilerCredentials().setJwtReadSigningKey("read-key", 0); + FilerProto.Locations locations = FilerProto.Locations.newBuilder() + .addLocations(FilerProto.Location.newBuilder().setUrl("volume:8080")).build(); + + byte[] data = SeaweedRead.doFetchFullChunkData(filerClient, + new SeaweedRead.ChunkView("3,01637037d6", 0, 5, 0, true, null, false), locations); + + assertEquals("chunk", new String(data, StandardCharsets.UTF_8)); + assertEquals(0, targetHits.get()); + assertEquals(2, filerAuth.size()); + assertTrue(filerAuth.get(0).startsWith("BEARER ")); + } finally { + filerClient.shutdown(); + filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + filer.stop(0); + target.stop(0); + } + } + + private static Server startFilerGrpc() throws IOException { + return ServerBuilder.forPort(0).addService(new SeaweedFilerGrpc.SeaweedFilerImplBase() { + @Override + public void getFilerConfiguration(FilerProto.GetFilerConfigurationRequest request, + StreamObserver observer) { + observer.onNext(FilerProto.GetFilerConfigurationResponse.getDefaultInstance()); + observer.onCompleted(); + } + }).build().start(); + } + + private static void respond(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length); + exchange.getResponseBody().write(bytes); + exchange.close(); + } + + 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))); + } +} diff --git a/other/java/hdfs3/README.md b/other/java/hdfs3/README.md index 8d1591ba04..d181da7def 100644 --- a/other/java/hdfs3/README.md +++ b/other/java/hdfs3/README.md @@ -149,6 +149,75 @@ The test suite covers: hadoop fs -put local.txt seaweedfs://localhost:8888/test/ ``` +### Secured filer + +With `fs.seaweed.volume.server.access` set to `filerProxy`, chunk reads and writes go to the +filer's HTTP port, so they need the filer's HTTP credentials. The client signs a filer JWT +when it has the filer's `jwt.filer_signing` key (writes) or +`jwt.filer_signing.read` key (reads), and otherwise sends the `[filer.basic_auth]` +credentials. These credentials are sent only to the filer, never to volume servers. In `direct` +and `publicUrl` modes chunk requests go straight to volume servers, so the filer's HTTP +credentials are not used; writes carry the volume token from the volume assignment as before. +gRPC mTLS comes from the `[grpc]` section as before, but it does not cover these HTTP chunk requests: +to keep the credentials off plain HTTP, serve the filer HTTP port over HTTPS (`[https.filer]` +on the filer) and enable `[https.client]` here. The client checks the certificate chain but +not the host name, so set `https.client.ca` to a CA that issues certificates only for your +SeaweedFS servers. + +`security.toml` (read from `./`, `~/.seaweedfs/` or `/etc/seaweedfs/`), using the filer's +own values: + +```toml +[jwt.filer_signing] +key = "" + +[jwt.filer_signing.read] +key = "" + +# or, for a filer with Basic Auth +[filer.basic_auth] +user = "" +password = "" + +[grpc] +ca = "/etc/seaweedfs/ca.crt" + +[grpc.client] +cert = "/etc/seaweedfs/client.crt" +key = "/etc/seaweedfs/client.key" + +[https.client] +enabled = true +ca = "/etc/seaweedfs/ca.crt" +cert = "/etc/seaweedfs/client.crt" +key = "/etc/seaweedfs/client.key" +``` + +The same values can be set in `core-site.xml`. Each option overrides only its own +`security.toml` value (for example, a password alone keeps the `security.toml` user), and +applies only to that filesystem. The secrets can also come from a Hadoop credential provider: + +```xml + + fs.seaweed.volume.server.access + filerProxy + + + fs.seaweed.filer.jwt.signing.key + filer write key + + + fs.seaweed.filer.jwt.signing.read.key + filer read key + + + +``` + ## Continuous Integration For CI environments, tests can be run in two modes: diff --git a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystem.java b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystem.java index 513266d699..f98d9e2c7f 100644 --- a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystem.java +++ b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystem.java @@ -10,6 +10,7 @@ import org.apache.hadoop.util.Progressable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import seaweedfs.client.FilerProto; +import seaweedfs.client.FilerCredentials; import java.io.FileNotFoundException; import java.io.IOException; @@ -30,6 +31,12 @@ public class SeaweedFileSystem extends FileSystem { public static final String FS_SEAWEED_VOLUME_SERVER_ACCESS = "fs.seaweed.volume.server.access"; public static final int FS_SEAWEED_DEFAULT_BUFFER_SIZE = 4 * 1024 * 1024; public static final String FS_SEAWEED_FILER_CN = "fs.seaweed.filer.cn"; + public static final String FS_SEAWEED_FILER_BASIC_AUTH_USER = "fs.seaweed.filer.basic.auth.user"; + public static final String FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD = "fs.seaweed.filer.basic.auth.password"; + public static final String FS_SEAWEED_FILER_JWT_SIGNING_KEY = "fs.seaweed.filer.jwt.signing.key"; + public static final String FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES = "fs.seaweed.filer.jwt.signing.expires.after.seconds"; + public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY = "fs.seaweed.filer.jwt.signing.read.key"; + public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES = "fs.seaweed.filer.jwt.signing.read.expires.after.seconds"; private static final Logger LOG = LoggerFactory.getLogger(SeaweedFileSystem.class); @@ -69,6 +76,21 @@ public class SeaweedFileSystem extends FileSystem { seaweedFileSystemStore = new SeaweedFileSystemStore(host, port, grpcPort, cn, conf); } + // Each option set here overrides only its own [filer.basic_auth] or [jwt.filer_signing] value of security.toml. + static void applyFilerCredentials(Configuration conf, FilerCredentials credentials) throws IOException { + credentials.setBasicAuth(conf.get(FS_SEAWEED_FILER_BASIC_AUTH_USER), + secret(conf, FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD)); + credentials.setJwtSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_KEY), + conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 0)); + credentials.setJwtReadSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY), + conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 0)); + } + + private static String secret(Configuration conf, String name) throws IOException { + char[] value = conf.getPassword(name); + return value == null ? null : new String(value); + } + @Override public void close() throws IOException { super.close(); diff --git a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java index c55d057976..f4fa558634 100644 --- a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java +++ b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java @@ -27,9 +27,15 @@ public class SeaweedFileSystemStore { private FilerClient filerClient; private Configuration conf; - public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) { + public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) throws IOException { filerClient = new FilerClient(host, port, grpcPort, cn); this.conf = conf; + try { + SeaweedFileSystem.applyFilerCredentials(conf, filerClient.getFilerCredentials()); + } catch (IOException | RuntimeException e) { + close(); + throw e; + } String volumeServerAccessMode = this.conf.get(FS_SEAWEED_VOLUME_SERVER_ACCESS, "direct"); if (volumeServerAccessMode.equals("publicUrl")) { filerClient.setAccessVolumeServerByPublicUrl(); diff --git a/other/java/hdfs3/src/test/java/seaweed/hdfs/SeaweedFileSystemConfigTest.java b/other/java/hdfs3/src/test/java/seaweed/hdfs/SeaweedFileSystemConfigTest.java index bcc08b8e2a..1cb5899622 100644 --- a/other/java/hdfs3/src/test/java/seaweed/hdfs/SeaweedFileSystemConfigTest.java +++ b/other/java/hdfs3/src/test/java/seaweed/hdfs/SeaweedFileSystemConfigTest.java @@ -4,6 +4,12 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.junit.Before; import org.junit.Test; +import seaweedfs.client.FilerCredentials; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Base64; import static org.junit.Assert.*; @@ -87,4 +93,57 @@ public class SeaweedFileSystemConfigTest { // Test default port constant assertEquals(8888, SeaweedFileSystem.FS_SEAWEED_DEFAULT_PORT); } + + @Test + public void testFilerCredentialsFromConfiguration() throws Exception { + FilerCredentials credentials = new FilerCredentials(); + conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_USER, "alice"); + conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "s3cret"); + SeaweedFileSystem.applyFilerCredentials(conf, credentials); + String basic = "Basic " + Base64.getEncoder().encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8)); + assertEquals(basic, credentials.getAuthorizationHeaderValue(true)); + + conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_KEY, "write-key"); + conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 120); + SeaweedFileSystem.applyFilerCredentials(conf, credentials); + long now = System.currentTimeMillis() / 1000; + assertTrue(signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now >= 119); + assertEquals(basic, credentials.getAuthorizationHeaderValue(false)); + + conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY, "read-key"); + conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 240); + SeaweedFileSystem.applyFilerCredentials(conf, credentials); + long readExp = signedExp(credentials.getAuthorizationHeaderValue(false), "read-key") - now; + assertTrue(readExp >= 239 && readExp <= 245); + long writeExp = signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now; + assertTrue(writeExp >= 119 && writeExp <= 125); + } + + @Test + public void testFilerCredentialOptionsOverrideOneValueEach() throws Exception { + FilerCredentials credentials = new FilerCredentials(); + credentials.setBasicAuth("toml-user", "toml-pass"); + credentials.setJwtReadSigningKey("toml-read-key", 0); + + conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "new-pass"); + conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 300); + SeaweedFileSystem.applyFilerCredentials(conf, credentials); + + assertEquals("Basic " + Base64.getEncoder().encodeToString("toml-user:new-pass".getBytes(StandardCharsets.UTF_8)), + credentials.getAuthorizationHeaderValue(true)); + long exp = signedExp(credentials.getAuthorizationHeaderValue(false), "toml-read-key"); + assertTrue(exp - System.currentTimeMillis() / 1000 >= 299); + } + + // Asserts the header is a filer JWT signed with key and returns its exp claim. + private static long signedExp(String header, String key) throws Exception { + assertTrue(header, header.startsWith("BEARER ")); + String[] parts = header.substring("BEARER ".length()).split("\\."); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString( + mac.doFinal((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8))), parts[2]); + String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + return Long.parseLong(payload.replaceAll("[^0-9]", "")); + } }