-
Notifications
You must be signed in to change notification settings - Fork 0
Add secure HTTP server communication transport #73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BenCodez
wants to merge
9
commits into
main
Choose a base branch
from
codex/http-transport-library
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
87d506f
feat(servercomm): add secure HTTP transport
BenCodez 2951868
fix(servercomm): persist HTTP replay state
BenCodez f62bf69
fix(servercomm): confirm HTTP delivery acknowledgements
BenCodez e9159c1
fix(servercomm): fail closed on partial HTTP state
BenCodez e3f08cc
fix(servercomm): bound authority state and support IPv6
BenCodez 4b92ea3
fix(servercomm): bound proxy state and secure credential roots
BenCodez 1faa2d2
fix(servercomm): separate HTTP acknowledgement directions
BenCodez c01f2cc
Handle HTTP renewal and backend state churn
BenCodez 80a55da
Make HTTP revocation persistence retryable
BenCodez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 65 additions & 0 deletions
65
SimpleAPI/src/main/java/com/bencodez/simpleapi/file/DurableFiles.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package com.bencodez.simpleapi.file; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.channels.FileChannel; | ||
| import java.nio.file.AccessDeniedException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.LinkOption; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.StandardOpenOption; | ||
| import java.util.Locale; | ||
|
|
||
| /** Cross-platform helpers for forcing file contents and published directory entries. */ | ||
| public final class DurableFiles { | ||
| private DurableFiles() { } | ||
|
|
||
| public static void forceFile(Path file) throws IOException { | ||
| try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) { | ||
| channel.force(true); | ||
| } | ||
| } | ||
|
|
||
| public static void forceDirectory(Path directory) throws IOException { | ||
| if (directory == null) return; | ||
| try { | ||
| try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { | ||
| channel.force(true); | ||
| } | ||
| } catch (AccessDeniedException unsupportedDirectoryHandle) { | ||
| // The Windows NIO provider cannot open directory handles. File contents are | ||
| // still forced before atomic publication; do not make persistence unusable. | ||
| if (!isWindowsName(System.getProperty("os.name", ""))) throw unsupportedDirectoryHandle; | ||
| } catch (UnsupportedOperationException unsupportedDirectoryForce) { | ||
| // Some providers support atomic moves but expose no directory-force operation. | ||
| } | ||
| } | ||
|
|
||
| public static boolean deleteIfExists(Path target) throws IOException { | ||
| boolean deleted = Files.deleteIfExists(target); | ||
| if (deleted) forceDirectory(target.toAbsolutePath().normalize().getParent()); | ||
| return deleted; | ||
| } | ||
|
|
||
| public static void forceMoveDirectories(Path source, Path target) throws IOException { | ||
| try { | ||
| Path sourceParent = source.toAbsolutePath().normalize().getParent(); | ||
| Path targetParent = target.toAbsolutePath().normalize().getParent(); | ||
| forceDirectory(targetParent); | ||
| if (sourceParent != null && !sourceParent.equals(targetParent)) forceDirectory(sourceParent); | ||
| } catch (IOException failure) { | ||
| throw new PublishedException(failure); | ||
| } | ||
| } | ||
|
|
||
| public static boolean isWindowsName(String name) { | ||
| return name != null && name.trim().toLowerCase(Locale.ROOT).startsWith("windows"); | ||
| } | ||
|
|
||
| /** Indicates that an atomic rename completed before metadata writeback failed. */ | ||
| @SuppressWarnings("serial") | ||
| public static final class PublishedException extends IOException { | ||
| public PublishedException(IOException cause) { | ||
| super("File was published but its directory metadata could not be forced", cause); | ||
| } | ||
| } | ||
| } |
560 changes: 560 additions & 0 deletions
560
...I/src/main/java/com/bencodez/simpleapi/servercomm/http/HttpBackendTransportConnector.java
Large diffs are not rendered by default.
Oops, something went wrong.
399 changes: 399 additions & 0 deletions
399
...leAPI/src/main/java/com/bencodez/simpleapi/servercomm/http/HttpClientCredentialStore.java
Large diffs are not rendered by default.
Oops, something went wrong.
112 changes: 112 additions & 0 deletions
112
SimpleAPI/src/main/java/com/bencodez/simpleapi/servercomm/http/HttpConnectionCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| package com.bencodez.simpleapi.servercomm.http; | ||
|
|
||
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.time.Clock; | ||
| import java.time.Instant; | ||
| import java.util.Base64; | ||
| import java.util.Locale; | ||
|
|
||
| /** | ||
| * A copy/paste connection code. It deliberately includes no long-lived credential: | ||
| * its only secret is a short-lived, single-use enrollment token. The trailing MAC is a | ||
| * corruption check keyed by that included token; it is not a proxy signature and cannot stop | ||
| * someone who can replace the whole code from replacing it with another valid code. | ||
| */ | ||
| public record HttpConnectionCode(String serverId, URI endpoint, String serverCertificatePin, String caCertificatePin, | ||
| Instant expiresAt, String enrollmentToken) { | ||
| private static final String LEGACY_VERSION = "VPH1"; | ||
| private static final String VERSION = "VPH2"; | ||
| private static final int MAX_CODE_LENGTH = 4096; | ||
|
|
||
| public HttpConnectionCode { | ||
| serverId = HttpTlsIdentity.canonicalServerId(serverId); | ||
| endpoint = validateEndpoint(endpoint); | ||
| serverCertificatePin = validatePin(serverCertificatePin, "server certificate pin"); | ||
| caCertificatePin = validatePin(caCertificatePin, "CA certificate pin"); | ||
| if (expiresAt == null) throw new IllegalArgumentException("Expiry is required"); | ||
| enrollmentToken = validateToken(enrollmentToken); | ||
| } | ||
|
|
||
| public String encode() { | ||
| String serverPart = Base64.getUrlEncoder().withoutPadding() | ||
| .encodeToString(serverId.getBytes(StandardCharsets.UTF_8)); | ||
| return encode(VERSION, serverPart); | ||
| } | ||
|
|
||
| String encodeLegacy() { | ||
| return encode(LEGACY_VERSION, serverId); | ||
| } | ||
|
|
||
| private String encode(String version, String serverPart) { | ||
| String endpointPart = Base64.getUrlEncoder().withoutPadding() | ||
| .encodeToString(endpoint.toASCIIString().getBytes(StandardCharsets.UTF_8)); | ||
| String unsigned = String.join(".", version, serverPart, endpointPart, serverCertificatePin, caCertificatePin, | ||
| Long.toString(expiresAt.getEpochSecond()), enrollmentToken); | ||
| byte[] token = Base64.getUrlDecoder().decode(enrollmentToken); | ||
| return unsigned + "." + HttpTransportSecrets.hmacSha256Url(token, unsigned); | ||
| } | ||
|
|
||
| public boolean isActive(Clock clock) { | ||
| return expiresAt.isAfter(clock.instant()); | ||
| } | ||
|
|
||
| public void requireActive(Clock clock) { | ||
| if (!isActive(clock)) throw new IllegalArgumentException("Connection code has expired"); | ||
| } | ||
|
|
||
| public static HttpConnectionCode parse(String code) { | ||
| if (code == null || code.length() > MAX_CODE_LENGTH || code.indexOf('\n') >= 0 || code.indexOf('\r') >= 0) | ||
| throw new IllegalArgumentException("Connection code is invalid"); | ||
| String[] parts = code.split("\\.", -1); | ||
| if (parts.length != 8 || (!VERSION.equals(parts[0]) && !LEGACY_VERSION.equals(parts[0]))) | ||
| throw new IllegalArgumentException("Connection code is invalid"); | ||
| try { | ||
| String serverId = LEGACY_VERSION.equals(parts[0]) ? parts[1] | ||
| : new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); | ||
| String endpoint = new String(Base64.getUrlDecoder().decode(parts[2]), StandardCharsets.UTF_8); | ||
| String unsigned = String.join(".", parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]); | ||
| byte[] token = Base64.getUrlDecoder().decode(parts[6]); | ||
| String expected = HttpTransportSecrets.hmacSha256Url(token, unsigned); | ||
| if (!HttpTransportSecrets.constantTimeEquals(expected.getBytes(StandardCharsets.US_ASCII), | ||
| parts[7].getBytes(StandardCharsets.US_ASCII))) throw new IllegalArgumentException("Connection code is invalid"); | ||
| return new HttpConnectionCode(serverId, new URI(endpoint), parts[3], parts[4], Instant.ofEpochSecond(Long.parseLong(parts[5])), | ||
| parts[6]); | ||
| } catch (IllegalArgumentException | URISyntaxException failure) { | ||
| throw new IllegalArgumentException("Connection code is invalid", failure); | ||
| } | ||
| } | ||
|
|
||
| private static URI validateEndpoint(URI value) { | ||
| if (value == null || !"https".equalsIgnoreCase(value.getScheme()) || value.getHost() == null | ||
| || value.getUserInfo() != null || value.getFragment() != null || value.getRawQuery() != null) | ||
| throw new IllegalArgumentException("Endpoint must be an absolute HTTPS URL without credentials or query"); | ||
| if (value.getPort() == 0 || value.getPort() > 65535 || value.getPort() < -1) | ||
| throw new IllegalArgumentException("Endpoint port is invalid"); | ||
| String path = value.getRawPath(); | ||
| if (path == null || path.isEmpty()) path = "/"; | ||
| if (!path.endsWith("/")) path += "/"; | ||
| try { | ||
| return new URI("https", null, value.getHost().toLowerCase(Locale.ROOT), value.getPort(), path, null, null); | ||
| } catch (URISyntaxException failure) { | ||
| throw new IllegalArgumentException("Endpoint is invalid", failure); | ||
| } | ||
| } | ||
|
|
||
| private static String validatePin(String pin, String name) { | ||
| if (pin == null || !pin.matches("[0-9a-fA-F]{64}")) throw new IllegalArgumentException(name + " is invalid"); | ||
| return pin.toLowerCase(Locale.ROOT); | ||
| } | ||
|
|
||
| private static String validateToken(String token) { | ||
| if (token == null || token.length() < 43 || token.length() > 128 || !token.matches("[A-Za-z0-9_-]+")) | ||
| throw new IllegalArgumentException("Enrollment token is invalid"); | ||
| try { | ||
| if (Base64.getUrlDecoder().decode(token).length < 32) throw new IllegalArgumentException("Enrollment token is invalid"); | ||
| return token; | ||
| } catch (IllegalArgumentException failure) { | ||
| throw new IllegalArgumentException("Enrollment token is invalid", failure); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an HTTPS endpoint uses a percent-escaped base path, such as
https://example.com/api%20root/,getRawPath()returns/api%20root/but this component constructor escapes the percent sign again, producing/api%2520root/. Encoding and parsing a connection code repeats the corruption, so enrollment and transport requests target the wrong reverse-proxy route; preserve the already-escaped raw path when rebuilding the URI.Useful? React with 👍 / 👎.