Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sanitise tags from invalid characters #7

Open
wants to merge 2 commits into
base: master
from
Open
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.

Always

Just for now

@@ -80,7 +80,7 @@ public void setTags(String... tags) {
if (!first) {
builder.append(",");
}
builder.append(t);
builder.append(sanitizeTag(t));
}
first = false;
}
@@ -212,4 +212,24 @@ private String joinStrings(Collection<String> messages) {
}
return b.toString();
}

/**
* Sanitize the tag based on the restrictions described in
* <a href="https://www.loggly.com/docs/tags/">https://www.loggly.com/docs/tags/</a>.
* Sanitation works by replacing invalid characters with the _ (underscore) character.
*
* @param tag tag to be sanitized
* @return the tag without invalid characters
*/
private String sanitizeTag(String tag) {
// replace invalid characters with _
String sanitized = tag.replaceAll("[^A-Za-z0-9_*,.\\-]", "_");

// don't allow non-alphanumeric values starting the tag
if (Character.isLetterOrDigit(tag.charAt(0))) {
return sanitized;
}

return sanitized.substring(1);
}
}
@@ -15,18 +15,19 @@
*/
package com.github.tony19.loggly;

import retrofit2.Call;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertThat;
import retrofit2.Call;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
@@ -138,4 +139,18 @@ public void emptyTagsResultInNoTags() {
loggly.logBulk("event");
Mockito.verify(restApi).logBulk(TOKEN, NO_TAGS, "event\n");
}

@Test
public void invalidTagsResultInNoTags() {
loggly.setTags("", " ", " ,", ", , ,, ");
loggly.logBulk("event");
Mockito.verify(restApi).logBulk(TOKEN, NO_TAGS, "event\n");
}

@Test
public void invalidTagsAreSentToLogglySanitized() {
loggly.setTags("_startInvalid", "middle@invalid.com", "%how_many$*3");
loggly.logBulk("event");
Mockito.verify(restApi).logBulk(TOKEN, "startInvalid,middle_invalid.com,how_many_*3", "event\n");
}
}
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.