Skip to content

Commit 086492d

Browse files
ellebrechtbbakerman
authored andcommitted
Use unpadded url/filename-safe Base64 encoding for Relay global IDs.
1 parent 11c99ab commit 086492d

2 files changed

Lines changed: 37 additions & 2 deletions

File tree

src/main/java/graphql/relay/Relay.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ public String getId() {
237237
}
238238
}
239239

240-
private static final java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
241-
private static final java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
240+
private static final java.util.Base64.Encoder encoder = java.util.Base64.getUrlEncoder().withoutPadding();
241+
private static final java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
242242

243243
public String toGlobalId(String type, String id) {
244244
return encoder.encodeToString((type + ":" + id).getBytes(StandardCharsets.UTF_8));
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package graphql.relay
2+
3+
import spock.lang.Specification
4+
5+
import java.nio.charset.StandardCharsets
6+
7+
class RelayTest extends Specification {
8+
9+
def urlSafe(String s) {
10+
return s == URLEncoder.encode(s, StandardCharsets.UTF_8.name())
11+
}
12+
13+
def "global id encoding is consistent and url-safe"() {
14+
given:
15+
def relay = new Relay()
16+
def type = "Type"
17+
18+
expect:
19+
def globalId = relay.toGlobalId(type, id)
20+
def idResolved = relay.fromGlobalId(globalId)
21+
type == idResolved.type && id == idResolved.id && urlSafe(globalId)
22+
23+
where:
24+
id || base64UrlSafeReference
25+
'null' || 'VHlwZTpudWxs'
26+
'' || 'VHlwZTo'
27+
'1' || 'VHlwZTox'
28+
'99' || 'VHlwZTo5OQ'
29+
'abc' || 'VHlwZTphYmM'
30+
'.,-:;_=?()/&%$§!' || 'VHlwZTouLC06O189PygpLyYlJMKnIQ'
31+
'~abc' || 'VHlwZTp-YWJj'
32+
'?_graphql' || 'VHlwZTo_X2dyYXBocWw'
33+
}
34+
35+
}

0 commit comments

Comments
 (0)