|
| 1 | +package uk.ac.cam.cl.dtg.segue.auth; |
| 2 | + |
| 3 | +import com.auth0.jwt.JWT; |
| 4 | +import com.auth0.jwt.JWTCreator; |
| 5 | +import com.auth0.jwt.algorithms.Algorithm; |
| 6 | +import com.auth0.jwt.exceptions.SignatureVerificationException; |
| 7 | +import com.google.common.cache.Cache; |
| 8 | +import com.google.common.cache.CacheBuilder; |
| 9 | +import jakarta.servlet.http.HttpServlet; |
| 10 | +import jakarta.servlet.http.HttpServletRequest; |
| 11 | +import jakarta.servlet.http.HttpServletResponse; |
| 12 | +import org.eclipse.jetty.server.Server; |
| 13 | +import org.eclipse.jetty.servlet.ServletHandler; |
| 14 | +import org.eclipse.jetty.servlet.ServletHolder; |
| 15 | +import org.json.JSONArray; |
| 16 | +import org.json.JSONObject; |
| 17 | +import org.junit.jupiter.api.Test; |
| 18 | +import uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider; |
| 19 | +import uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException; |
| 20 | + |
| 21 | +import java.io.IOException; |
| 22 | +import java.security.KeyPair; |
| 23 | +import java.security.KeyPairGenerator; |
| 24 | +import java.security.NoSuchAlgorithmException; |
| 25 | +import java.security.interfaces.RSAPrivateKey; |
| 26 | +import java.security.interfaces.RSAPublicKey; |
| 27 | +import java.util.Base64; |
| 28 | +import java.util.concurrent.TimeUnit; |
| 29 | +import java.util.function.Function; |
| 30 | + |
| 31 | +import static org.junit.jupiter.api.Assertions.*; |
| 32 | +import static uk.ac.cam.cl.dtg.segue.auth.Helpers.*; |
| 33 | + |
| 34 | +class MicrosoftAuthenticatorTest { |
| 35 | + @Test |
| 36 | + void getUserInfo_validToken_returnsUserInformation() throws Exception { |
| 37 | + String token = signedToken(validSigningKey, t -> t |
| 38 | + .withKeyId(validSigningKey.id()) |
| 39 | + . withPayload( "{\"email\": \"[email protected]\"}")); |
| 40 | + var userInfo = testGetUserInfo(token); |
| 41 | + assertEquals( "[email protected]", userInfo. getEmail()); |
| 42 | + } |
| 43 | + |
| 44 | + @Test |
| 45 | + void getUserInfo_tokenSignatureNoKeyId_throwsError() { |
| 46 | + String token = signedToken(validSigningKey, t -> t); |
| 47 | + var error = assertThrows(AuthenticatorSecurityException.class, () -> testGetUserInfo(token)); |
| 48 | + assertEquals("Token verification: NO_KEY_ID", error.getMessage()); |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + void getUserInfo_tokenSignatureKeyNotFound_throwsError() { |
| 53 | + String token = signedToken(validSigningKey, t -> t.withKeyId("no-such-key")); |
| 54 | + var error = assertThrows(AuthenticatorSecurityException.class, () -> testGetUserInfo(token)); |
| 55 | + assertEquals("No key found in http://localhost:8888/keys with kid no-such-key", error.getMessage()); |
| 56 | + } |
| 57 | + |
| 58 | + @Test |
| 59 | + void getUserInfo_tokenSignatureMismatch_throwsError() { |
| 60 | + String token = signedToken(invalidSigningKey, t -> t.withKeyId(validSigningKey.id())); |
| 61 | + var error = assertThrows(SignatureVerificationException.class, () -> testGetUserInfo(token)); |
| 62 | + assertEquals("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withRSA", error.getMessage()); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +class Helpers { |
| 67 | + public static UserFromAuthProvider testGetUserInfo(String token) throws Exception { |
| 68 | + var keyServer = TestKeyServer.withKey(validSigningKey).start(8888); |
| 69 | + Cache<String, String> store = CacheBuilder.newBuilder() |
| 70 | + .expireAfterAccess(10, TimeUnit.MINUTES) |
| 71 | + .build(); |
| 72 | + try { |
| 73 | + var subject = new MicrosoftAuthenticator( |
| 74 | + "", "", "", "http://localhost:8888/keys" |
| 75 | + ) {{ |
| 76 | + MicrosoftAuthenticator.credentialStore = store; |
| 77 | + }}; |
| 78 | + store.put("the_internal_id", token); |
| 79 | + return subject.getUserInfo("the_internal_id"); |
| 80 | + } finally { |
| 81 | + keyServer.stop(); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + public static String signedToken(TestKeyPair key, Function<JWTCreator.Builder, JWTCreator.Builder> fn) { |
| 86 | + var algorithm = Algorithm.RSA256(key.publicKey(), key.privateKey()); |
| 87 | + var token = fn.apply(JWT.create()); |
| 88 | + return token.sign(algorithm); |
| 89 | + } |
| 90 | + |
| 91 | + public static TestKeyPair validSigningKey = new TestKeyPair(); |
| 92 | + public static TestKeyPair invalidSigningKey = new TestKeyPair(); |
| 93 | +} |
| 94 | + |
| 95 | +class TestKeyServer { |
| 96 | + private Server server; |
| 97 | + private TestKeyPair key; |
| 98 | + |
| 99 | + private TestKeyServer(TestKeyPair key) { |
| 100 | + this.key = key; |
| 101 | + } |
| 102 | + |
| 103 | + public static TestKeyServer withKey(TestKeyPair key) { |
| 104 | + return new TestKeyServer(key); |
| 105 | + } |
| 106 | + |
| 107 | + public TestKeyServer start(int port) throws Exception { |
| 108 | + server = new Server(port); |
| 109 | + ServletHandler handler = new ServletHandler(); |
| 110 | + server.setHandler(handler); |
| 111 | + handler.addServletWithMapping(new ServletHolder(new HttpServlet() { |
| 112 | + @Override |
| 113 | + protected void doGet(HttpServletRequest req, HttpServletResponse resp) |
| 114 | + throws IOException { |
| 115 | + resp.setContentType("application/json"); |
| 116 | + resp.setStatus(HttpServletResponse.SC_OK); |
| 117 | + resp.getWriter().println(response()); |
| 118 | + } |
| 119 | + }), "/keys"); |
| 120 | + server.start(); |
| 121 | + return this; |
| 122 | + } |
| 123 | + |
| 124 | + public void stop() throws Exception { |
| 125 | + server.stop(); |
| 126 | + } |
| 127 | + |
| 128 | + private JSONObject response() { |
| 129 | + return new JSONObject().put( |
| 130 | + "keys", new JSONArray().put( |
| 131 | + new JSONObject() |
| 132 | + .put("kty", "RSA") |
| 133 | + .put("use", "sig") |
| 134 | + .put("kid", key.id()) |
| 135 | + .put("n", key.modulus()) |
| 136 | + .put("e", key.exponent()) |
| 137 | + .put("cloud_instance_name", "microsoftonline.com") |
| 138 | +// Microsoft's response also contains an X.509 certificate, which we don't test here. |
| 139 | +// For an example, response, see: https://login.microsoftonline.com/common/discovery/keys |
| 140 | +// .put("x5t", key_id) |
| 141 | +// .put("x5c", new JSONArray("some_string")) |
| 142 | + ) |
| 143 | + ); |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +class TestKeyPair { |
| 148 | + private KeyPair keyPair; |
| 149 | + |
| 150 | + public TestKeyPair() { |
| 151 | + try { |
| 152 | + keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); |
| 153 | + } catch (NoSuchAlgorithmException e) { |
| 154 | + throw new RuntimeException(e); |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + public String id() { |
| 159 | + return String.format("key_id_%s", keyPair.getPublic().hashCode()); |
| 160 | + } |
| 161 | + |
| 162 | + public String modulus() { |
| 163 | + return Base64.getUrlEncoder().withoutPadding().encodeToString(publicKey().getModulus().toByteArray()); |
| 164 | + } |
| 165 | + |
| 166 | + public String exponent() { |
| 167 | + return Base64.getUrlEncoder().withoutPadding().encodeToString(publicKey().getPublicExponent().toByteArray()); |
| 168 | + } |
| 169 | + |
| 170 | + public RSAPublicKey publicKey() { |
| 171 | + return (RSAPublicKey) keyPair.getPublic(); |
| 172 | + } |
| 173 | + |
| 174 | + public RSAPrivateKey privateKey() { |
| 175 | + return (RSAPrivateKey) keyPair.getPrivate(); |
| 176 | + } |
| 177 | +} |
0 commit comments