Skip to content

Commit ab103a7

Browse files
fix(spec): refuse an autocomplete query over 64 characters
1 parent 4e7d72a commit ab103a7

5 files changed

Lines changed: 38 additions & 3 deletions

File tree

‎java/api/src/main/java/io/github/adeniyikayodee/ngpostcode/api/Api.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ public final class Api {
2525

2626
public static final String BASE_URL = "https://api.postcode.gov.ng";
2727

28+
/** Characters of autocomplete text sent. A full code with its separators is 15. */
29+
private static final int MAX_PARTIAL = 64;
30+
2831
// Responses are read as a tree and checked by hand: data binding would turn a missing
2932
// boolean into false, and a renamed field into "not assigned".
3033
/** Levels of nesting a body may have: what serde_json, behind the Rust crate, reads. */
@@ -57,13 +60,17 @@ public static Request<Lookup> lookup(Postcode code) {
5760
/**
5861
* Suggests completions for a partial postcode such as {@code EK 01 A}.
5962
*
60-
* @throws IllegalArgumentException for a blank {@code partial}: the live API never answers one
63+
* @throws IllegalArgumentException for a blank {@code partial}, which the live API never answers,
64+
* or one over 64 characters
6165
*/
6266
public static Request<Autocomplete> autocomplete(String partial) {
6367
// Unicode White_Space, as the other implementations trim: isBlank() keeps a no-break space.
6468
if (partial.chars().allMatch(c -> Character.isSpaceChar(c) || (c >= '\t' && c <= '\r') || c == 0x85)) {
6569
throw new IllegalArgumentException("partial must not be empty");
6670
}
71+
if (partial.codePointCount(0, partial.length()) > MAX_PARTIAL) {
72+
throw new IllegalArgumentException("partial is over " + MAX_PARTIAL + " characters");
73+
}
6774
return new Request<>("/v1/search/autocomplete", List.of(Map.entry("q", partial)), Api::readAutocomplete);
6875
}
6976

‎js/packages/ng-postcode-js/src/api.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import { Postcode, SEGMENTS, type Segment, trimWhiteSpace } from "./postcode.js"
1010

1111
export const BASE_URL = "https://api.postcode.gov.ng";
1212

13+
/** Characters of autocomplete text sent. A full code with its separators is 15. */
14+
const MAX_PARTIAL = 64;
15+
1316
/** A GET request whose successful response decodes to `T`. */
1417
export interface Request<T> {
1518
readonly path: string;
@@ -137,11 +140,16 @@ export function lookup(code: Postcode, level = 1): Request<Lookup> {
137140
/**
138141
* Suggest completions for a partial postcode such as `EK 01 A`.
139142
*
140-
* Throws `RangeError` for an empty `partial`: the live API never answers one.
143+
* Throws `RangeError` for an empty `partial`, which the live API never answers, or one
144+
* over 64 characters.
141145
*/
142146
export function autocomplete(partial: string): Request<Autocomplete> {
143147
if (typeof partial !== "string") throw new TypeError("partial must be text");
144148
if (!trimWhiteSpace(partial)) throw new RangeError("partial must not be empty");
149+
// Spread counts characters, where `length` counts an emoji as two.
150+
if ([...partial].length > MAX_PARTIAL) {
151+
throw new RangeError(`partial is over ${MAX_PARTIAL} characters`);
152+
}
145153
return { path: "/v1/search/autocomplete", params: [["q", partial]], read: readAutocomplete };
146154
}
147155

‎python/src/ng_postcode/api.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121

2222
BASE_URL = "https://api.postcode.gov.ng"
2323

24+
_MAX_PARTIAL = 64
25+
"""Characters of autocomplete text sent. A full code with its separators is 15."""
26+
2427
_MAX_DEPTH = 127
2528
"""Levels of nesting a body may have: what serde_json, behind the Rust crate, reads."""
2629

@@ -161,12 +164,15 @@ def lookup(code: Postcode, level: int = 1) -> Request[Lookup]:
161164
def autocomplete(partial: str) -> Request[Autocomplete]:
162165
"""Suggest completions for a partial postcode such as `EK 01 A`.
163166
164-
Raises `ValueError` for an empty `partial`: the live API never answers one.
167+
Raises `ValueError` for an empty `partial`, which the live API never answers, or one
168+
over 64 characters.
165169
"""
166170
if not isinstance(partial, str):
167171
raise TypeError(f"partial must be text, got {partial!r}")
168172
if not partial.strip(WHITE_SPACE):
169173
raise ValueError("partial must not be empty")
174+
if len(partial) > _MAX_PARTIAL:
175+
raise ValueError(f"partial is over {_MAX_PARTIAL} characters")
170176
return Request("/v1/search/autocomplete", (("q", partial),), _autocomplete)
171177

172178

‎spec/requests.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
{ "name": "autocomplete_next_line", "request": "autocomplete", "args": {"q": "\u0085"}, "sends": null },
1111
{ "name": "autocomplete_control_character", "request": "autocomplete", "args": {"q": "\u001c"}, "sends": {"path": "/v1/search/autocomplete", "query": [["q", "\u001c"]]} },
1212
{ "name": "autocomplete_blank", "request": "autocomplete", "args": {"q": " "}, "sends": null },
13+
{ "name": "autocomplete_at_the_length_limit", "request": "autocomplete", "args": {"q": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, "sends": {"path": "/v1/search/autocomplete", "query": [["q", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]]} },
14+
{ "name": "autocomplete_limit_counts_characters", "request": "autocomplete", "args": {"q": "\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00"}, "sends": {"path": "/v1/search/autocomplete", "query": [["q", "\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00"]]} },
15+
{ "name": "autocomplete_too_long", "request": "autocomplete", "args": {"q": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, "sends": null },
1316
{ "name": "reverse", "request": "reverse", "args": {"lat": 7.6211, "lng": 5.2214}, "sends": {"path": "/v1/search/reverse", "query": [["lat", "7.6211"], ["lng", "5.2214"]]} },
1417
{ "name": "reverse_within", "request": "reverse", "args": {"lat": 7.6211, "lng": 5.2214, "metres": 100}, "sends": {"path": "/v1/search/reverse", "query": [["lat", "7.6211"], ["lng", "5.2214"], ["max_distance_m", "100"]]} },
1518
{ "name": "nearby_within", "request": "nearby", "args": {"lat": 7.6211, "lng": 5.2214, "metres": 62.5}, "sends": {"path": "/v1/search/nearby", "query": [["lat", "7.6211"], ["lng", "5.2214"], ["radius", "62.5"]]} },

‎src/api.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ use crate::{Postcode, Segment};
1212

1313
pub const BASE_URL: &str = "https://api.postcode.gov.ng";
1414

15+
/// Characters of autocomplete text sent. A full code with its separators is 15.
16+
const MAX_PARTIAL: usize = 64;
17+
1518
/// A GET request whose successful response decodes to `T`.
1619
#[derive(Clone, Debug)]
1720
pub struct Request<T> {
@@ -41,6 +44,8 @@ pub enum InvalidRequest {
4144
Level(u8),
4245
/// The autocomplete text is empty, which the live API never answers.
4346
EmptyQuery,
47+
/// The autocomplete text is over 64 characters.
48+
QueryTooLong,
4449
/// The named coordinate or distance is not a finite number.
4550
NotFinite(&'static str),
4651
/// The named coordinate is off the globe: latitude beyond 90, or longitude beyond 180.
@@ -64,6 +69,9 @@ pub fn autocomplete(partial: &str) -> Result<Request<Autocomplete>, InvalidReque
6469
if partial.trim().is_empty() {
6570
return Err(InvalidRequest::EmptyQuery);
6671
}
72+
if partial.chars().count() > MAX_PARTIAL {
73+
return Err(InvalidRequest::QueryTooLong);
74+
}
6775
let query = [("q", partial.to_owned())];
6876
Ok(Request::get(
6977
"/v1/search/autocomplete",
@@ -341,6 +349,9 @@ impl fmt::Display for InvalidRequest {
341349
match self {
342350
Self::Level(level) => write!(f, "level must be 1 to 5, got {level}"),
343351
Self::EmptyQuery => f.write_str("autocomplete text must not be empty"),
352+
Self::QueryTooLong => {
353+
write!(f, "autocomplete text is over {MAX_PARTIAL} characters")
354+
}
344355
Self::NotFinite(name) => write!(f, "{name} must be a finite number"),
345356
Self::OutOfRange(name) => write!(f, "{name} is off the globe"),
346357
Self::Negative(name) => write!(f, "{name} must not be negative"),

0 commit comments

Comments
 (0)