Use MailboxId instead of String for type-safety

This commit is contained in:
Torsten Grote
2022-01-24 13:50:58 -03:00
parent 61ea7ff8de
commit f057f0859b
10 changed files with 125 additions and 65 deletions

View File

@@ -9,6 +9,7 @@ apply from: 'witness.gradle'
dependencies {
implementation "com.google.dagger:dagger:$dagger_version"
implementation 'com.google.code.findbugs:jsr305:3.0.2'
implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
testImplementation "junit:junit:$junit_version"
testImplementation "org.jmock:jmock:$jmock_version"

View File

@@ -0,0 +1,47 @@
package org.briarproject.bramble.api.mailbox;
import com.fasterxml.jackson.annotation.JsonValue;
import org.briarproject.bramble.api.UniqueId;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.util.Locale;
import javax.annotation.concurrent.ThreadSafe;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
@ThreadSafe
@NotNullByDefault
public class MailboxId extends UniqueId {
public MailboxId(byte[] id) {
super(id);
}
/**
* Creates a {@link MailboxId} from the given string.
*
* @throws IllegalArgumentException if token is not valid.
*/
public static MailboxId fromString(String token) {
if (token.length() != 64) throw new IllegalArgumentException();
return new MailboxId(fromHexString(token));
}
/**
* Returns the string representation expected by the mailbox API.
* Also used for serialization.
*/
@Override
@JsonValue
public String toString() {
return toHexString(getBytes()).toLowerCase(Locale.US);
}
@Override
public boolean equals(Object o) {
return o instanceof MailboxId && super.equals(o);
}
}

View File

@@ -8,10 +8,11 @@ import javax.annotation.concurrent.Immutable;
@NotNullByDefault
public class MailboxProperties {
private final String onionAddress, authToken;
private final String onionAddress;
private final MailboxId authToken;
private final boolean owner;
public MailboxProperties(String onionAddress, String authToken,
public MailboxProperties(String onionAddress, MailboxId authToken,
boolean owner) {
this.onionAddress = onionAddress;
this.authToken = authToken;
@@ -22,7 +23,7 @@ public class MailboxProperties {
return onionAddress;
}
public String getAuthToken() {
public MailboxId getAuthToken() {
return authToken;
}

View File

@@ -16,6 +16,7 @@ import org.briarproject.bramble.api.identity.Author;
import org.briarproject.bramble.api.identity.AuthorId;
import org.briarproject.bramble.api.identity.Identity;
import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.plugin.TransportId;
import org.briarproject.bramble.api.properties.TransportProperties;
import org.briarproject.bramble.api.sync.ClientId;
@@ -35,7 +36,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
@@ -52,7 +52,6 @@ import static org.briarproject.bramble.api.sync.SyncConstants.MAX_GROUP_DESCRIPT
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_BODY_LENGTH;
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
public class TestUtils {
@@ -216,8 +215,8 @@ public class TestUtils {
getAgreementPublicKey(), verified);
}
public static String getMailboxSecret() {
return toHexString(getRandomBytes(32)).toLowerCase(Locale.US);
public static MailboxId getMailboxId() {
return new MailboxId(getRandomId());
}
public static void writeBytes(File file, byte[] bytes)

View File

@@ -3,6 +3,7 @@ package org.briarproject.bramble.mailbox;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.mailbox.MailboxProperties;
import java.io.File;
@@ -21,7 +22,7 @@ interface MailboxApi {
* @return the owner token
* @throws ApiException for 401 response.
*/
String setup(MailboxProperties properties)
MailboxId setup(MailboxProperties properties)
throws IOException, ApiException;
/**
@@ -66,7 +67,7 @@ interface MailboxApi {
* The owner can add files to the contacts' inboxes
* and the contacts can add files to their own outbox.
*/
void addFile(MailboxProperties properties, String folderId,
void addFile(MailboxProperties properties, MailboxId folderId,
File file) throws IOException, ApiException;
/**
@@ -74,7 +75,7 @@ interface MailboxApi {
* <p>
* Returns 200 OK with the list of files in JSON.
*/
List<MailboxFile> getFiles(MailboxProperties properties, String folderId)
List<MailboxFile> getFiles(MailboxProperties properties, MailboxId folderId)
throws IOException, ApiException;
/**
@@ -85,8 +86,8 @@ interface MailboxApi {
*
* @param file the empty file the response bytes will be written into.
*/
void getFile(MailboxProperties properties, String folderId,
String fileId, File file) throws IOException, ApiException;
void getFile(MailboxProperties properties, MailboxId folderId,
MailboxId fileId, File file) throws IOException, ApiException;
/**
* Used by owner and contacts to delete files.
@@ -96,8 +97,8 @@ interface MailboxApi {
* @throws TolerableFailureException on 404 response,
* because file was most likely deleted already.
*/
void deleteFile(MailboxProperties properties, String folderId,
String fileId)
void deleteFile(MailboxProperties properties, MailboxId folderId,
MailboxId fileId)
throws IOException, ApiException, TolerableFailureException;
/**
@@ -105,22 +106,22 @@ interface MailboxApi {
* for the owner to download.
*
* @return a list of folder names
* to be used with {@link #getFiles(MailboxProperties, String)}.
* to be used with {@link #getFiles(MailboxProperties, MailboxId)}.
* @throws IllegalArgumentException if used by non-owner.
*/
List<String> getFolders(MailboxProperties properties)
List<MailboxId> getFolders(MailboxProperties properties)
throws IOException, ApiException;
@Immutable
@JsonSerialize
class MailboxContact {
public final int contactId;
public final String token, inboxId, outboxId;
public final MailboxId token, inboxId, outboxId;
MailboxContact(ContactId contactId,
String token,
String inboxId,
String outboxId) {
MailboxId token,
MailboxId inboxId,
MailboxId outboxId) {
this.contactId = contactId.getInt();
this.token = token;
this.inboxId = inboxId;
@@ -128,11 +129,12 @@ interface MailboxApi {
}
}
@JsonSerialize
class MailboxFile {
public final String name;
public final MailboxId name;
public final long time;
public MailboxFile(String name, long time) {
public MailboxFile(MailboxId name, long time) {
this.name = name;
this.time = time;
}

View File

@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import org.briarproject.bramble.api.WeakSingletonProvider;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.mailbox.MailboxProperties;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
@@ -50,7 +51,7 @@ class MailboxApiImpl implements MailboxApi {
}
@Override
public String setup(MailboxProperties properties)
public MailboxId setup(MailboxProperties properties)
throws IOException, ApiException {
if (!properties.isOwner()) throw new IllegalArgumentException();
Request request = getRequestBuilder(properties.getAuthToken())
@@ -74,12 +75,14 @@ class MailboxApiImpl implements MailboxApi {
if (ownerToken == null || !isValidToken(ownerToken)) {
throw new ApiException();
}
return ownerToken;
return MailboxId.fromString(ownerToken);
} catch (JacksonException e) {
throw new ApiException();
}
}
// TODO find a batter way to validate (regex?)
// that doesn't do hex string conversion twice
private boolean isValidToken(String token) {
if (token.length() != 64) return false;
try {
@@ -161,7 +164,7 @@ class MailboxApiImpl implements MailboxApi {
/* File Management (owner and contacts) */
@Override
public void addFile(MailboxProperties properties, String folderId,
public void addFile(MailboxProperties properties, MailboxId folderId,
File file) throws IOException, ApiException {
String path = "/files/" + folderId;
RequestBody body = RequestBody.create(FILE, file);
@@ -171,7 +174,7 @@ class MailboxApiImpl implements MailboxApi {
@Override
public List<MailboxFile> getFiles(MailboxProperties properties,
String folderId) throws IOException, ApiException {
MailboxId folderId) throws IOException, ApiException {
String path = "/files/" + folderId;
Response response = sendGetRequest(properties, path);
if (response.code() != 200) throw new ApiException();
@@ -200,7 +203,7 @@ class MailboxApiImpl implements MailboxApi {
long time = timeNode.asLong();
if (!isValidToken(name)) throw new ApiException();
if (time < 1) throw new ApiException();
list.add(new MailboxFile(name, time));
list.add(new MailboxFile(MailboxId.fromString(name), time));
}
return list;
} catch (JacksonException e) {
@@ -209,8 +212,8 @@ class MailboxApiImpl implements MailboxApi {
}
@Override
public void getFile(MailboxProperties properties, String folderId,
String fileId, File file) throws IOException, ApiException {
public void getFile(MailboxProperties properties, MailboxId folderId,
MailboxId fileId, File file) throws IOException, ApiException {
String path = "/files/" + folderId + "/" + fileId;
Response response = sendGetRequest(properties, path);
if (response.code() != 200) throw new ApiException();
@@ -222,8 +225,8 @@ class MailboxApiImpl implements MailboxApi {
}
@Override
public void deleteFile(MailboxProperties properties, String folderId,
String fileId)
public void deleteFile(MailboxProperties properties, MailboxId folderId,
MailboxId fileId)
throws IOException, ApiException, TolerableFailureException {
String path = "/files/" + folderId + "/" + fileId;
Request request = getRequestBuilder(properties.getAuthToken())
@@ -237,7 +240,7 @@ class MailboxApiImpl implements MailboxApi {
}
@Override
public List<String> getFolders(MailboxProperties properties)
public List<MailboxId> getFolders(MailboxProperties properties)
throws IOException, ApiException {
if (!properties.isOwner()) throw new IllegalArgumentException();
Response response = sendGetRequest(properties, "/folders");
@@ -251,7 +254,7 @@ class MailboxApiImpl implements MailboxApi {
if (filesNode == null || !filesNode.isArray()) {
throw new ApiException();
}
List<String> list = new ArrayList<>();
List<MailboxId> list = new ArrayList<>();
for (JsonNode fileNode : filesNode) {
if (!fileNode.isObject()) throw new ApiException();
ObjectNode objectNode = (ObjectNode) fileNode;
@@ -261,7 +264,7 @@ class MailboxApiImpl implements MailboxApi {
}
String id = idNode.asText();
if (!isValidToken(id)) throw new ApiException();
list.add(id);
list.add(MailboxId.fromString(id));
}
return list;
} catch (JacksonException e) {
@@ -290,7 +293,7 @@ class MailboxApiImpl implements MailboxApi {
return client.newCall(request).execute();
}
private Request.Builder getRequestBuilder(String token) {
private Request.Builder getRequestBuilder(MailboxId token) {
return new Request.Builder()
.addHeader("Authorization", "Bearer " + token);
}

View File

@@ -3,6 +3,7 @@ package org.briarproject.bramble.mailbox;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.mailbox.MailboxProperties;
import org.briarproject.bramble.api.mailbox.MailboxSettingsManager;
import org.briarproject.bramble.api.mailbox.MailboxStatus;
@@ -43,7 +44,8 @@ class MailboxSettingsManagerImpl implements MailboxSettingsManager {
String onion = s.get(SETTINGS_KEY_ONION);
String token = s.get(SETTINGS_KEY_TOKEN);
if (isNullOrEmpty(onion) || isNullOrEmpty(token)) return null;
return new MailboxProperties(onion, token, true);
MailboxId tokenId = MailboxId.fromString(token);
return new MailboxProperties(onion, tokenId, true);
}
@Override
@@ -51,7 +53,7 @@ class MailboxSettingsManagerImpl implements MailboxSettingsManager {
throws DbException {
Settings s = new Settings();
s.put(SETTINGS_KEY_ONION, p.getOnionAddress());
s.put(SETTINGS_KEY_TOKEN, p.getAuthToken());
s.put(SETTINGS_KEY_TOKEN, p.getAuthToken().toString());
settingsManager.mergeSettings(txn, s, SETTINGS_NAMESPACE);
}

View File

@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.briarproject.bramble.api.WeakSingletonProvider;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.mailbox.MailboxProperties;
import org.briarproject.bramble.mailbox.MailboxApi.ApiException;
import org.briarproject.bramble.mailbox.MailboxApi.MailboxContact;
@@ -31,7 +32,7 @@ import okio.Buffer;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.briarproject.bramble.test.TestUtils.getContactId;
import static org.briarproject.bramble.test.TestUtils.getMailboxSecret;
import static org.briarproject.bramble.test.TestUtils.getMailboxId;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.readBytes;
import static org.briarproject.bramble.test.TestUtils.writeBytes;
@@ -62,12 +63,12 @@ public class MailboxApiTest extends BrambleTestCase {
};
private final MailboxApiImpl api = new MailboxApiImpl(httpClientProvider);
private final String token = getMailboxSecret();
private final String token2 = getMailboxSecret();
private final MailboxId token = getMailboxId();
private final MailboxId token2 = getMailboxId();
private final ContactId contactId = getContactId();
private final String contactToken = getMailboxSecret();
private final String contactInboxId = getMailboxSecret();
private final String contactOutboxId = getMailboxSecret();
private final MailboxId contactToken = getMailboxId();
private final MailboxId contactInboxId = getMailboxId();
private final MailboxId contactOutboxId = getMailboxId();
private final MailboxContact mailboxContact = new MailboxContact(
contactId, contactToken, contactInboxId, contactOutboxId);
@@ -427,9 +428,9 @@ public class MailboxApiTest extends BrambleTestCase {
@Test
public void testGetFiles() throws Exception {
MailboxFile mailboxFile1 = new MailboxFile(getMailboxSecret(), 1337);
MailboxFile mailboxFile1 = new MailboxFile(getMailboxId(), 1337);
MailboxFile mailboxFile2 =
new MailboxFile(getMailboxSecret(), System.currentTimeMillis());
new MailboxFile(getMailboxId(), System.currentTimeMillis());
String fileResponse1 =
new ObjectMapper().writeValueAsString(mailboxFile1);
String fileResponse2 =
@@ -538,7 +539,7 @@ public class MailboxApiTest extends BrambleTestCase {
@Test
public void testGetFile() throws Exception {
String name = getMailboxSecret();
MailboxId name = getMailboxId();
File file1 = folder.newFile();
File file2 = folder.newFile();
File file3 = folder.newFile();
@@ -585,7 +586,7 @@ public class MailboxApiTest extends BrambleTestCase {
@Test
public void testDeleteFile() throws Exception {
String name = getMailboxSecret();
MailboxId name = getMailboxId();
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
@@ -635,8 +636,8 @@ public class MailboxApiTest extends BrambleTestCase {
@Test
public void testGetFolders() throws Exception {
String id1 = getMailboxSecret();
String id2 = getMailboxSecret();
MailboxId id1 = getMailboxId();
MailboxId id2 = getMailboxId();
String validResponse1 = "{\"folders\": [ {\"id\": \"" + id1 + "\"} ] }";
String validResponse2 = "{\"folders\": [ {\"id\": \"" + id1 + "\"}, " +
"{ \"id\": \"" + id2 + "\"} ] }";
@@ -738,7 +739,7 @@ public class MailboxApiTest extends BrambleTestCase {
return baseUrl.substring(0, baseUrl.length() - 1);
}
private void assertToken(RecordedRequest request, String token) {
private void assertToken(RecordedRequest request, MailboxId token) {
assertNotNull(request.getHeader("Authorization"));
assertEquals("Bearer " + token, request.getHeader("Authorization"));
}

View File

@@ -2,6 +2,7 @@ package org.briarproject.bramble.mailbox;
import org.briarproject.bramble.api.WeakSingletonProvider;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.mailbox.MailboxProperties;
import org.briarproject.bramble.mailbox.MailboxApi.ApiException;
import org.briarproject.bramble.mailbox.MailboxApi.MailboxContact;
@@ -27,7 +28,7 @@ import okhttp3.OkHttpClient;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.briarproject.bramble.test.TestUtils.getMailboxSecret;
import static org.briarproject.bramble.test.TestUtils.getMailboxId;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.isOptionalTestEnabled;
import static org.briarproject.bramble.test.TestUtils.readBytes;
@@ -44,8 +45,8 @@ public class MailboxIntegrationTest extends BrambleTestCase {
public TemporaryFolder folder = new TemporaryFolder();
private final static String URL_BASE = "http://127.0.0.1:8000";
private final static String SETUP_TOKEN =
"54686973206973206120736574757020746f6b656e20666f722042726961722e";
private final static MailboxId SETUP_TOKEN = MailboxId.fromString(
"54686973206973206120736574757020746f6b656e20666f722042726961722e");
private final OkHttpClient client = new OkHttpClient.Builder()
.socketFactory(SocketFactory.getDefault())
@@ -76,7 +77,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
if (ownerProperties != null) return;
MailboxProperties setupProperties =
new MailboxProperties(URL_BASE, SETUP_TOKEN, true);
String ownerToken = api.setup(setupProperties);
MailboxId ownerToken = api.setup(setupProperties);
ownerProperties = new MailboxProperties(URL_BASE, ownerToken, true);
}
@@ -132,7 +133,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
List<MailboxFile> files1 =
api.getFiles(contactProperties, contact.inboxId);
assertEquals(1, files1.size());
String fileName1 = files1.get(0).name;
MailboxId fileName1 = files1.get(0).name;
// owner can't check files
assertThrows(ApiException.class, () ->
@@ -170,15 +171,15 @@ public class MailboxIntegrationTest extends BrambleTestCase {
api.addFile(contactProperties, contact.outboxId, file3);
// owner checks folders with available files
List<String> folders = api.getFolders(ownerProperties);
List<MailboxId> folders = api.getFolders(ownerProperties);
assertEquals(singletonList(contact.outboxId), folders);
// owner lists files in contact's outbox
List<MailboxFile> files2 =
api.getFiles(ownerProperties, contact.outboxId);
assertEquals(2, files2.size());
String file2name = files2.get(0).name;
String file3name = files2.get(1).name;
MailboxId file2name = files2.get(0).name;
MailboxId file3name = files2.get(1).name;
// contact can't list files in contact's outbox
assertThrows(ApiException.class, () ->
@@ -235,8 +236,8 @@ public class MailboxIntegrationTest extends BrambleTestCase {
}
private MailboxContact getMailboxContact(ContactId contactId) {
return new MailboxContact(contactId, getMailboxSecret(),
getMailboxSecret(), getMailboxSecret());
return new MailboxContact(contactId, getMailboxId(), getMailboxId(),
getMailboxId());
}
}

View File

@@ -2,6 +2,7 @@ package org.briarproject.bramble.mailbox;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.mailbox.MailboxId;
import org.briarproject.bramble.api.mailbox.MailboxProperties;
import org.briarproject.bramble.api.mailbox.MailboxSettingsManager;
import org.briarproject.bramble.api.mailbox.MailboxStatus;
@@ -20,6 +21,7 @@ import static org.briarproject.bramble.mailbox.MailboxSettingsManagerImpl.SETTIN
import static org.briarproject.bramble.mailbox.MailboxSettingsManagerImpl.SETTINGS_KEY_TOKEN;
import static org.briarproject.bramble.mailbox.MailboxSettingsManagerImpl.SETTINGS_NAMESPACE;
import static org.briarproject.bramble.mailbox.MailboxSettingsManagerImpl.SETTINGS_UPLOADS_NAMESPACE;
import static org.briarproject.bramble.test.TestUtils.getMailboxId;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -35,7 +37,7 @@ public class MailboxSettingsManagerImplTest extends BrambleMockTestCase {
new MailboxSettingsManagerImpl(settingsManager);
private final Random random = new Random();
private final String onion = getRandomString(64);
private final String token = getRandomString(64);
private final MailboxId token = getMailboxId();
private final ContactId contactId1 = new ContactId(random.nextInt());
private final ContactId contactId2 = new ContactId(random.nextInt());
private final ContactId contactId3 = new ContactId(random.nextInt());
@@ -62,7 +64,7 @@ public class MailboxSettingsManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, true);
Settings settings = new Settings();
settings.put(SETTINGS_KEY_ONION, onion);
settings.put(SETTINGS_KEY_TOKEN, token);
settings.put(SETTINGS_KEY_TOKEN, token.toString());
context.checking(new Expectations() {{
oneOf(settingsManager).getSettings(txn, SETTINGS_NAMESPACE);
@@ -81,7 +83,7 @@ public class MailboxSettingsManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, false);
Settings expectedSettings = new Settings();
expectedSettings.put(SETTINGS_KEY_ONION, onion);
expectedSettings.put(SETTINGS_KEY_TOKEN, token);
expectedSettings.put(SETTINGS_KEY_TOKEN, token.toString());
MailboxProperties properties =
new MailboxProperties(onion, token, true);
@@ -180,7 +182,7 @@ public class MailboxSettingsManagerImplTest extends BrambleMockTestCase {
Transaction txn = new Transaction(null, true);
Settings settings = new Settings();
settings.put(String.valueOf(contactId1.getInt()), onion);
settings.put(String.valueOf(contactId2.getInt()), token);
settings.put(String.valueOf(contactId2.getInt()), token.toString());
settings.put(String.valueOf(contactId3.getInt()), "");
context.checking(new Expectations() {{
@@ -192,7 +194,8 @@ public class MailboxSettingsManagerImplTest extends BrambleMockTestCase {
String filename1 = manager.getPendingUpload(txn, contactId1);
assertEquals(onion, filename1);
String filename2 = manager.getPendingUpload(txn, contactId2);
assertEquals(token, filename2);
assertNotNull(filename2);
assertEquals(token, MailboxId.fromString(filename2));
String filename3 = manager.getPendingUpload(txn, contactId3);
assertNull(filename3);
String filename4 =