|
| 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 | +} |
0 commit comments