Add uri checking

This commit is contained in:
Carl Mastrangelo 2015-10-23 11:03:07 -07:00
parent efac679abc
commit f39b67c0e8
2 changed files with 62 additions and 5 deletions

View File

@ -31,6 +31,7 @@
package io.grpc.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static io.grpc.Status.Code.CANCELLED;
import static io.grpc.Status.Code.DEADLINE_EXCEEDED;
@ -319,10 +320,6 @@ public final class GrpcUtil {
} catch (URISyntaxException ex) {
throw new IllegalArgumentException("Invalid authority: " + authority, ex);
}
if (uri.getUserInfo() != null) {
throw new IllegalArgumentException(
"Userinfo must not be present on authority: " + authority);
}
return uri;
}
@ -333,7 +330,10 @@ public final class GrpcUtil {
* @return the {@code authority} provided
*/
public static String checkAuthority(String authority) {
authorityToUri(authority);
URI uri = authorityToUri(authority);
checkArgument(uri.getHost() != null, "No host in authority '%s'", authority);
checkArgument(uri.getUserInfo() == null,
"Userinfo must not be present on authority: '%s'", authority);
return authority;
}

View File

@ -40,13 +40,18 @@ import static org.junit.Assert.assertTrue;
import io.grpc.Status;
import io.grpc.internal.GrpcUtil.Http2Error;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link GrpcUtil}. */
@RunWith(JUnit4.class)
public class GrpcUtilTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test
public void http2ErrorForCode() {
// Try edge cases manually, to make the test obviously correct for important cases.
@ -117,4 +122,56 @@ public class GrpcUtilTest {
public void contentTypeShouldNotBeValid() {
assertFalse(GrpcUtil.isGrpcContentType("application/bad"));
}
@Test
public void checkAuthority_failsOnNull() {
thrown.expect(NullPointerException.class);
GrpcUtil.checkAuthority(null);
}
@Test
public void checkAuthority_succeedsOnHostAndPort() {
String actual = GrpcUtil.checkAuthority("valid:1234");
assertEquals("valid:1234", actual);
}
@Test
public void checkAuthority_succeedsOnHost() {
String actual = GrpcUtil.checkAuthority("valid");
assertEquals("valid", actual);
}
@Test
public void checkAuthority_succeedsOnIpV6() {
String actual = GrpcUtil.checkAuthority("[::1]");
assertEquals("[::1]", actual);
}
@Test
public void checkAuthority_failsOnInvalidAuthority() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Invalid authority");
GrpcUtil.checkAuthority("[ : : 1]");
}
@Test
public void checkAuthority_failsOnInvalidHost() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("No host in authority");
GrpcUtil.checkAuthority("bad_host");
}
@Test
public void checkAuthority_userInfoNotAllowed() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Userinfo");
GrpcUtil.checkAuthority("foo@valid");
}
}