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

sanitize tags from invalid characters #1

Merged
merged 1 commit into from
Oct 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public void setTags(String... tags) {
if (!first) {
builder.append(",");
}
builder.append(t);
builder.append(sanitizeTag(t));
}
first = false;
}
Expand Down Expand Up @@ -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 _
tag = tag.replaceAll("[^A-Za-z0-9_*,.\\-]", "_");

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

return tag.substring(1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
}
}