Skip to content

Commit d169a12

Browse files
committed
feat(registry): add sha256 digests and bearer challenge parsing
1 parent 9803d10 commit d169a12

4 files changed

Lines changed: 213 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package io.github.intisy.docker.registry;
2+
3+
import java.io.UnsupportedEncodingException;
4+
import java.net.URLEncoder;
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
import java.util.regex.Matcher;
8+
import java.util.regex.Pattern;
9+
10+
/**
11+
* A parsed {@code WWW-Authenticate: Bearer ...} challenge.
12+
*
13+
* @author Finn Birich
14+
*/
15+
public final class AuthChallenge {
16+
private static final String BEARER_PREFIX = "Bearer ";
17+
private static final Pattern PARAMETER = Pattern.compile("([a-zA-Z_]+)=\"([^\"]*)\"");
18+
19+
private final String realm;
20+
private final String service;
21+
private final String scope;
22+
23+
private AuthChallenge(String realm, String service, String scope) {
24+
this.realm = realm;
25+
this.service = service;
26+
this.scope = scope;
27+
}
28+
29+
/**
30+
* @return null when the header is absent or is not a bearer challenge, which is the normal
31+
* case for an unauthenticated registry rather than an error.
32+
*/
33+
public static AuthChallenge parse(String header) {
34+
if (header == null || !header.startsWith(BEARER_PREFIX)) {
35+
return null;
36+
}
37+
Map<String, String> parameters = new HashMap<String, String>();
38+
Matcher matcher = PARAMETER.matcher(header.substring(BEARER_PREFIX.length()));
39+
while (matcher.find()) {
40+
parameters.put(matcher.group(1), matcher.group(2));
41+
}
42+
if (!parameters.containsKey("realm")) {
43+
return null;
44+
}
45+
return new AuthChallenge(parameters.get("realm"), parameters.get("service"), parameters.get("scope"));
46+
}
47+
48+
public String realm() {
49+
return realm;
50+
}
51+
52+
public String service() {
53+
return service;
54+
}
55+
56+
public String scope() {
57+
return scope;
58+
}
59+
60+
public String tokenUrl(String requestedScope) {
61+
StringBuilder url = new StringBuilder(realm);
62+
url.append('?');
63+
if (service != null) {
64+
url.append("service=").append(encode(service)).append('&');
65+
}
66+
url.append("scope=").append(encode(requestedScope));
67+
return url.toString();
68+
}
69+
70+
private static String encode(String value) {
71+
try {
72+
return URLEncoder.encode(value, "UTF-8");
73+
} catch (UnsupportedEncodingException impossible) {
74+
throw new IllegalStateException("UTF-8 is required by every JRE", impossible);
75+
}
76+
}
77+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package io.github.intisy.docker.registry;
2+
3+
import java.io.IOException;
4+
import java.io.InputStream;
5+
import java.security.MessageDigest;
6+
import java.security.NoSuchAlgorithmException;
7+
8+
/**
9+
* @author Finn Birich
10+
*/
11+
public final class Digests {
12+
private static final char[] HEX = "0123456789abcdef".toCharArray();
13+
private static final int BUFFER_BYTES = 64 * 1024;
14+
15+
public static String sha256(byte[] content) {
16+
MessageDigest digest = newDigest();
17+
digest.update(content);
18+
return format(digest.digest());
19+
}
20+
21+
public static String sha256(InputStream content) throws IOException {
22+
MessageDigest digest = newDigest();
23+
byte[] buffer = new byte[BUFFER_BYTES];
24+
int read;
25+
while ((read = content.read(buffer)) != -1) {
26+
digest.update(buffer, 0, read);
27+
}
28+
return format(digest.digest());
29+
}
30+
31+
private static MessageDigest newDigest() {
32+
try {
33+
return MessageDigest.getInstance("SHA-256");
34+
} catch (NoSuchAlgorithmException impossible) {
35+
throw new IllegalStateException("SHA-256 is required by every JRE", impossible);
36+
}
37+
}
38+
39+
private static String format(byte[] raw) {
40+
StringBuilder hex = new StringBuilder("sha256:");
41+
for (int i = 0; i < raw.length; i++) {
42+
int value = raw[i] & 0xff;
43+
hex.append(HEX[value >>> 4]).append(HEX[value & 0x0f]);
44+
}
45+
return hex.toString();
46+
}
47+
48+
private Digests() {}
49+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package io.github.intisy.docker.unit;
2+
3+
import io.github.intisy.docker.registry.AuthChallenge;
4+
import org.junit.jupiter.api.Tag;
5+
import org.junit.jupiter.api.Test;
6+
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
8+
import static org.junit.jupiter.api.Assertions.assertNull;
9+
10+
@Tag("unit")
11+
public class AuthChallengeTest {
12+
private static final String DOCKER_HUB_HEADER =
13+
"Bearer realm=\"https://auth.docker.io/token\",service=\"registry.docker.io\"";
14+
15+
@Test
16+
public void parsesRealmAndService() {
17+
AuthChallenge challenge = AuthChallenge.parse(DOCKER_HUB_HEADER);
18+
assertEquals("https://auth.docker.io/token", challenge.realm());
19+
assertEquals("registry.docker.io", challenge.service());
20+
}
21+
22+
@Test
23+
public void buildsTheTokenUrlWithServiceAndScope() {
24+
AuthChallenge challenge = AuthChallenge.parse(DOCKER_HUB_HEADER);
25+
assertEquals("https://auth.docker.io/token?service=registry.docker.io"
26+
+ "&scope=repository%3Alibrary%2Feclipse-temurin%3Apull",
27+
challenge.tokenUrl("repository:library/eclipse-temurin:pull"));
28+
}
29+
30+
@Test
31+
public void headerWithAnEmbeddedScopeIsKept() {
32+
AuthChallenge challenge = AuthChallenge.parse(
33+
"Bearer realm=\"https://auth.example.com/token\",service=\"reg\",scope=\"repository:a/b:pull\"");
34+
assertEquals("repository:a/b:pull", challenge.scope());
35+
}
36+
37+
@Test
38+
public void bearerHeaderWithoutRealmIsNotAChallenge() {
39+
assertNull(AuthChallenge.parse("Bearer service=\"registry.docker.io\""));
40+
}
41+
42+
/**
43+
* A registry that answers Basic, or no challenge at all, must read as "no bearer flow here"
44+
* rather than as a malformed bearer challenge. The in-cluster registry is unauthenticated and
45+
* sends no challenge at all, so this is the path it takes.
46+
*/
47+
@Test
48+
public void nonBearerHeaderIsNotAChallenge() {
49+
assertNull(AuthChallenge.parse("Basic realm=\"registry\""));
50+
assertNull(AuthChallenge.parse(null));
51+
}
52+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package io.github.intisy.docker.unit;
2+
3+
import io.github.intisy.docker.registry.Digests;
4+
import org.junit.jupiter.api.Tag;
5+
import org.junit.jupiter.api.Test;
6+
7+
import java.io.ByteArrayInputStream;
8+
import java.io.IOException;
9+
import java.nio.charset.StandardCharsets;
10+
11+
import static org.junit.jupiter.api.Assertions.assertEquals;
12+
13+
@Tag("unit")
14+
public class DigestsTest {
15+
private static final String EMPTY_SHA256 =
16+
"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
17+
private static final String ABC_SHA256 =
18+
"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
19+
20+
@Test
21+
public void emptyInputHasTheKnownEmptyDigest() {
22+
assertEquals(EMPTY_SHA256, Digests.sha256(new byte[0]));
23+
}
24+
25+
@Test
26+
public void knownVectorMatches() {
27+
assertEquals(ABC_SHA256, Digests.sha256("abc".getBytes(StandardCharsets.UTF_8)));
28+
}
29+
30+
@Test
31+
public void streamAndBytesAgree() throws IOException {
32+
byte[] payload = "the quick brown fox".getBytes(StandardCharsets.UTF_8);
33+
assertEquals(Digests.sha256(payload), Digests.sha256(new ByteArrayInputStream(payload)));
34+
}
35+
}

0 commit comments

Comments
 (0)