]> git.openstreetmap.org Git - rails.git/blob - test/controllers/api/ways_controller_test.rb
Merge remote-tracking branch 'upstream/pull/6154'
[rails.git] / test / controllers / api / ways_controller_test.rb
1 require "test_helper"
2
3 module Api
4   class WaysControllerTest < ActionDispatch::IntegrationTest
5     ##
6     # test all routes which lead to this controller
7     def test_routes
8       assert_routing(
9         { :path => "/api/0.6/ways", :method => :get },
10         { :controller => "api/ways", :action => "index" }
11       )
12       assert_routing(
13         { :path => "/api/0.6/ways.json", :method => :get },
14         { :controller => "api/ways", :action => "index", :format => "json" }
15       )
16       assert_routing(
17         { :path => "/api/0.6/ways", :method => :post },
18         { :controller => "api/ways", :action => "create" }
19       )
20       assert_routing(
21         { :path => "/api/0.6/way/1", :method => :get },
22         { :controller => "api/ways", :action => "show", :id => "1" }
23       )
24       assert_routing(
25         { :path => "/api/0.6/way/1.json", :method => :get },
26         { :controller => "api/ways", :action => "show", :id => "1", :format => "json" }
27       )
28       assert_routing(
29         { :path => "/api/0.6/way/1/full", :method => :get },
30         { :controller => "api/ways", :action => "show", :full => true, :id => "1" }
31       )
32       assert_routing(
33         { :path => "/api/0.6/way/1/full.json", :method => :get },
34         { :controller => "api/ways", :action => "show", :full => true, :id => "1", :format => "json" }
35       )
36       assert_routing(
37         { :path => "/api/0.6/way/1", :method => :put },
38         { :controller => "api/ways", :action => "update", :id => "1" }
39       )
40       assert_routing(
41         { :path => "/api/0.6/way/1", :method => :delete },
42         { :controller => "api/ways", :action => "destroy", :id => "1" }
43       )
44
45       assert_recognizes(
46         { :controller => "api/ways", :action => "create" },
47         { :path => "/api/0.6/way/create", :method => :put }
48       )
49     end
50
51     ##
52     # test fetching multiple ways
53     def test_index
54       way1 = create(:way)
55       way2 = create(:way, :deleted)
56       way3 = create(:way)
57       way4 = create(:way)
58
59       # check error when no parameter provided
60       get api_ways_path
61       assert_response :bad_request
62
63       # check error when no parameter value provided
64       get api_ways_path(:ways => "")
65       assert_response :bad_request
66
67       # test a working call
68       get api_ways_path(:ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id}")
69       assert_response :success
70       assert_select "osm" do
71         assert_select "way", :count => 4
72         assert_select "way[id='#{way1.id}'][visible='true']", :count => 1
73         assert_select "way[id='#{way2.id}'][visible='false']", :count => 1
74         assert_select "way[id='#{way3.id}'][visible='true']", :count => 1
75         assert_select "way[id='#{way4.id}'][visible='true']", :count => 1
76       end
77
78       # test a working call with json format
79       get api_ways_path(:ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id}", :format => "json")
80
81       js = ActiveSupport::JSON.decode(@response.body)
82       assert_not_nil js
83       assert_equal 4, js["elements"].count
84       assert_equal 4, (js["elements"].count { |a| a["type"] == "way" })
85       assert_equal 1, (js["elements"].count { |a| a["id"] == way1.id && a["visible"].nil? })
86       assert_equal 1, (js["elements"].count { |a| a["id"] == way2.id && a["visible"] == false })
87       assert_equal 1, (js["elements"].count { |a| a["id"] == way3.id && a["visible"].nil? })
88       assert_equal 1, (js["elements"].count { |a| a["id"] == way4.id && a["visible"].nil? })
89
90       # check error when a non-existent way is included
91       get api_ways_path(:ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id},0")
92       assert_response :not_found
93     end
94
95     # -------------------------------------
96     # Test showing ways.
97     # -------------------------------------
98
99     def test_show_not_found
100       get api_way_path(0)
101       assert_response :not_found
102     end
103
104     def test_show_deleted
105       get api_way_path(create(:way, :deleted))
106       assert_response :gone
107     end
108
109     def test_show
110       way = create(:way, :timestamp => "2021-02-03T00:00:00Z")
111       node = create(:node, :timestamp => "2021-04-05T00:00:00Z")
112       create(:way_node, :way => way, :node => node)
113
114       get api_way_path(way)
115
116       assert_response :success
117       assert_not_nil @response.header["Last-Modified"]
118       assert_equal "2021-02-03T00:00:00Z", Time.parse(@response.header["Last-Modified"]).utc.xmlschema
119     end
120
121     def test_show_json
122       way = create(:way_with_nodes, :nodes_count => 3)
123
124       get api_way_path(way, :format => "json")
125
126       assert_response :success
127
128       js = ActiveSupport::JSON.decode(@response.body)
129       assert_not_nil js
130       assert_equal 1, js["elements"].count
131       js_ways = js["elements"].filter { |e| e["type"] == "way" }
132       assert_equal 1, js_ways.count
133       assert_equal way.id, js_ways[0]["id"]
134       assert_equal 1, js_ways[0]["version"]
135     end
136
137     ##
138     # check the "full" mode
139     def test_show_full
140       way = create(:way_with_nodes, :nodes_count => 3)
141
142       get api_way_path(way, :full => true)
143
144       assert_response :success
145
146       # Check the way is correctly returned
147       assert_select "osm way[id='#{way.id}'][version='1'][visible='true']", 1
148
149       # check that each node in the way appears once in the output as a
150       # reference and as the node element.
151       way.nodes.each do |n|
152         assert_select "osm way nd[ref='#{n.id}']", 1
153         assert_select "osm node[id='#{n.id}'][version='1'][lat='#{format('%<lat>.7f', :lat => n.lat)}'][lon='#{format('%<lon>.7f', :lon => n.lon)}']", 1
154       end
155     end
156
157     def test_show_full_json
158       way = create(:way_with_nodes, :nodes_count => 3)
159
160       get api_way_path(way, :full => true, :format => "json")
161
162       assert_response :success
163
164       # Check the way is correctly returned
165       js = ActiveSupport::JSON.decode(@response.body)
166       assert_not_nil js
167       assert_equal 4, js["elements"].count
168       js_ways = js["elements"].filter { |e| e["type"] == "way" }
169       assert_equal 1, js_ways.count
170       assert_equal way.id, js_ways[0]["id"]
171       assert_equal 1, js_ways[0]["version"]
172
173       # check that each node in the way appears once in the output as a
174       # reference and as the node element.
175       js_nodes = js["elements"].filter { |e| e["type"] == "node" }
176       assert_equal 3, js_nodes.count
177
178       way.nodes.each_with_index do |n, i|
179         assert_equal n.id, js_ways[0]["nodes"][i]
180         js_nodes_with_id = js_nodes.filter { |e| e["id"] == n.id }
181         assert_equal 1, js_nodes_with_id.count
182         assert_equal n.id, js_nodes_with_id[0]["id"]
183         assert_equal 1, js_nodes_with_id[0]["version"]
184         assert_equal n.lat, js_nodes_with_id[0]["lat"]
185         assert_equal n.lon, js_nodes_with_id[0]["lon"]
186       end
187     end
188
189     def test_show_full_deleted
190       way = create(:way, :deleted)
191
192       get api_way_path(way, :full => true)
193
194       assert_response :gone
195     end
196
197     # -------------------------------------
198     # Test simple way creation.
199     # -------------------------------------
200
201     def test_create
202       node1 = create(:node)
203       node2 = create(:node)
204       private_user = create(:user, :data_public => false)
205       private_changeset = create(:changeset, :user => private_user)
206       user = create(:user)
207       changeset = create(:changeset, :user => user)
208
209       ## First check that it fails when creating a way using a non-public user
210       auth_header = bearer_authorization_header private_user
211
212       # use the first user's open changeset
213       changeset_id = private_changeset.id
214
215       # create a way with pre-existing nodes
216       xml = <<~OSM
217         <osm>
218           <way changeset='#{changeset_id}'>
219             <nd ref='#{node1.id}'/>
220             <nd ref='#{node2.id}'/>
221             <tag k='test' v='yes' />
222           </way>
223         </osm>
224       OSM
225       post api_ways_path, :params => xml, :headers => auth_header
226       # hope for failure
227       assert_response :forbidden,
228                       "way upload did not return forbidden status"
229
230       ## Now use a public user
231       auth_header = bearer_authorization_header user
232
233       # use the first user's open changeset
234       changeset_id = changeset.id
235
236       # create a way with pre-existing nodes
237       xml = <<~OSM
238         <osm>
239           <way changeset='#{changeset_id}'>
240             <nd ref='#{node1.id}'/>
241             <nd ref='#{node2.id}'/>
242             <tag k='test' v='yes' />
243           </way>
244         </osm>
245       OSM
246       post api_ways_path, :params => xml, :headers => auth_header
247       # hope for success
248       assert_response :success,
249                       "way upload did not return success status"
250       # read id of created way and search for it
251       wayid = @response.body
252       checkway = Way.find(wayid)
253       assert_not_nil checkway,
254                      "uploaded way not found in data base after upload"
255       # compare values
256       assert_equal(2, checkway.nds.length, "saved way does not contain exactly one node")
257       assert_equal checkway.nds[0], node1.id,
258                    "saved way does not contain the right node on pos 0"
259       assert_equal checkway.nds[1], node2.id,
260                    "saved way does not contain the right node on pos 1"
261       assert_equal checkway.changeset_id, changeset_id,
262                    "saved way does not belong to the correct changeset"
263       assert_equal user.id, checkway.changeset.user_id,
264                    "saved way does not belong to user that created it"
265       assert checkway.visible,
266              "saved way is not visible"
267     end
268
269     # -------------------------------------
270     # Test creating some invalid ways.
271     # -------------------------------------
272
273     def test_create_invalid
274       node = create(:node)
275       private_user = create(:user, :data_public => false)
276       private_open_changeset = create(:changeset, :user => private_user)
277       private_closed_changeset = create(:changeset, :closed, :user => private_user)
278       user = create(:user)
279       open_changeset = create(:changeset, :user => user)
280       closed_changeset = create(:changeset, :closed, :user => user)
281
282       ## First test with a private user to make sure that they are not authorized
283       auth_header = bearer_authorization_header private_user
284
285       # use the first user's open changeset
286       # create a way with non-existing node
287       xml = <<~OSM
288         <osm>
289           <way changeset='#{private_open_changeset.id}'>
290             <nd ref='0'/>
291           </way>
292         </osm>
293       OSM
294       post api_ways_path, :params => xml, :headers => auth_header
295       # expect failure
296       assert_response :forbidden,
297                       "way upload with invalid node using a private user did not return 'forbidden'"
298
299       # create a way with no nodes
300       xml = <<~OSM
301         <osm>
302           <way changeset='#{private_open_changeset.id}'>
303           </way>
304         </osm>
305       OSM
306       post api_ways_path, :params => xml, :headers => auth_header
307       # expect failure
308       assert_response :forbidden,
309                       "way upload with no node using a private userdid not return 'forbidden'"
310
311       # create a way inside a closed changeset
312       xml = <<~OSM
313         <osm>
314           <way changeset='#{private_closed_changeset.id}'>
315             <nd ref='#{node.id}'/>
316           </way>
317         </osm>
318       OSM
319       post api_ways_path, :params => xml, :headers => auth_header
320       # expect failure
321       assert_response :forbidden,
322                       "way upload to closed changeset with a private user did not return 'forbidden'"
323
324       ## Now test with a public user
325       auth_header = bearer_authorization_header user
326
327       # use the first user's open changeset
328       # create a way with non-existing node
329       xml = <<~OSM
330         <osm>
331           <way changeset='#{open_changeset.id}'>
332             <nd ref='0'/>
333           </way>
334         </osm>
335       OSM
336       post api_ways_path, :params => xml, :headers => auth_header
337       # expect failure
338       assert_response :precondition_failed,
339                       "way upload with invalid node did not return 'precondition failed'"
340       assert_equal "Precondition failed: Way  requires the nodes with id in (0), which either do not exist, or are not visible.", @response.body
341
342       # create a way with no nodes
343       xml = <<~OSM
344         <osm>
345           <way changeset='#{open_changeset.id}'>
346           </way>
347         </osm>
348       OSM
349       post api_ways_path, :params => xml, :headers => auth_header
350       # expect failure
351       assert_response :precondition_failed,
352                       "way upload with no node did not return 'precondition failed'"
353       assert_equal "Precondition failed: Cannot create way: data is invalid.", @response.body
354
355       # create a way inside a closed changeset
356       xml = <<~OSM
357         <osm>
358           <way changeset='#{closed_changeset.id}'>
359             <nd ref='#{node.id}'/>
360           </way>
361         </osm>
362       OSM
363       post api_ways_path, :params => xml, :headers => auth_header
364       # expect failure
365       assert_response :conflict,
366                       "way upload to closed changeset did not return 'conflict'"
367
368       # create a way with a tag which is too long
369       xml = <<~OSM
370         <osm>
371           <way changeset='#{open_changeset.id}'>
372             <nd ref='#{node.id}'/>
373             <tag k='foo' v='#{'x' * 256}'/>
374           </way>
375         </osm>
376       OSM
377       post api_ways_path, :params => xml, :headers => auth_header
378       # expect failure
379       assert_response :bad_request,
380                       "way upload to with too long tag did not return 'bad_request'"
381     end
382
383     # -------------------------------------
384     # Test deleting ways.
385     # -------------------------------------
386
387     def test_destroy
388       private_user = create(:user, :data_public => false)
389       private_open_changeset = create(:changeset, :user => private_user)
390       private_closed_changeset = create(:changeset, :closed, :user => private_user)
391       private_way = create(:way, :changeset => private_open_changeset)
392       private_deleted_way = create(:way, :deleted, :changeset => private_open_changeset)
393       private_used_way = create(:way, :changeset => private_open_changeset)
394       create(:relation_member, :member => private_used_way)
395       user = create(:user)
396       open_changeset = create(:changeset, :user => user)
397       closed_changeset = create(:changeset, :closed, :user => user)
398       way = create(:way, :changeset => open_changeset)
399       deleted_way = create(:way, :deleted, :changeset => open_changeset)
400       used_way = create(:way, :changeset => open_changeset)
401       relation_member = create(:relation_member, :member => used_way)
402       relation = relation_member.relation
403
404       # first try to delete way without auth
405       delete api_way_path(way)
406       assert_response :unauthorized
407
408       # now set auth using the private user
409       auth_header = bearer_authorization_header private_user
410
411       # this shouldn't work as with the 0.6 api we need pay load to delete
412       delete api_way_path(private_way), :headers => auth_header
413       assert_response :forbidden
414
415       # Now try without having a changeset
416       xml = "<osm><way id='#{private_way.id}'/></osm>"
417       delete api_way_path(private_way), :params => xml.to_s, :headers => auth_header
418       assert_response :forbidden
419
420       # try to delete with an invalid (closed) changeset
421       xml = update_changeset(xml_for_way(private_way), private_closed_changeset.id)
422       delete api_way_path(private_way), :params => xml.to_s, :headers => auth_header
423       assert_response :forbidden
424
425       # try to delete with an invalid (non-existent) changeset
426       xml = update_changeset(xml_for_way(private_way), 0)
427       delete api_way_path(private_way), :params => xml.to_s, :headers => auth_header
428       assert_response :forbidden
429
430       # Now try with a valid changeset
431       xml = xml_for_way(private_way)
432       delete api_way_path(private_way), :params => xml.to_s, :headers => auth_header
433       assert_response :forbidden
434
435       # check the returned value - should be the new version number
436       # valid delete should return the new version number, which should
437       # be greater than the old version number
438       # assert @response.body.to_i > current_ways(:visible_way).version,
439       #   "delete request should return a new version number for way"
440
441       # this won't work since the way is already deleted
442       xml = xml_for_way(private_deleted_way)
443       delete api_way_path(private_deleted_way), :params => xml.to_s, :headers => auth_header
444       assert_response :forbidden
445
446       # this shouldn't work as the way is used in a relation
447       xml = xml_for_way(private_used_way)
448       delete api_way_path(private_used_way), :params => xml.to_s, :headers => auth_header
449       assert_response :forbidden,
450                       "shouldn't be able to delete a way used in a relation (#{@response.body}), when done by a private user"
451
452       # this won't work since the way never existed
453       delete api_way_path(0), :headers => auth_header
454       assert_response :forbidden
455
456       ### Now check with a public user
457       # now set auth
458       auth_header = bearer_authorization_header user
459
460       # this shouldn't work as with the 0.6 api we need pay load to delete
461       delete api_way_path(way), :headers => auth_header
462       assert_response :bad_request
463
464       # Now try without having a changeset
465       xml = "<osm><way id='#{way.id}'/></osm>"
466       delete api_way_path(way), :params => xml.to_s, :headers => auth_header
467       assert_response :bad_request
468
469       # try to delete with an invalid (closed) changeset
470       xml = update_changeset(xml_for_way(way), closed_changeset.id)
471       delete api_way_path(way), :params => xml.to_s, :headers => auth_header
472       assert_response :conflict
473
474       # try to delete with an invalid (non-existent) changeset
475       xml = update_changeset(xml_for_way(way), 0)
476       delete api_way_path(way), :params => xml.to_s, :headers => auth_header
477       assert_response :conflict
478
479       # Now try with a valid changeset
480       xml = xml_for_way(way)
481       delete api_way_path(way), :params => xml.to_s, :headers => auth_header
482       assert_response :success
483
484       # check the returned value - should be the new version number
485       # valid delete should return the new version number, which should
486       # be greater than the old version number
487       assert_operator @response.body.to_i, :>, way.version, "delete request should return a new version number for way"
488
489       # this won't work since the way is already deleted
490       xml = xml_for_way(deleted_way)
491       delete api_way_path(deleted_way), :params => xml.to_s, :headers => auth_header
492       assert_response :gone
493
494       # this shouldn't work as the way is used in a relation
495       xml = xml_for_way(used_way)
496       delete api_way_path(used_way), :params => xml.to_s, :headers => auth_header
497       assert_response :precondition_failed,
498                       "shouldn't be able to delete a way used in a relation (#{@response.body})"
499       assert_equal "Precondition failed: Way #{used_way.id} is still used by relations #{relation.id}.", @response.body
500
501       # this won't work since the way never existed
502       delete api_way_path(0), :params => xml.to_s, :headers => auth_header
503       assert_response :not_found
504     end
505
506     ##
507     # tests whether the API works and prevents incorrect use while trying
508     # to update ways.
509     def test_update
510       private_user = create(:user, :data_public => false)
511       private_way = create(:way, :changeset => create(:changeset, :user => private_user))
512       user = create(:user)
513       way = create(:way, :changeset => create(:changeset, :user => user))
514       node = create(:node)
515       create(:way_node, :way => private_way, :node => node)
516       create(:way_node, :way => way, :node => node)
517
518       ## First test with no user credentials
519       # try and update a way without authorisation
520       xml = xml_for_way(way)
521       put api_way_path(way), :params => xml.to_s
522       assert_response :unauthorized
523
524       ## Second test with the private user
525
526       # setup auth
527       auth_header = bearer_authorization_header private_user
528
529       ## trying to break changesets
530
531       # try and update in someone else's changeset
532       xml = update_changeset(xml_for_way(private_way),
533                              create(:changeset).id)
534       put api_way_path(private_way), :params => xml.to_s, :headers => auth_header
535       assert_require_public_data "update with other user's changeset should be forbidden when date isn't public"
536
537       # try and update in a closed changeset
538       xml = update_changeset(xml_for_way(private_way),
539                              create(:changeset, :closed, :user => private_user).id)
540       put api_way_path(private_way), :params => xml.to_s, :headers => auth_header
541       assert_require_public_data "update with closed changeset should be forbidden, when data isn't public"
542
543       # try and update in a non-existant changeset
544       xml = update_changeset(xml_for_way(private_way), 0)
545       put api_way_path(private_way), :params => xml.to_s, :headers => auth_header
546       assert_require_public_data("update with changeset=0 should be forbidden, when data isn't public")
547
548       ## try and submit invalid updates
549       xml = xml_replace_node(xml_for_way(private_way), node.id, 9999)
550       put api_way_path(private_way), :params => xml.to_s, :headers => auth_header
551       assert_require_public_data "way with non-existent node should be forbidden, when data isn't public"
552
553       xml = xml_replace_node(xml_for_way(private_way), node.id, create(:node, :deleted).id)
554       put api_way_path(private_way), :params => xml.to_s, :headers => auth_header
555       assert_require_public_data "way with deleted node should be forbidden, when data isn't public"
556
557       ## finally, produce a good request which will still not work
558       xml = xml_for_way(private_way)
559       put api_way_path(private_way), :params => xml.to_s, :headers => auth_header
560       assert_require_public_data "should have failed with a forbidden when data isn't public"
561
562       ## Finally test with the public user
563
564       # setup auth
565       auth_header = bearer_authorization_header user
566
567       ## trying to break changesets
568
569       # try and update in someone else's changeset
570       xml = update_changeset(xml_for_way(way),
571                              create(:changeset).id)
572       put api_way_path(way), :params => xml.to_s, :headers => auth_header
573       assert_response :conflict, "update with other user's changeset should be rejected"
574
575       # try and update in a closed changeset
576       xml = update_changeset(xml_for_way(way),
577                              create(:changeset, :closed, :user => user).id)
578       put api_way_path(way), :params => xml.to_s, :headers => auth_header
579       assert_response :conflict, "update with closed changeset should be rejected"
580
581       # try and update in a non-existant changeset
582       xml = update_changeset(xml_for_way(way), 0)
583       put api_way_path(way), :params => xml.to_s, :headers => auth_header
584       assert_response :conflict, "update with changeset=0 should be rejected"
585
586       ## try and submit invalid updates
587       xml = xml_replace_node(xml_for_way(way), node.id, 9999)
588       put api_way_path(way), :params => xml.to_s, :headers => auth_header
589       assert_response :precondition_failed, "way with non-existent node should be rejected"
590
591       xml = xml_replace_node(xml_for_way(way), node.id, create(:node, :deleted).id)
592       put api_way_path(way), :params => xml.to_s, :headers => auth_header
593       assert_response :precondition_failed, "way with deleted node should be rejected"
594
595       ## next, attack the versioning
596       current_way_version = way.version
597
598       # try and submit a version behind
599       xml = xml_attr_rewrite(xml_for_way(way),
600                              "version", current_way_version - 1)
601       put api_way_path(way), :params => xml.to_s, :headers => auth_header
602       assert_response :conflict, "should have failed on old version number"
603
604       # try and submit a version ahead
605       xml = xml_attr_rewrite(xml_for_way(way),
606                              "version", current_way_version + 1)
607       put api_way_path(way), :params => xml.to_s, :headers => auth_header
608       assert_response :conflict, "should have failed on skipped version number"
609
610       # try and submit total crap in the version field
611       xml = xml_attr_rewrite(xml_for_way(way),
612                              "version", "p1r4t3s!")
613       put api_way_path(way), :params => xml.to_s, :headers => auth_header
614       assert_response :conflict,
615                       "should not be able to put 'p1r4at3s!' in the version field"
616
617       ## try an update with the wrong ID
618       xml = xml_for_way(create(:way))
619       put api_way_path(way), :params => xml.to_s, :headers => auth_header
620       assert_response :bad_request,
621                       "should not be able to update a way with a different ID from the XML"
622
623       ## try an update with a minimal valid XML doc which isn't a well-formed OSM doc.
624       xml = "<update/>"
625       put api_way_path(way), :params => xml.to_s, :headers => auth_header
626       assert_response :bad_request,
627                       "should not be able to update a way with non-OSM XML doc."
628
629       ## finally, produce a good request which should work
630       xml = xml_for_way(way)
631       put api_way_path(way), :params => xml.to_s, :headers => auth_header
632       assert_response :success, "a valid update request failed"
633     end
634
635     # ------------------------------------------------------------
636     # test tags handling
637     # ------------------------------------------------------------
638
639     ##
640     # Try adding a new tag to a way
641     def test_add_tags
642       private_user = create(:user, :data_public => false)
643       private_way = create(:way_with_nodes, :nodes_count => 2, :changeset => create(:changeset, :user => private_user))
644       user = create(:user)
645       way = create(:way_with_nodes, :nodes_count => 2, :changeset => create(:changeset, :user => user))
646
647       ## Try with the non-public user
648       # setup auth
649       auth_header = bearer_authorization_header private_user
650
651       # add an identical tag to the way
652       tag_xml = XML::Node.new("tag")
653       tag_xml["k"] = "new"
654       tag_xml["v"] = "yes"
655
656       # add the tag into the existing xml
657       way_xml = xml_for_way(private_way)
658       way_xml.find("//osm/way").first << tag_xml
659
660       # try and upload it
661       put api_way_path(private_way), :params => way_xml.to_s, :headers => auth_header
662       assert_response :forbidden,
663                       "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
664
665       ## Now try with the public user
666       # setup auth
667       auth_header = bearer_authorization_header user
668
669       # add an identical tag to the way
670       tag_xml = XML::Node.new("tag")
671       tag_xml["k"] = "new"
672       tag_xml["v"] = "yes"
673
674       # add the tag into the existing xml
675       way_xml = xml_for_way(way)
676       way_xml.find("//osm/way").first << tag_xml
677
678       # try and upload it
679       put api_way_path(way), :params => way_xml.to_s, :headers => auth_header
680       assert_response :success,
681                       "adding a new tag to a way should succeed"
682       assert_equal way.version + 1, @response.body.to_i
683     end
684
685     ##
686     # Try adding a duplicate of an existing tag to a way
687     def test_add_duplicate_tags
688       private_user = create(:user, :data_public => false)
689       private_way = create(:way, :changeset => create(:changeset, :user => private_user))
690       private_existing_tag = create(:way_tag, :way => private_way)
691       user = create(:user)
692       way = create(:way, :changeset => create(:changeset, :user => user))
693       existing_tag = create(:way_tag, :way => way)
694
695       ## Try with the non-public user
696       # setup auth
697       auth_header = bearer_authorization_header private_user
698
699       # add an identical tag to the way
700       tag_xml = XML::Node.new("tag")
701       tag_xml["k"] = private_existing_tag.k
702       tag_xml["v"] = private_existing_tag.v
703
704       # add the tag into the existing xml
705       way_xml = xml_for_way(private_way)
706       way_xml.find("//osm/way").first << tag_xml
707
708       # try and upload it
709       put api_way_path(private_way), :params => way_xml.to_s, :headers => auth_header
710       assert_response :forbidden,
711                       "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
712
713       ## Now try with the public user
714       # setup auth
715       auth_header = bearer_authorization_header user
716
717       # add an identical tag to the way
718       tag_xml = XML::Node.new("tag")
719       tag_xml["k"] = existing_tag.k
720       tag_xml["v"] = existing_tag.v
721
722       # add the tag into the existing xml
723       way_xml = xml_for_way(way)
724       way_xml.find("//osm/way").first << tag_xml
725
726       # try and upload it
727       put api_way_path(way), :params => way_xml.to_s, :headers => auth_header
728       assert_response :bad_request,
729                       "adding a duplicate tag to a way should fail with 'bad request'"
730       assert_equal "Element way/#{way.id} has duplicate tags with key #{existing_tag.k}", @response.body
731     end
732
733     ##
734     # Try adding a new duplicate tags to a way
735     def test_new_duplicate_tags
736       private_user = create(:user, :data_public => false)
737       private_way = create(:way, :changeset => create(:changeset, :user => private_user))
738       user = create(:user)
739       way = create(:way, :changeset => create(:changeset, :user => user))
740
741       ## First test with the non-public user so should be rejected
742       # setup auth
743       auth_header = bearer_authorization_header private_user
744
745       # create duplicate tag
746       tag_xml = XML::Node.new("tag")
747       tag_xml["k"] = "i_am_a_duplicate"
748       tag_xml["v"] = "foobar"
749
750       # add the tag into the existing xml
751       way_xml = xml_for_way(private_way)
752
753       # add two copies of the tag
754       way_xml.find("//osm/way").first << tag_xml.copy(true) << tag_xml
755
756       # try and upload it
757       put api_way_path(private_way), :params => way_xml.to_s, :headers => auth_header
758       assert_response :forbidden,
759                       "adding new duplicate tags to a way using a non-public user should fail with 'forbidden'"
760
761       ## Now test with the public user
762       # setup auth
763       auth_header = bearer_authorization_header user
764
765       # create duplicate tag
766       tag_xml = XML::Node.new("tag")
767       tag_xml["k"] = "i_am_a_duplicate"
768       tag_xml["v"] = "foobar"
769
770       # add the tag into the existing xml
771       way_xml = xml_for_way(way)
772
773       # add two copies of the tag
774       way_xml.find("//osm/way").first << tag_xml.copy(true) << tag_xml
775
776       # try and upload it
777       put api_way_path(way), :params => way_xml.to_s, :headers => auth_header
778       assert_response :bad_request,
779                       "adding new duplicate tags to a way should fail with 'bad request'"
780       assert_equal "Element way/#{way.id} has duplicate tags with key i_am_a_duplicate", @response.body
781     end
782
783     ##
784     # Try adding a new duplicate tags to a way.
785     # But be a bit subtle - use unicode decoding ambiguities to use different
786     # binary strings which have the same decoding.
787     def test_invalid_duplicate_tags
788       private_user = create(:user, :data_public => false)
789       private_changeset = create(:changeset, :user => private_user)
790       user = create(:user)
791       changeset = create(:changeset, :user => user)
792
793       ## First make sure that you can't with a non-public user
794       # setup auth
795       auth_header = bearer_authorization_header private_user
796
797       # add the tag into the existing xml
798       way_str = <<~OSM
799         <osm>
800           <way changeset='#{private_changeset.id}'>
801             <tag k='addr:housenumber' v='1'/>
802             <tag k='addr:housenumber' v='2'/>
803           </way>
804         </osm>
805       OSM
806
807       # try and upload it
808       post api_ways_path, :params => way_str, :headers => auth_header
809       assert_response :forbidden,
810                       "adding new duplicate tags to a way with a non-public user should fail with 'forbidden'"
811
812       ## Now do it with a public user
813       # setup auth
814       auth_header = bearer_authorization_header user
815
816       # add the tag into the existing xml
817       way_str = <<~OSM
818         <osm>
819           <way changeset='#{changeset.id}'>
820             <tag k='addr:housenumber' v='1'/>
821             <tag k='addr:housenumber' v='2'/>
822           </way>
823         </osm>
824       OSM
825
826       # try and upload it
827       post api_ways_path, :params => way_str, :headers => auth_header
828       assert_response :bad_request,
829                       "adding new duplicate tags to a way should fail with 'bad request'"
830       assert_equal "Element way/ has duplicate tags with key addr:housenumber", @response.body
831     end
832
833     ##
834     # test initial rate limit
835     def test_initial_rate_limit
836       # create a user
837       user = create(:user)
838
839       # create some nodes
840       node1 = create(:node)
841       node2 = create(:node)
842
843       # create a changeset that puts us near the initial rate limit
844       changeset = create(:changeset, :user => user,
845                                      :created_at => Time.now.utc - 5.minutes,
846                                      :num_changes => Settings.initial_changes_per_hour - 1)
847
848       # create authentication header
849       auth_header = bearer_authorization_header user
850
851       # try creating a way
852       xml = <<~OSM
853         <osm>
854           <way changeset='#{changeset.id}'>
855             <nd ref='#{node1.id}'/>
856             <nd ref='#{node2.id}'/>
857           </way>
858         </osm>
859       OSM
860       post api_ways_path, :params => xml, :headers => auth_header
861       assert_response :success, "way create did not return success status"
862
863       # get the id of the way we created
864       wayid = @response.body
865
866       # try updating the way, which should be rate limited
867       xml = <<~OSM
868         <osm>
869           <way id='#{wayid}' version='1' changeset='#{changeset.id}'>
870             <nd ref='#{node2.id}'/>
871             <nd ref='#{node1.id}'/>
872           </way>
873         </osm>
874       OSM
875       put api_way_path(wayid), :params => xml, :headers => auth_header
876       assert_response :too_many_requests, "way update did not hit rate limit"
877
878       # try deleting the way, which should be rate limited
879       xml = "<osm><way id='#{wayid}' version='2' changeset='#{changeset.id}'/></osm>"
880       delete api_way_path(wayid), :params => xml, :headers => auth_header
881       assert_response :too_many_requests, "way delete did not hit rate limit"
882
883       # try creating a way, which should be rate limited
884       xml = <<~OSM
885         <osm>
886           <way changeset='#{changeset.id}'>
887             <nd ref='#{node1.id}'/>
888             <nd ref='#{node2.id}'/>
889           </way>
890         </osm>
891       OSM
892       post api_ways_path, :params => xml, :headers => auth_header
893       assert_response :too_many_requests, "way create did not hit rate limit"
894     end
895
896     ##
897     # test maximum rate limit
898     def test_maximum_rate_limit
899       # create a user
900       user = create(:user)
901
902       # create some nodes
903       node1 = create(:node)
904       node2 = create(:node)
905
906       # create a changeset to establish our initial edit time
907       changeset = create(:changeset, :user => user,
908                                      :created_at => Time.now.utc - 28.days)
909
910       # create changeset to put us near the maximum rate limit
911       total_changes = Settings.max_changes_per_hour - 1
912       while total_changes.positive?
913         changes = [total_changes, Changeset::MAX_ELEMENTS].min
914         changeset = create(:changeset, :user => user,
915                                        :created_at => Time.now.utc - 5.minutes,
916                                        :num_changes => changes)
917         total_changes -= changes
918       end
919
920       # create authentication header
921       auth_header = bearer_authorization_header user
922
923       # try creating a way
924       xml = <<~OSM
925         <osm>
926           <way changeset='#{changeset.id}'>
927             <nd ref='#{node1.id}'/>
928             <nd ref='#{node2.id}'/>
929           </way>
930         </osm>
931       OSM
932       post api_ways_path, :params => xml, :headers => auth_header
933       assert_response :success, "way create did not return success status"
934
935       # get the id of the way we created
936       wayid = @response.body
937
938       # try updating the way, which should be rate limited
939       xml = <<~OSM
940         <osm>
941           <way id='#{wayid}' version='1' changeset='#{changeset.id}'>
942             <nd ref='#{node2.id}'/>
943             <nd ref='#{node1.id}'/>
944           </way>
945         </osm>
946       OSM
947       put api_way_path(wayid), :params => xml, :headers => auth_header
948       assert_response :too_many_requests, "way update did not hit rate limit"
949
950       # try deleting the way, which should be rate limited
951       xml = "<osm><way id='#{wayid}' version='2' changeset='#{changeset.id}'/></osm>"
952       delete api_way_path(wayid), :params => xml, :headers => auth_header
953       assert_response :too_many_requests, "way delete did not hit rate limit"
954
955       # try creating a way, which should be rate limited
956       xml = <<~OSM
957         <osm>
958           <way changeset='#{changeset.id}'>
959             <nd ref='#{node1.id}'/>
960             <nd ref='#{node2.id}'/>
961           </way>
962         </osm>
963       OSM
964       post api_ways_path, :params => xml, :headers => auth_header
965       assert_response :too_many_requests, "way create did not hit rate limit"
966     end
967
968     private
969
970     ##
971     # update the changeset_id of a way element
972     def update_changeset(xml, changeset_id)
973       xml_attr_rewrite(xml, "changeset", changeset_id)
974     end
975
976     ##
977     # update an attribute in the way element
978     def xml_attr_rewrite(xml, name, value)
979       xml.find("//osm/way").first[name] = value.to_s
980       xml
981     end
982
983     ##
984     # replace a node in a way element
985     def xml_replace_node(xml, old_node, new_node)
986       xml.find("//osm/way/nd[@ref='#{old_node}']").first["ref"] = new_node.to_s
987       xml
988     end
989   end
990 end