From 29e06d83c0aa183ea48dfb53bf38162d5d078ab4 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 12 Jul 2018 15:13:01 +0300 Subject: [PATCH 01/60] Add description for authentication endpoint --- doc/registrant-api.md | 24 ++++++ doc/registrant-api/authentication.md | 120 +++++++++++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 doc/registrant-api.md create mode 100644 doc/registrant-api/authentication.md diff --git a/doc/registrant-api.md b/doc/registrant-api.md new file mode 100644 index 000000000..c8dd852c2 --- /dev/null +++ b/doc/registrant-api.md @@ -0,0 +1,24 @@ +# Registrant API integration specification + +REPP uses HTTP/1.1 protocol (http://tools.ietf.org/html/rfc2616) and +Basic Authentication (http://tools.ietf.org/html/rfc2617#section-2) using +Secure Transport (https://tools.ietf.org/html/rfc5246) with certificate and key +(https://tools.ietf.org/html/rfc5280). + +Credentials and certificate are issued by EIS (in an exchange for desired API +username, CSR and IP). + +To quickly test the API, use curl: + + curl -q -k --cert user.crt.pem --key user.key.pem https://TBA/repp/v1/accounts/balance -u username:password + +Test API endpoint: https://testepp.internet.ee/repp/v1 +Production API endpoint: TBA + +Main communication specification through Restful EPP (REPP): + +[Contact related functions](repp/v1/contact.md) +[Domain related functions](repp/v1/domain.md) +[Domain transfers](repp/v1/domain_transfers.md) +[Account related functions](repp/v1/account.md) +[Nameservers](repp/v1/nameservers.md) diff --git a/doc/registrant-api/authentication.md b/doc/registrant-api/authentication.md new file mode 100644 index 000000000..5396d82b6 --- /dev/null +++ b/doc/registrant-api/authentication.md @@ -0,0 +1,120 @@ +# Authentication + +## Authenticating with mobileID or ID-card + +For specified partners the API allows for use of data from mobile ID for +authentication. API client should perform authentication with eID according to +the approriate documentation, and then pass on values from the webserver's +certificate to the API server. + +## POST /repp/v1/auth/eid/token + +Returns a bearer token to be used for further API requests. Tokens are valid for 2 hours since their creation. + +#### Paramaters + +Values in brackets represent values that come from the id card certificate. + +| Field name | Required | Type | Allowed values | Description | +| ----------------- | -------- | ---- | -------------- | ----------- | +| ident | true | String | | Identity code of the user (`serialNumber`) | +| first_name | true | String | | Name of the customer (`GN`) | +| last_name | true | String | | Name of the customer (`SN`) | +| country | true | String | 'ee' | Code of the country that issued the id card (`C`) | +| issuing authority | true | String | 'AS Sertifitseerimiskeskus' | | +| | | | | | + + +#### Request +``` +POST /repp/v1/auth/token HTTP/1.1 +Accept: application/json +Content-length: 0 +Content-type: application/json + +{ + "ident": "30110100103", + "first_name": "Jaan", + "last_name": "Tamm", + "country": "ee", + "issuing authority": "AS Sertifitseerimiskeskus" +} +``` + +#### Response +``` +HTTP/1.1 201 +Cache-Control: max-age=0, private, must-revalidate +Content-Length: 0 +Content-Type: application.json + + +{ + "access_token": "", + "expires_at": "2018-07-13 11:30:51 UTC", + "type": "Bearer" +} +``` + +## POST /repp/v1/auth/username/token -- NOT IMPLEMENTED + +#### Paramaters + +Values in brackets represent values that come from the id card certificate + +| Field name | Required | Type | Allowed values | Description | +| ----------------- | -------- | ---- | -------------- | ----------- | +| username | true | String | Username as provided by the user | | +| password | true | String | Password as provided by the user | | + + +#### Request +``` +POST /repp/v1/auth/token HTTP/1.1 +Accept: application/json +Content-length: 0 +Content-type: application/json +``` + +#### Response +``` +HTTP/1.1 201 +Cache-Control: max-age=0, private, must-revalidate +Content-Length: 0 +Content-Type: application.json + + +{ + "access_token": "", + "expires_at": "2018-07-13 11:30:51 UTC", + "type": "Bearer" +} +``` + +## Implementation notes: + +We do not need to store the session data at all, instead we can levarage AES encryption and use +Rails secret as the key. General approximation: + +```ruby +class AuthenticationToken + def initialize(secret = Rails.application.config.secret_key_base, values = {}) + end + + def create_token_hash + data = values.to_s + + cipher = OpenSSL::Cipher::AES.new(256, :CBC) + cipher.encrypt + + encrypted = cipher.update(data) + cipher.final + base64_encoded = Base64.encode64(encrypted) + + { + token: base64_encoded, + expires_in = values[:expires_in] + type: "Bearer" + } + end +end +``` From d49b4b5c0f622665577cef2100402cc40cc0fc9e Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Fri, 13 Jul 2018 16:19:34 +0300 Subject: [PATCH 02/60] Add domain list documentation --- doc/registrant-api.md | 8 +- doc/registrant-api/{ => v1}/authentication.md | 2 +- doc/registrant-api/v1/domain.md | 102 ++++++++++++++++++ 3 files changed, 106 insertions(+), 6 deletions(-) rename doc/registrant-api/{ => v1}/authentication.md (98%) create mode 100644 doc/registrant-api/v1/domain.md diff --git a/doc/registrant-api.md b/doc/registrant-api.md index c8dd852c2..7ab295d38 100644 --- a/doc/registrant-api.md +++ b/doc/registrant-api.md @@ -17,8 +17,6 @@ Production API endpoint: TBA Main communication specification through Restful EPP (REPP): -[Contact related functions](repp/v1/contact.md) -[Domain related functions](repp/v1/domain.md) -[Domain transfers](repp/v1/domain_transfers.md) -[Account related functions](repp/v1/account.md) -[Nameservers](repp/v1/nameservers.md) +[Authentication](registrant-api/v1/authentication.md) +[Domain related functions](registrant-api/v1/domain.md) +[Contact related functions](registrant-api/v1/contact.md) diff --git a/doc/registrant-api/authentication.md b/doc/registrant-api/v1/authentication.md similarity index 98% rename from doc/registrant-api/authentication.md rename to doc/registrant-api/v1/authentication.md index 5396d82b6..f9486f57a 100644 --- a/doc/registrant-api/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -7,7 +7,7 @@ authentication. API client should perform authentication with eID according to the approriate documentation, and then pass on values from the webserver's certificate to the API server. -## POST /repp/v1/auth/eid/token +## POST /repp/v1/registrant/auth/eid/token Returns a bearer token to be used for further API requests. Tokens are valid for 2 hours since their creation. diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md new file mode 100644 index 000000000..b39f28cae --- /dev/null +++ b/doc/registrant-api/v1/domain.md @@ -0,0 +1,102 @@ +# Domain related actions + +## GET /repp/v1/registrant/domains +Returns domains of the current registrar. + + +#### Parameters + +| Field name | Required | Type | Allowed values | Description | +| ---------- | -------- | ---- | -------------- | ----------- | +| limit | false | Integer | [1..200] | How many domains to show | +| offset | false | Integer | | Domain number to start at | +| details | false | String | ["true", "false"] | Whether to include details | + +#### Request +``` +GET repp/v1/registrant/domains?limit=1&details=true HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Length: 0 +Content-Type: application/json +``` + +#### Response +``` +HTTP/1.1 200 +Cache-Control: max-age=0, private, must-revalidate +Content-Length: 808 +Content-Type: application/json + +{ + "domains": [ + { + "id": 1, + "name": "domain0.ee", + "registrar_id": 2, + "registered_at": "2015-09-09T09:11:14.861Z", + "status": null, + "valid_from": "2015-09-09T09:11:14.861Z", + "valid_to": "2016-09-09T09:11:14.861Z", + "registrant_id": 1, + "transfer_code": "98oiewslkfkd", + "created_at": "2015-09-09T09:11:14.861Z", + "updated_at": "2015-09-09T09:11:14.860Z", + "name_dirty": "domain0.ee", + "name_puny": "domain0.ee", + "period": 1, + "period_unit": "y", + "creator_str": null, + "updator_str": null, + "legacy_id": null, + "legacy_registrar_id": null, + "legacy_registrant_id": null, + "outzone_at": "2016-09-24T09:11:14.861Z", + "delete_at": "2016-10-24T09:11:14.861Z", + "registrant_verification_asked_at": null, + "registrant_verification_token": null, + "pending_json": { + }, + "force_delete_at": null, + "statuses": [ + "ok" + ], + "reserved": false, + "status_notes": { + }, + "statuses_backup": [ + + ] + } + ], + "total_number_of_records": 2 +} +``` + +## GET repp/v1/registrant/domains +Returns domain names with offset. + + +#### Request +``` +GET repp/v1/registrant/domains?offset=1 HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Length: 0 +Content-Type: application/json +``` + +#### Response +``` +HTTP/1.1 200 +Cache-Control: max-age=0, private, must-revalidate +Content-Length: 54 +Content-Type: application/json + +{ + "domains": [ + "domain1.ee" + ], + "total_number_of_records": 2 +} +``` From f965878b42a327904d1e76143419abd9c85c34a4 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 16 Jul 2018 10:28:17 +0300 Subject: [PATCH 03/60] Add contact endpoint documentation --- doc/registrant-api/v1/authentication.md | 6 +- doc/registrant-api/v1/contact.md | 148 ++++++++++++++++++++++++ doc/registrant-api/v1/domain.md | 8 +- 3 files changed, 157 insertions(+), 5 deletions(-) create mode 100644 doc/registrant-api/v1/contact.md diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index f9486f57a..f914a7a23 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -7,7 +7,7 @@ authentication. API client should perform authentication with eID according to the approriate documentation, and then pass on values from the webserver's certificate to the API server. -## POST /repp/v1/registrant/auth/eid/token +## POST /repp/v1/registrant/auth/eid Returns a bearer token to be used for further API requests. Tokens are valid for 2 hours since their creation. @@ -34,7 +34,7 @@ Content-type: application/json { "ident": "30110100103", - "first_name": "Jaan", + "first_name": "Jan", "last_name": "Tamm", "country": "ee", "issuing authority": "AS Sertifitseerimiskeskus" @@ -56,7 +56,7 @@ Content-Type: application.json } ``` -## POST /repp/v1/auth/username/token -- NOT IMPLEMENTED +## POST /repp/v1/auth/username -- NOT IMPLEMENTED #### Paramaters diff --git a/doc/registrant-api/v1/contact.md b/doc/registrant-api/v1/contact.md new file mode 100644 index 000000000..126ae27c6 --- /dev/null +++ b/doc/registrant-api/v1/contact.md @@ -0,0 +1,148 @@ +## GET /repp/v1/registrant/contacts +Returns contacts of the current registrar. + + +#### Parameters + +| Field name | Required | Type | Allowed values | Description | +| ---------- | -------- | ---- | -------------- | ----------- | +| limit | false | Integer | [1..200] | How many contacts to show | +| offset | false | Integer | | Contact number to start at | + +#### Request +``` +GET /repp/v1/registrant/contacts?limit=1 HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Type: application/json +``` + +#### Response +``` +HTTP/1.1 200 +Cache-Control: max-age=0, private, must-revalidate +Content-Length: 564 +Content-Type: application/json + +{ + "contacts": [ + { + "uuid": "84c62f3d-e56f-40fa-9ca4-dc0137778949", + "domain_name": "example.com" + "code": "REGISTRAR2:SH022086480", + "phone": "+372.12345678", + "email": "hoyt@deckowbechtelar.net", + "fax": null, + "created_at": "2015-09-09T09:11:14.130Z", + "updated_at": "2015-09-09T09:11:14.130Z", + "ident": "37605030299", + "ident_type": "priv", + "auth_info": "password", + "name": "Karson Kessler0", + "org_name": null, + "registrar_id": 2, + "creator_str": null, + "updator_str": null, + "ident_country_code": "EE", + "city": "Tallinn", + "street": "Short street 11", + "zip": "11111", + "country_code": "EE", + "state": null, + "legacy_id": null, + "statuses": [ + "ok" + ], + "status_notes": { + } + } + ], + "total_number_of_records": 2 +} +``` + +## PUT/PATCH /rep/v1/registrant/contacts/$UUID + +Update contact details for a contact. + +#### Parameters + +| Field name | Required | Type | Allowed values | Description | +| ---- | --- | --- | --- | --- | +| email | false | String | | New email address | +| phone | false | String | | New phone number | +| fax | false | String | | New fax number | +| city | false | String | | New city name | +| street | false | String | | New street name | +| zip | false | String | | New zip code | +| country_code | false | String | | New country code in 2 letter format ('EE', 'LV') | +| state | false | String | | New state name | + + +#### Request +``` +PUT /repp/v1/registrant/contacts/84c62f3d-e56f-40fa-9ca4-dc0137778949 HTTP/1.1 +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Accept: application/json +Content-type: application/json + +{ + "email": "foo@bar.baz", + "phone": "+372.12345671", + "fax": "+372.12345672", + "city": "New City", + "street": "Main Street 123", + "zip": "22222", + "country_code": "LV", + "state": "New state" +} + +``` +#### Response on success + +``` +HTTP/1.1 200 +Content-Type: application.json + +{ + "uuid": "84c62f3d-e56f-40fa-9ca4-dc0137778949", + "domain_name": "example.com" + "code": "REGISTRAR2:SH022086480", + "phone": "+372.12345671", + "email": "foo@bar.baz", + "fax": "+372.12345672", + "created_at": "2015-09-09T09:11:14.130Z", + "updated_at": "2018-09-09T09:11:14.130Z", + "ident": "37605030299", + "ident_type": "priv", + "auth_info": "password", + "name": "Karson Kessler0", + "org_name": null, + "registrar_id": 2, + "creator_str": null, + "updator_str": null, + "ident_country_code": "EE", + "city": "New City", + "street": "Main Street 123", + "zip": "22222", + "country_code": "LV", + "state": "New state" + "legacy_id": null, + "statuses": [ + "ok" + ], + "status_notes": {} +} +``` + +### Response on failure +``` +HTTP/1.1 400 +Content-Type: application.json + +{ + "errors": [ + { "phone": "Phone nr is invalid" } + ] +} +``` diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index b39f28cae..5ea82a376 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -1,7 +1,7 @@ # Domain related actions ## GET /repp/v1/registrant/domains -Returns domains of the current registrar. +Returns domains of the current registrant. #### Parameters @@ -65,7 +65,6 @@ Content-Type: application/json "status_notes": { }, "statuses_backup": [ - ] } ], @@ -100,3 +99,8 @@ Content-Type: application/json "total_number_of_records": 2 } ``` + +#### Implementation details + +This endpoint is practically a copy-paste from similar endpoint used by +registrars. From 2e2e5cd08deb698b9c0cc130d74c531969bcc0d0 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 16 Jul 2018 13:32:40 +0300 Subject: [PATCH 04/60] Add GET contact info endpoint --- doc/registrant-api/v1/contact.md | 52 +++++++++++++++++++++++++++++++- doc/registrant-api/v1/domain.md | 7 +---- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/doc/registrant-api/v1/contact.md b/doc/registrant-api/v1/contact.md index 126ae27c6..127c9fdb4 100644 --- a/doc/registrant-api/v1/contact.md +++ b/doc/registrant-api/v1/contact.md @@ -61,7 +61,57 @@ Content-Type: application/json } ``` -## PUT/PATCH /rep/v1/registrant/contacts/$UUID +## GET /repp/v1/registrant/contacts/$UUID +Returns contacts of the current registrar. + + +#### Request +``` +GET /repp/v1/registrant/contacts/84c62f3d-e56f-40fa-9ca4-dc0137778949 HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Type: application/json +``` + +#### Response +``` +HTTP/1.1 200 +Cache-Control: max-age=0, private, must-revalidate +Content-Length: 564 +Content-Type: application/json + +{ + "uuid": "84c62f3d-e56f-40fa-9ca4-dc0137778949", + "domain_name": "example.com" + "code": "REGISTRAR2:SH022086480", + "phone": "+372.12345678", + "email": "hoyt@deckowbechtelar.net", + "fax": null, + "created_at": "2015-09-09T09:11:14.130Z", + "updated_at": "2015-09-09T09:11:14.130Z", + "ident": "37605030299", + "ident_type": "priv", + "auth_info": "password", + "name": "Karson Kessler0", + "org_name": null, + "registrar_id": 2, + "creator_str": null, + "updator_str": null, + "ident_country_code": "EE", + "city": "Tallinn", + "street": "Short street 11", + "zip": "11111", + "country_code": "EE", + "state": null, + "legacy_id": null, + "statuses": [ + "ok" + ], + "status_notes": {} +} +``` + +## PUT/PATCH /repp/v1/registrant/contacts/$UUID Update contact details for a contact. diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index 5ea82a376..db9b17978 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -31,7 +31,7 @@ Content-Type: application/json { "domains": [ { - "id": 1, + "uuid": "98d1083a-8863-4153-93e4-caee4a013535", "name": "domain0.ee", "registrar_id": 2, "registered_at": "2015-09-09T09:11:14.861Z", @@ -99,8 +99,3 @@ Content-Type: application/json "total_number_of_records": 2 } ``` - -#### Implementation details - -This endpoint is practically a copy-paste from similar endpoint used by -registrars. From 6aeda6444e9efcaecfc14a62347ae557f570bc23 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 16 Jul 2018 13:47:55 +0300 Subject: [PATCH 05/60] Change `domain_names` to be an array, not a singular object --- doc/registrant-api/v1/contact.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/registrant-api/v1/contact.md b/doc/registrant-api/v1/contact.md index 127c9fdb4..32d194a75 100644 --- a/doc/registrant-api/v1/contact.md +++ b/doc/registrant-api/v1/contact.md @@ -28,7 +28,7 @@ Content-Type: application/json "contacts": [ { "uuid": "84c62f3d-e56f-40fa-9ca4-dc0137778949", - "domain_name": "example.com" + "domain_names": ["example.com"], "code": "REGISTRAR2:SH022086480", "phone": "+372.12345678", "email": "hoyt@deckowbechtelar.net", @@ -82,7 +82,7 @@ Content-Type: application/json { "uuid": "84c62f3d-e56f-40fa-9ca4-dc0137778949", - "domain_name": "example.com" + "domain_names": ["example.com"], "code": "REGISTRAR2:SH022086480", "phone": "+372.12345678", "email": "hoyt@deckowbechtelar.net", @@ -156,7 +156,7 @@ Content-Type: application.json { "uuid": "84c62f3d-e56f-40fa-9ca4-dc0137778949", - "domain_name": "example.com" + "domain_names": ["example.com"], "code": "REGISTRAR2:SH022086480", "phone": "+372.12345671", "email": "foo@bar.baz", From e2d2768b6e35de19ed96e45f61eb5f8c693888ee Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 16 Jul 2018 14:26:59 +0300 Subject: [PATCH 06/60] Update domain endpoint --- doc/registrant-api/v1/domain.md | 68 +++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index db9b17978..bfc4349eb 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -17,7 +17,6 @@ Returns domains of the current registrant. GET repp/v1/registrant/domains?limit=1&details=true HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== -Content-Length: 0 Content-Type: application/json ``` @@ -81,15 +80,12 @@ Returns domain names with offset. GET repp/v1/registrant/domains?offset=1 HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== -Content-Length: 0 Content-Type: application/json ``` #### Response ``` HTTP/1.1 200 -Cache-Control: max-age=0, private, must-revalidate -Content-Length: 54 Content-Type: application/json { @@ -99,3 +95,67 @@ Content-Type: application/json "total_number_of_records": 2 } ``` + +## GET repp/v1/registrant/domains/$UUID +Returns domain names with offset. + + +#### Request +``` +GET repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535 HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Length: 0 +Content-Type: application/json +``` + +#### Response for success + +``` +HTTP/1.1 200 +Content-Type: application/json + +{ + "uuid": "98d1083a-8863-4153-93e4-caee4a013535", + "name": "domain0.ee", + "registrar_id": 2, + "registered_at": "2015-09-09T09:11:14.861Z", + "status": null, + "valid_from": "2015-09-09T09:11:14.861Z", + "valid_to": "2016-09-09T09:11:14.861Z", + "registrant_id": 1, + "transfer_code": "98oiewslkfkd", + "created_at": "2015-09-09T09:11:14.861Z", + "updated_at": "2015-09-09T09:11:14.860Z", + "name_dirty": "domain0.ee", + "name_puny": "domain0.ee", + "period": 1, + "period_unit": "y", + "creator_str": null, + "updator_str": null, + "legacy_id": null, + "legacy_registrar_id": null, + "legacy_registrant_id": null, + "outzone_at": "2016-09-24T09:11:14.861Z", + "delete_at": "2016-10-24T09:11:14.861Z", + "registrant_verification_asked_at": null, + "registrant_verification_token": null, + "pending_json": {}, + "force_delete_at": null, + "statuses": [ + "ok" + ], + "reserved": false, + "status_notes": {}, + "statuses_backup": [] +} +``` + +#### Response for failure + +``` +HTTP/1.1 404 +Content-Type: application/json + +{ "error": "Domain not found" } +``` From 270444b2e8be80dd81b2781890c1715f8d2c75f8 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 16 Jul 2018 16:03:51 +0300 Subject: [PATCH 07/60] Add registry lock documentation --- doc/registrant-api.md | 21 +--- doc/registrant-api/v1/domain.md | 5 +- doc/registrant-api/v1/domain_lock.md | 164 +++++++++++++++++++++++++++ 3 files changed, 173 insertions(+), 17 deletions(-) create mode 100644 doc/registrant-api/v1/domain_lock.md diff --git a/doc/registrant-api.md b/doc/registrant-api.md index 7ab295d38..c6f063a91 100644 --- a/doc/registrant-api.md +++ b/doc/registrant-api.md @@ -1,22 +1,11 @@ # Registrant API integration specification -REPP uses HTTP/1.1 protocol (http://tools.ietf.org/html/rfc2616) and -Basic Authentication (http://tools.ietf.org/html/rfc2617#section-2) using -Secure Transport (https://tools.ietf.org/html/rfc5246) with certificate and key -(https://tools.ietf.org/html/rfc5280). - -Credentials and certificate are issued by EIS (in an exchange for desired API -username, CSR and IP). - -To quickly test the API, use curl: - - curl -q -k --cert user.crt.pem --key user.key.pem https://TBA/repp/v1/accounts/balance -u username:password - -Test API endpoint: https://testepp.internet.ee/repp/v1 +Test API endpoint: TBA Production API endpoint: TBA -Main communication specification through Restful EPP (REPP): +Main communication specification through Registrant API: [Authentication](registrant-api/v1/authentication.md) -[Domain related functions](registrant-api/v1/domain.md) -[Contact related functions](registrant-api/v1/contact.md) +[Domains](registrant-api/v1/domain.md) +[Domain Lock](registrant-api/v1/domain_lock.md) +[Contacts](registrant-api/v1/contact.md) diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index bfc4349eb..f4b5b2895 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -1,6 +1,7 @@ # Domain related actions ## GET /repp/v1/registrant/domains + Returns domains of the current registrant. @@ -72,6 +73,7 @@ Content-Type: application/json ``` ## GET repp/v1/registrant/domains + Returns domain names with offset. @@ -97,7 +99,8 @@ Content-Type: application/json ``` ## GET repp/v1/registrant/domains/$UUID -Returns domain names with offset. + +Returns a single domain object. #### Request diff --git a/doc/registrant-api/v1/domain_lock.md b/doc/registrant-api/v1/domain_lock.md new file mode 100644 index 000000000..7dcd6efa4 --- /dev/null +++ b/doc/registrant-api/v1/domain_lock.md @@ -0,0 +1,164 @@ +# Domain locks + +## POST repp/v1/registrant/domains/$UUID/registry_lock + +Set a registry lock on a domain. + +#### Request +``` +POST repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535/registry_lock HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Type: application/json +``` + +#### Response for success + +``` +HTTP/1.1 200 +Content-Type: application/json + +{ + "uuid": "98d1083a-8863-4153-93e4-caee4a013535", + "name": "domain0.ee", + "registrar_id": 2, + "registered_at": "2015-09-09T09:11:14.861Z", + "status": null, + "valid_from": "2015-09-09T09:11:14.861Z", + "valid_to": "2016-09-09T09:11:14.861Z", + "registrant_id": 1, + "transfer_code": "98oiewslkfkd", + "created_at": "2015-09-09T09:11:14.861Z", + "updated_at": "2015-09-09T09:11:14.860Z", + "name_dirty": "domain0.ee", + "name_puny": "domain0.ee", + "period": 1, + "period_unit": "y", + "creator_str": null, + "updator_str": null, + "legacy_id": null, + "legacy_registrar_id": null, + "legacy_registrant_id": null, + "outzone_at": "2016-09-24T09:11:14.861Z", + "delete_at": "2016-10-24T09:11:14.861Z", + "registrant_verification_asked_at": null, + "registrant_verification_token": null, + "pending_json": {}, + "force_delete_at": null, + "statuses": [ + "clientUpdateProhibited", + "serverUpdateProhibited", + "serverTransferProhibited", + "serverDeleteProhibited", + ], + "reserved": false, + "status_notes": {}, + "statuses_backup": [] +} +``` + +#### Response for failure + +``` +HTTP/1.1 400 +Content-Type: application/json + +{ + "errors": [ + { "base": "domain cannot be locked" } + ] +} + +``` + +``` +HTTP/1.1 404 +Content-Type: application/json + +{ + "errors": [ + { "base": "domain does not exist" } + ] +} + +``` + +## DELETE repp/v1/registrant/domains/$UUID/registry_lock + +Remove a registry lock. + +#### Request +``` +DELETE repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535/registry_lock HTTP/1.1 +Accept: application/json +Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== +Content-Type: application/json +``` + +#### Response for success + +``` +HTTP/1.1 200 +Content-Type: application/json + +{ + "uuid": "98d1083a-8863-4153-93e4-caee4a013535", + "name": "domain0.ee", + "registrar_id": 2, + "registered_at": "2015-09-09T09:11:14.861Z", + "status": null, + "valid_from": "2015-09-09T09:11:14.861Z", + "valid_to": "2016-09-09T09:11:14.861Z", + "registrant_id": 1, + "transfer_code": "98oiewslkfkd", + "created_at": "2015-09-09T09:11:14.861Z", + "updated_at": "2015-09-09T09:11:14.860Z", + "name_dirty": "domain0.ee", + "name_puny": "domain0.ee", + "period": 1, + "period_unit": "y", + "creator_str": null, + "updator_str": null, + "legacy_id": null, + "legacy_registrar_id": null, + "legacy_registrant_id": null, + "outzone_at": "2016-09-24T09:11:14.861Z", + "delete_at": "2016-10-24T09:11:14.861Z", + "registrant_verification_asked_at": null, + "registrant_verification_token": null, + "pending_json": {}, + "force_delete_at": null, + "statuses": [ + "ok" + ], + "reserved": false, + "status_notes": {}, + "statuses_backup": [] +} +``` + +#### Response for failure + +``` +HTTP/1.1 400 +Content-Type: application/json + +{ + "errors": [ + { "base": "domain cannot be unlocked" } + ] +} + +``` + +``` +HTTP/1.1 404 +Content-Type: application/json + +{ + "errors": [ + { "base": "domain does not exist" } + ] +} + +``` From e42951bec881fb2a5bb47c0347e6fcc9bc0020fc Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 17 Jul 2018 12:46:21 +0300 Subject: [PATCH 08/60] Update statuses for registry lock --- doc/registrant-api/v1/domain_lock.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc/registrant-api/v1/domain_lock.md b/doc/registrant-api/v1/domain_lock.md index 7dcd6efa4..6702d4233 100644 --- a/doc/registrant-api/v1/domain_lock.md +++ b/doc/registrant-api/v1/domain_lock.md @@ -47,9 +47,8 @@ Content-Type: application/json "force_delete_at": null, "statuses": [ "clientUpdateProhibited", - "serverUpdateProhibited", - "serverTransferProhibited", - "serverDeleteProhibited", + "clientDeleteProhibited", + "clientTransferProhibited" ], "reserved": false, "status_notes": {}, From d71726c55d1ee23741272de63a273704ea63a04a Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 17 Jul 2018 15:04:55 +0300 Subject: [PATCH 09/60] Remove Content-Length header from examples --- doc/registrant-api/v1/authentication.md | 4 ---- doc/registrant-api/v1/contact.md | 2 -- doc/registrant-api/v1/domain.md | 2 -- 3 files changed, 8 deletions(-) diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index f914a7a23..b3b926a67 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -29,7 +29,6 @@ Values in brackets represent values that come from the id card certificate. ``` POST /repp/v1/auth/token HTTP/1.1 Accept: application/json -Content-length: 0 Content-type: application/json { @@ -45,7 +44,6 @@ Content-type: application/json ``` HTTP/1.1 201 Cache-Control: max-age=0, private, must-revalidate -Content-Length: 0 Content-Type: application.json @@ -72,7 +70,6 @@ Values in brackets represent values that come from the id card certificate ``` POST /repp/v1/auth/token HTTP/1.1 Accept: application/json -Content-length: 0 Content-type: application/json ``` @@ -80,7 +77,6 @@ Content-type: application/json ``` HTTP/1.1 201 Cache-Control: max-age=0, private, must-revalidate -Content-Length: 0 Content-Type: application.json diff --git a/doc/registrant-api/v1/contact.md b/doc/registrant-api/v1/contact.md index 32d194a75..8ce129cdb 100644 --- a/doc/registrant-api/v1/contact.md +++ b/doc/registrant-api/v1/contact.md @@ -21,7 +21,6 @@ Content-Type: application/json ``` HTTP/1.1 200 Cache-Control: max-age=0, private, must-revalidate -Content-Length: 564 Content-Type: application/json { @@ -77,7 +76,6 @@ Content-Type: application/json ``` HTTP/1.1 200 Cache-Control: max-age=0, private, must-revalidate -Content-Length: 564 Content-Type: application/json { diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index f4b5b2895..49953f4a1 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -25,7 +25,6 @@ Content-Type: application/json ``` HTTP/1.1 200 Cache-Control: max-age=0, private, must-revalidate -Content-Length: 808 Content-Type: application/json { @@ -108,7 +107,6 @@ Returns a single domain object. GET repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535 HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== -Content-Length: 0 Content-Type: application/json ``` From aa87d001d562ebf84ca0943653ac533a84ee69f5 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 17 Jul 2018 15:07:32 +0300 Subject: [PATCH 10/60] Remove Cache-Control headers from examples --- doc/registrant-api/v1/authentication.md | 2 -- doc/registrant-api/v1/contact.md | 2 -- doc/registrant-api/v1/domain.md | 1 - 3 files changed, 5 deletions(-) diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index b3b926a67..1c65691d2 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -43,7 +43,6 @@ Content-type: application/json #### Response ``` HTTP/1.1 201 -Cache-Control: max-age=0, private, must-revalidate Content-Type: application.json @@ -76,7 +75,6 @@ Content-type: application/json #### Response ``` HTTP/1.1 201 -Cache-Control: max-age=0, private, must-revalidate Content-Type: application.json diff --git a/doc/registrant-api/v1/contact.md b/doc/registrant-api/v1/contact.md index 8ce129cdb..ea28294d0 100644 --- a/doc/registrant-api/v1/contact.md +++ b/doc/registrant-api/v1/contact.md @@ -20,7 +20,6 @@ Content-Type: application/json #### Response ``` HTTP/1.1 200 -Cache-Control: max-age=0, private, must-revalidate Content-Type: application/json { @@ -75,7 +74,6 @@ Content-Type: application/json #### Response ``` HTTP/1.1 200 -Cache-Control: max-age=0, private, must-revalidate Content-Type: application/json { diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index 49953f4a1..80290fbac 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -24,7 +24,6 @@ Content-Type: application/json #### Response ``` HTTP/1.1 200 -Cache-Control: max-age=0, private, must-revalidate Content-Type: application/json { From e1605f81eb75278a91ffe16df9bbf8003cd872ab Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 18 Jul 2018 14:34:07 +0300 Subject: [PATCH 11/60] Fix error in authentication field name --- doc/registrant-api/v1/authentication.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index 1c65691d2..2b25a62c2 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -21,7 +21,7 @@ Values in brackets represent values that come from the id card certificate. | first_name | true | String | | Name of the customer (`GN`) | | last_name | true | String | | Name of the customer (`SN`) | | country | true | String | 'ee' | Code of the country that issued the id card (`C`) | -| issuing authority | true | String | 'AS Sertifitseerimiskeskus' | | +| issuing_authority | true | String | 'AS Sertifitseerimiskeskus' | | | | | | | | @@ -36,7 +36,7 @@ Content-type: application/json "first_name": "Jan", "last_name": "Tamm", "country": "ee", - "issuing authority": "AS Sertifitseerimiskeskus" + "issuing_authority": "AS Sertifitseerimiskeskus" } ``` From 74c97eb9238c7c187495f39ea68d12e4049d37ee Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 18 Jul 2018 15:21:53 +0300 Subject: [PATCH 12/60] Remove issuing authority as a parameter from authentication --- doc/registrant-api/v1/authentication.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index 2b25a62c2..13638fca7 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -21,8 +21,6 @@ Values in brackets represent values that come from the id card certificate. | first_name | true | String | | Name of the customer (`GN`) | | last_name | true | String | | Name of the customer (`SN`) | | country | true | String | 'ee' | Code of the country that issued the id card (`C`) | -| issuing_authority | true | String | 'AS Sertifitseerimiskeskus' | | -| | | | | | #### Request @@ -36,7 +34,6 @@ Content-type: application/json "first_name": "Jan", "last_name": "Tamm", "country": "ee", - "issuing_authority": "AS Sertifitseerimiskeskus" } ``` From d67e777ea835ed62dc38b518ace5f113aac5e675 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 18 Jul 2018 16:24:55 +0300 Subject: [PATCH 13/60] Create a Registrant auth controller --- .../api/v1/registrant/auth_controller.rb | 19 +++++++++++++++ config/application.rb | 2 +- config/routes.rb | 9 +++++++ .../registrant_api_authentication_test.rb | 24 +++++++++++++++++++ 4 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 app/controllers/api/v1/registrant/auth_controller.rb create mode 100644 test/system/api/registrant/registrant_api_authentication_test.rb diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb new file mode 100644 index 000000000..c137a1286 --- /dev/null +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -0,0 +1,19 @@ +require 'rails5_api_controller_backport' + +module Api + module V1 + module Registrant + class AuthController < ActionController::API + def eid + login_params = set_eid_params + + render json: login_params + end + + def set_eid_params + params.permit(:ident, :first_name, :last_name, :country) + end + end + end + end +end diff --git a/config/application.rb b/config/application.rb index 400e72124..1420d3cd3 100644 --- a/config/application.rb +++ b/config/application.rb @@ -36,7 +36,7 @@ module DomainNameRegistry config.i18n.default_locale = :en config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb') - config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] + # config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] # Autoload all model subdirs config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')] diff --git a/config/routes.rb b/config/routes.rb index 8f50d5587..2bc965a0f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -18,6 +18,15 @@ Rails.application.routes.draw do mount Repp::API => '/' + namespace :api do + namespace :v1 do + namespace :registrant do + post 'auth/eid', to: 'auth#eid' + post 'auth/username', to: 'auth#username' + end + end + end + # REGISTRAR ROUTES namespace :registrar do resource :dashboard diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb new file mode 100644 index 000000000..5ecd7e08a --- /dev/null +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -0,0 +1,24 @@ +require 'test_helper' + +class RegistrantApiAuthenticationTest < ApplicationSystemTestCase + def setup + super + + end + + def teardown + super + + end + + def test_request_creates_user_when_one_does_not_exist + params = { + ident: "30110100103", + first_name: "Jan", + last_name: "Tamm", + country: "ee", + } + + post '/api/v1/registrant/auth/eid', params + end +end From 1b9a504fb5c4ece69bd4a181d9c99229987d0ead Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 18 Jul 2018 21:22:13 +0300 Subject: [PATCH 14/60] Remove country as identification parameter, restore server statuses --- doc/registrant-api/v1/authentication.md | 12 +++++------- doc/registrant-api/v1/domain_lock.md | 6 +++--- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index 13638fca7..558bb1880 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -15,12 +15,11 @@ Returns a bearer token to be used for further API requests. Tokens are valid for Values in brackets represent values that come from the id card certificate. -| Field name | Required | Type | Allowed values | Description | -| ----------------- | -------- | ---- | -------------- | ----------- | -| ident | true | String | | Identity code of the user (`serialNumber`) | -| first_name | true | String | | Name of the customer (`GN`) | -| last_name | true | String | | Name of the customer (`SN`) | -| country | true | String | 'ee' | Code of the country that issued the id card (`C`) | +| Field name | Required | Type | Allowed values | Description | +| ----------------- | -------- | ---- | -------------- | ----------- | +| ident | true | String | | Identity code of the user (`serialNumber`) | +| first_name | true | String | | Name of the customer (`GN`) | +| last_name | true | String | | Name of the customer (`SN`) | #### Request @@ -33,7 +32,6 @@ Content-type: application/json "ident": "30110100103", "first_name": "Jan", "last_name": "Tamm", - "country": "ee", } ``` diff --git a/doc/registrant-api/v1/domain_lock.md b/doc/registrant-api/v1/domain_lock.md index 6702d4233..0237a11cb 100644 --- a/doc/registrant-api/v1/domain_lock.md +++ b/doc/registrant-api/v1/domain_lock.md @@ -46,9 +46,9 @@ Content-Type: application/json "pending_json": {}, "force_delete_at": null, "statuses": [ - "clientUpdateProhibited", - "clientDeleteProhibited", - "clientTransferProhibited" + "serverUpdateProhibited", + "serverDeleteProhibited", + "serverTransferProhibited" ], "reserved": false, "status_notes": {}, From 1c6b838b2bc5c6caa71068e63ef600a5d1836a12 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 19 Jul 2018 10:31:31 +0300 Subject: [PATCH 15/60] Add auth-token class --- .../api/v1/registrant/auth_controller.rb | 18 +++++++++++-- app/models/registrant_user.rb | 10 +++++++ lib/auth_token.rb | 26 +++++++++++++++++++ .../registrant_api_authentication_test.rb | 15 ++++++++--- test/test_helper.rb | 2 +- 5 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 lib/auth_token.rb diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index c137a1286..36bf750a8 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -1,4 +1,5 @@ require 'rails5_api_controller_backport' +require 'auth_token' module Api module V1 @@ -7,11 +8,24 @@ module Api def eid login_params = set_eid_params - render json: login_params + user = RegistrantUser.find_or_create_by_api_data(login_params) + + unless user.valid? + render json: user.errors, status: :bad_request + else + token = create_token(user) + render json: token + end end def set_eid_params - params.permit(:ident, :first_name, :last_name, :country) + params.permit(:ident, :first_name, :last_name) + end + + def create_token(user) + token = AuthToken.new + hash = token.generate_token(user) + hash end end end diff --git a/app/models/registrant_user.rb b/app/models/registrant_user.rb index 12cae0d82..8f742a361 100644 --- a/app/models/registrant_user.rb +++ b/app/models/registrant_user.rb @@ -52,6 +52,16 @@ class RegistrantUser < User u end + def find_or_create_by_api_data(api_data = {}) + estonian_ident = "EE-#{api_data[:ident]}" + + user = find_or_create_by(registrant_ident: estonian_ident) + user.username = "#{api_data[:first_name]}, #{api_data[:last_name]}" + user.save + + user + end + def find_or_create_by_mid_data(response) u = where(registrant_ident: "#{response.user_country}-#{response.user_id_code}").first_or_create u.username = "#{response.user_givenname} #{response.user_surname}" diff --git a/lib/auth_token.rb b/lib/auth_token.rb new file mode 100644 index 000000000..5313d603d --- /dev/null +++ b/lib/auth_token.rb @@ -0,0 +1,26 @@ +class AuthToken + def initialize; end + + def generate_token(user, secret = Rails.application.config.secret_key_base) + cipher = OpenSSL::Cipher::AES.new(256, :CBC) + expires_at = (Time.now.utc + 2.hours).strftime("%F %T %Z") + + data = { + username: user.username, + expires_at: expires_at + } + + hashable = data.to_json + + cipher.encrypt + cipher.key = secret + encrypted = cipher.update(hashable) + cipher.final + base64_encoded = Base64.encode64(encrypted) + + { + access_token: base64_encoded, + expires_at: expires_at, + type: "Bearer" + } + end +end diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb index 5ecd7e08a..6789b3d5d 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -4,6 +4,8 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase def setup super + @user_hash = {ident: "37010100049", first_name: 'Adam', last_name: 'Baker'} + @existing_user = RegistrantUser.find_or_create_by_api_data(@user_hash) end def teardown @@ -14,11 +16,18 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase def test_request_creates_user_when_one_does_not_exist params = { ident: "30110100103", - first_name: "Jan", - last_name: "Tamm", - country: "ee", + first_name: "John", + last_name: "Smith", } post '/api/v1/registrant/auth/eid', params + assert(User.find_by(registrant_ident: 'EE-30110100103')) + + json = JSON.parse(response.body, symbolize_names: true) + assert_equal([:access_token, :expires_at, :type], json.keys) + end + + def test_request_returns_existing_user + end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 500861f75..56a4a7aeb 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -11,7 +11,7 @@ require 'minitest/mock' require 'capybara/rails' require 'capybara/minitest' require 'webmock/minitest' -require 'support/rails5_assetions' # Remove once upgraded to Rails 5 +require 'support/rails5_assertions' # Remove once upgraded to Rails 5 require 'application_system_test_case' From dad57ba52882087e92f77941167e25149f512b17 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 19 Jul 2018 11:50:40 +0300 Subject: [PATCH 16/60] Implement the basic interface for the Authentication endpoint * Handle errors as 422 * Require parameters through strong_parameters * Use a custom rescue_from --- .../api/v1/registrant/auth_controller.rb | 27 ++++++++++++------- app/models/registrant_user.rb | 6 ++++- .../registrant_api_authentication_test.rb | 11 ++++++++ test/test_helper.rb | 2 +- 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 36bf750a8..bfd99baad 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -5,21 +5,30 @@ module Api module V1 module Registrant class AuthController < ActionController::API + rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception| + error = {} + error[parameter_missing_exception.param] = ['parameter is required'] + response = { errors: [error] } + render json: response, status: :unprocessable_entity + end + def eid - login_params = set_eid_params + user = RegistrantUser.find_or_create_by_api_data(eid_params) + token = create_token(user) - user = RegistrantUser.find_or_create_by_api_data(login_params) - - unless user.valid? - render json: user.errors, status: :bad_request - else - token = create_token(user) + if token render json: token + else + render json: { error: 'Cannot create generate session token'} end end - def set_eid_params - params.permit(:ident, :first_name, :last_name) + private + + def eid_params + [:ident, :first_name, :last_name].each_with_object(params) do |key, obj| + obj.require(key) + end end def create_token(user) diff --git a/app/models/registrant_user.rb b/app/models/registrant_user.rb index 8f742a361..db851eb6a 100644 --- a/app/models/registrant_user.rb +++ b/app/models/registrant_user.rb @@ -53,10 +53,14 @@ class RegistrantUser < User end def find_or_create_by_api_data(api_data = {}) + return false unless api_data[:ident] + return false unless api_data[:first_name] + return false unless api_data[:last_name] + estonian_ident = "EE-#{api_data[:ident]}" user = find_or_create_by(registrant_ident: estonian_ident) - user.username = "#{api_data[:first_name]}, #{api_data[:last_name]}" + user.username = "#{api_data[:first_name]} #{api_data[:last_name]}" user.save user diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb index 6789b3d5d..82b5f48fd 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -28,6 +28,17 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase end def test_request_returns_existing_user + assert_no_changes User.count do + post '/api/v1/registrant/auth/eid', @user_hash + end + end + def test_request_documented_parameters_are_required + params = { foo: :bar, test: :test } + + post '/api/v1/registrant/auth/eid', params + json = JSON.parse(response.body, symbolize_names: true) + assert_equal({errors: [{ident: ['parameter is required']}]}, json) + assert_equal(422, response.status) end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 56a4a7aeb..500861f75 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -11,7 +11,7 @@ require 'minitest/mock' require 'capybara/rails' require 'capybara/minitest' require 'webmock/minitest' -require 'support/rails5_assertions' # Remove once upgraded to Rails 5 +require 'support/rails5_assetions' # Remove once upgraded to Rails 5 require 'application_system_test_case' From dc8230dcc21a8f13641202ee2fcae780b6eb00e7 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Fri, 20 Jul 2018 15:21:10 +0300 Subject: [PATCH 17/60] Create AuthTokenCreator and AuthTokenDecryptor classes --- .../api/v1/registrant/auth_controller.rb | 6 +- lib/auth_token.rb | 26 ------- lib/auth_token/auth_token_creator.rb | 41 ++++++++++ lib/auth_token/auth_token_decryptor.rb | 43 +++++++++++ test/fixtures/users.yml | 1 + .../lib/auth_token/auth_token_creator_test.rb | 52 +++++++++++++ .../auth_token/auth_token_decryptor_test.rb | 77 +++++++++++++++++++ .../registrant_api_authentication_test.rb | 8 +- 8 files changed, 221 insertions(+), 33 deletions(-) delete mode 100644 lib/auth_token.rb create mode 100644 lib/auth_token/auth_token_creator.rb create mode 100644 lib/auth_token/auth_token_decryptor.rb create mode 100644 test/lib/auth_token/auth_token_creator_test.rb create mode 100644 test/lib/auth_token/auth_token_decryptor_test.rb diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index bfd99baad..5de962437 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -1,5 +1,5 @@ require 'rails5_api_controller_backport' -require 'auth_token' +require 'auth_token/auth_token_creator' module Api module V1 @@ -32,8 +32,8 @@ module Api end def create_token(user) - token = AuthToken.new - hash = token.generate_token(user) + token_creator = AuthTokenCreator.create_with_defaults(user) + hash = token_creator.token_in_hash hash end end diff --git a/lib/auth_token.rb b/lib/auth_token.rb deleted file mode 100644 index 5313d603d..000000000 --- a/lib/auth_token.rb +++ /dev/null @@ -1,26 +0,0 @@ -class AuthToken - def initialize; end - - def generate_token(user, secret = Rails.application.config.secret_key_base) - cipher = OpenSSL::Cipher::AES.new(256, :CBC) - expires_at = (Time.now.utc + 2.hours).strftime("%F %T %Z") - - data = { - username: user.username, - expires_at: expires_at - } - - hashable = data.to_json - - cipher.encrypt - cipher.key = secret - encrypted = cipher.update(hashable) + cipher.final - base64_encoded = Base64.encode64(encrypted) - - { - access_token: base64_encoded, - expires_at: expires_at, - type: "Bearer" - } - end -end diff --git a/lib/auth_token/auth_token_creator.rb b/lib/auth_token/auth_token_creator.rb new file mode 100644 index 000000000..2272a3650 --- /dev/null +++ b/lib/auth_token/auth_token_creator.rb @@ -0,0 +1,41 @@ +class AuthTokenCreator + DEFAULT_VALIDITY = 2.hours + + attr_reader :user + attr_reader :key + attr_reader :expires_at + + def self.create_with_defaults(user) + self.new(user, Rails.application.config.secret_key_base, Time.now + DEFAULT_VALIDITY) + end + + def initialize(user, key, expires_at) + @user = user + @key = key + @expires_at = expires_at.utc.strftime("%F %T %Z") + end + + def hashable + { + user_ident: user.registrant_ident, + user_username: user.username, + expires_at: expires_at + }.to_json + end + + def encrypted_token + encryptor = OpenSSL::Cipher::AES.new(256, :CBC) + encryptor.encrypt + encryptor.key = key + encrypted_bytes = encryptor.update(hashable) + encryptor.final + Base64.encode64(encrypted_bytes) + end + + def token_in_hash + { + access_token: encrypted_token, + expires_at: expires_at, + type: 'Bearer' + } + end +end diff --git a/lib/auth_token/auth_token_decryptor.rb b/lib/auth_token/auth_token_decryptor.rb new file mode 100644 index 000000000..1f513bece --- /dev/null +++ b/lib/auth_token/auth_token_decryptor.rb @@ -0,0 +1,43 @@ +class AuthTokenDecryptor + attr_reader :decrypted_data + attr_reader :token + attr_reader :key + attr_reader :user + + def self.create_with_defaults(token) + self.new(token, Rails.application.config.secret_key_base) + end + + def initialize(token, key) + @token = token + @key = key + end + + def decrypt_token + decipher = OpenSSL::Cipher::AES.new(256, :CBC) + decipher.decrypt + decipher.key = key + + base64_decoded = Base64.decode64(token) + plain = decipher.update(base64_decoded) + decipher.final + + @decrypted_data = JSON.parse(plain, symbolize_names: true) + rescue OpenSSL::Cipher::CipherError + false + end + + def valid? + decrypted_data && valid_user? && still_valid? + end + + private + + def valid_user? + @user = RegistrantUser.find_by(registrant_ident: decrypted_data[:user_ident]) + @user&.username == decrypted_data[:user_username] + end + + def still_valid? + decrypted_data[:expires_at] > Time.now + end +end diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml index b20bd8a83..5fd2dc925 100644 --- a/test/fixtures/users.yml +++ b/test/fixtures/users.yml @@ -26,3 +26,4 @@ admin: registrant: type: RegistrantUser registrant_ident: US-1234 + username: Registrant User diff --git a/test/lib/auth_token/auth_token_creator_test.rb b/test/lib/auth_token/auth_token_creator_test.rb new file mode 100644 index 000000000..4fab724c1 --- /dev/null +++ b/test/lib/auth_token/auth_token_creator_test.rb @@ -0,0 +1,52 @@ +require 'test_helper' +require 'openssl' +require_relative '../../../lib/auth_token/auth_token_creator' + +class AuthTokenCreatorTest < ActiveSupport::TestCase + def setup + super + + @user = users(:registrant) + time = Time.zone.parse('2010-07-05 00:30:00 +0000') + @random_bytes = SecureRandom.random_bytes(64) + @token_creator = AuthTokenCreator.new(@user, @random_bytes, time) + end + + def test_hashable_is_constructed_as_expected + expected_hashable = { user_ident: 'US-1234', user_username: 'Registrant User', + expires_at: '2010-07-05 00:30:00 UTC' }.to_json + assert_equal(expected_hashable, @token_creator.hashable) + end + + def test_encrypted_token_is_decryptable + encryptor = OpenSSL::Cipher::AES.new(256, :CBC) + encryptor.decrypt + encryptor.key = @random_bytes + + base64_decoded = Base64.decode64(@token_creator.encrypted_token) + result = encryptor.update(base64_decoded) + encryptor.final + + hashable = { user_ident: 'US-1234', user_username: 'Registrant User', + expires_at: '2010-07-05 00:30:00 UTC' }.to_json + + assert_equal(hashable, result) + end + + def test_token_in_json_returns_expected_values + @token_creator.stub(:encrypted_token, 'super_secure_token') do + token = @token_creator.token_in_hash + assert_equal('2010-07-05 00:30:00 UTC', token[:expires_at]) + assert_equal('Bearer', token[:type]) + end + end + + def test_create_with_defaults_injects_values + travel_to Time.zone.parse('2010-07-05 00:30:00 +0000') + + token_creator_with_defaults = AuthTokenCreator.create_with_defaults(@user) + assert_equal(Rails.application.config.secret_key_base, token_creator_with_defaults.key) + assert_equal('2010-07-05 02:30:00 UTC', token_creator_with_defaults.expires_at) + + travel_back + end +end diff --git a/test/lib/auth_token/auth_token_decryptor_test.rb b/test/lib/auth_token/auth_token_decryptor_test.rb new file mode 100644 index 000000000..d83de7990 --- /dev/null +++ b/test/lib/auth_token/auth_token_decryptor_test.rb @@ -0,0 +1,77 @@ +require 'test_helper' +require_relative '../../../lib/auth_token/auth_token_decryptor' +require_relative '../../../lib/auth_token/auth_token_creator' + +class AuthTokenDecryptorTest < ActiveSupport::TestCase + def setup + super + + travel_to Time.parse("2010-07-05 00:15:00 UTC") + @user = users(:registrant) + + # For testing purposes, the token needs to be random and long enough, hence: + @key = "b8+PtSq1+iXzUVnGEqciKsITNR0KmLl7uPiSTHbteqCoEBdbMLUl3GXlIDWD\nDZp1hIgKWnIMPNEgbuCa/7qccA==\n" + @faulty_key = "FALSE+iXzUVnGEqciKsITNR0KmLl7uPiSTHbteqCoEBdbMLUl3GXlIDWD\nDZp1hIgKWnIMPNEgbuCa/7qccA==\n" + + # this token corresponds to: + # {:user_ident=>"US-1234", :user_username=>"Registrant User", :expires_at=>"2010-07-05 02:15:00 UTC"} + @access_token = "q27NWIsKD5snWj9vZzJ0RcOYvgocEyu7H9yCaDjfmGi54sogovpBeALMPWTZ\nHMcdFQzSiq6b4cI0p5tO0/5UEOHic2jRzNW7mkhi+bn+Y2W9l9TJV0IdiTj9\nbaf+JvlbyaJh6+/eXIm0tuV5E8Ra9Q==\n" + end + + def teardown + super + + travel_back + end + + def test_decrypt_token_returns_a_hash_when_token_is_valid + decryptor = AuthTokenDecryptor.new(@access_token, @key) + + assert(decryptor.decrypt_token.is_a?(Hash)) + end + + def test_decrypt_token_return_false_when_token_is_invalid + faulty_decryptor = AuthTokenDecryptor.new(@access_token, @faulty_key) + refute(faulty_decryptor.decrypt_token) + end + + def test_valid_returns_true_for_valid_token + decryptor = AuthTokenDecryptor.new(@access_token, @key) + decryptor.decrypt_token + + assert(decryptor.valid?) + end + + def test_valid_returns_false_for_invalid_token + faulty_decryptor = AuthTokenDecryptor.new(@access_token, @faulty_key) + faulty_decryptor.decrypt_token + + refute(faulty_decryptor.valid?) + end + + def test_valid_returns_false_for_expired_token + travel_to Time.parse("2010-07-05 10:15:00 UTC") + + decryptor = AuthTokenDecryptor.new(@access_token, @key) + decryptor.decrypt_token + + refute(decryptor.valid?) + end + + def test_returns_false_for_non_existing_user + # This token was created from an admin user and @key. Decrypted, it corresponds to: + # {:user_ident=>nil, :user_username=>"test", :expires_at=>"2010-07-05 00:15:00 UTC"} + other_token = "rMkjgpyRcj2xOnHVwvvQ5RAS0yQepUSrw3XM5BrwM4TMH+h+TBeLve9InC/z\naPneMMnCs0NHQHt1EpH95A2YhX5P3HsyYITRErDmtlzUf21e185q/CUkW5NG\nWa4rar+6\n" + + decryptor = AuthTokenDecryptor.new(other_token, @key) + decryptor.decrypt_token + + refute(decryptor.valid?) + end + + def test_create_with_defaults_injects_values + decryptor = AuthTokenDecryptor.create_with_defaults(@access_token) + + assert_equal(Rails.application.config.secret_key_base, decryptor.key) + end +end diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb index 82b5f48fd..72da06fff 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -4,7 +4,7 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase def setup super - @user_hash = {ident: "37010100049", first_name: 'Adam', last_name: 'Baker'} + @user_hash = {ident: '37010100049', first_name: 'Adam', last_name: 'Baker'} @existing_user = RegistrantUser.find_or_create_by_api_data(@user_hash) end @@ -15,9 +15,9 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase def test_request_creates_user_when_one_does_not_exist params = { - ident: "30110100103", - first_name: "John", - last_name: "Smith", + ident: '30110100103', + first_name: 'John', + last_name: 'Smith', } post '/api/v1/registrant/auth/eid', params From 35c3f0a5bfa41899d724486a4d0170d9b7b5f145 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Fri, 20 Jul 2018 16:46:22 +0300 Subject: [PATCH 18/60] Change Base64 encoding to be url_safe, add crude implementation of a Controller --- .../api/v1/registrant/domains_controller.rb | 41 +++++++++++++++++++ config/routes.rb | 3 +- lib/auth_token/auth_token_creator.rb | 2 +- lib/auth_token/auth_token_decryptor.rb | 4 +- .../lib/auth_token/auth_token_creator_test.rb | 3 +- .../auth_token/auth_token_decryptor_test.rb | 4 +- 6 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 app/controllers/api/v1/registrant/domains_controller.rb diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb new file mode 100644 index 000000000..744692d80 --- /dev/null +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -0,0 +1,41 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_decryptor' + +module Api + module V1 + module Registrant + class DomainsController < ActionController::API + before_filter :authenticate + + def index + registrant = ::Registrant.find_by(ident: current_user.registrant_ident) + unless registrant + render json: Domain.all + else + domains = Domain.where(registrant_id: registrant.id) + render json: domains + end + end + + private + + def bearer_token + pattern = /^Bearer / + header = request.headers['Authorization'] + header.gsub(pattern, '') if header && header.match(pattern) + end + + def authenticate + decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token) + decryptor.decrypt_token + + if decryptor.valid? + sign_in decryptor.user + else + render json: { error: "Not authorized" }, status: 403 + end + end + end + end + end +end diff --git a/config/routes.rb b/config/routes.rb index 2bc965a0f..3ae18a7cd 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -22,7 +22,8 @@ Rails.application.routes.draw do namespace :v1 do namespace :registrant do post 'auth/eid', to: 'auth#eid' - post 'auth/username', to: 'auth#username' + + resources :domains, only: [:index] end end end diff --git a/lib/auth_token/auth_token_creator.rb b/lib/auth_token/auth_token_creator.rb index 2272a3650..0597e0489 100644 --- a/lib/auth_token/auth_token_creator.rb +++ b/lib/auth_token/auth_token_creator.rb @@ -28,7 +28,7 @@ class AuthTokenCreator encryptor.encrypt encryptor.key = key encrypted_bytes = encryptor.update(hashable) + encryptor.final - Base64.encode64(encrypted_bytes) + Base64.urlsafe_encode64(encrypted_bytes) end def token_in_hash diff --git a/lib/auth_token/auth_token_decryptor.rb b/lib/auth_token/auth_token_decryptor.rb index 1f513bece..2af4be0a9 100644 --- a/lib/auth_token/auth_token_decryptor.rb +++ b/lib/auth_token/auth_token_decryptor.rb @@ -18,11 +18,11 @@ class AuthTokenDecryptor decipher.decrypt decipher.key = key - base64_decoded = Base64.decode64(token) + base64_decoded = Base64.urlsafe_decode64(token) plain = decipher.update(base64_decoded) + decipher.final @decrypted_data = JSON.parse(plain, symbolize_names: true) - rescue OpenSSL::Cipher::CipherError + rescue OpenSSL::Cipher::CipherError, ArgumentError false end diff --git a/test/lib/auth_token/auth_token_creator_test.rb b/test/lib/auth_token/auth_token_creator_test.rb index 4fab724c1..9d4cdd2c6 100644 --- a/test/lib/auth_token/auth_token_creator_test.rb +++ b/test/lib/auth_token/auth_token_creator_test.rb @@ -15,6 +15,7 @@ class AuthTokenCreatorTest < ActiveSupport::TestCase def test_hashable_is_constructed_as_expected expected_hashable = { user_ident: 'US-1234', user_username: 'Registrant User', expires_at: '2010-07-05 00:30:00 UTC' }.to_json + assert_equal(expected_hashable, @token_creator.hashable) end @@ -23,7 +24,7 @@ class AuthTokenCreatorTest < ActiveSupport::TestCase encryptor.decrypt encryptor.key = @random_bytes - base64_decoded = Base64.decode64(@token_creator.encrypted_token) + base64_decoded = Base64.urlsafe_decode64(@token_creator.encrypted_token) result = encryptor.update(base64_decoded) + encryptor.final hashable = { user_ident: 'US-1234', user_username: 'Registrant User', diff --git a/test/lib/auth_token/auth_token_decryptor_test.rb b/test/lib/auth_token/auth_token_decryptor_test.rb index d83de7990..fbb18d6d3 100644 --- a/test/lib/auth_token/auth_token_decryptor_test.rb +++ b/test/lib/auth_token/auth_token_decryptor_test.rb @@ -15,7 +15,7 @@ class AuthTokenDecryptorTest < ActiveSupport::TestCase # this token corresponds to: # {:user_ident=>"US-1234", :user_username=>"Registrant User", :expires_at=>"2010-07-05 02:15:00 UTC"} - @access_token = "q27NWIsKD5snWj9vZzJ0RcOYvgocEyu7H9yCaDjfmGi54sogovpBeALMPWTZ\nHMcdFQzSiq6b4cI0p5tO0/5UEOHic2jRzNW7mkhi+bn+Y2W9l9TJV0IdiTj9\nbaf+JvlbyaJh6+/eXIm0tuV5E8Ra9Q==\n" + @access_token = "q27NWIsKD5snWj9vZzJ0RcOYvgocEyu7H9yCaDjfmGi54sogovpBeALMPWTZHMcdFQzSiq6b4cI0p5tO0_5UEOHic2jRzNW7mkhi-bn-Y2Wlnw7jhMpxw6VwJR8QEoDzjkcNxnKBN6OKF4nssa60ZQ==" end def teardown @@ -61,7 +61,7 @@ class AuthTokenDecryptorTest < ActiveSupport::TestCase def test_returns_false_for_non_existing_user # This token was created from an admin user and @key. Decrypted, it corresponds to: # {:user_ident=>nil, :user_username=>"test", :expires_at=>"2010-07-05 00:15:00 UTC"} - other_token = "rMkjgpyRcj2xOnHVwvvQ5RAS0yQepUSrw3XM5BrwM4TMH+h+TBeLve9InC/z\naPneMMnCs0NHQHt1EpH95A2YhX5P3HsyYITRErDmtlzUf21e185q/CUkW5NG\nWa4rar+6\n" + other_token = "rMkjgpyRcj2xOnHVwvvQ5RAS0yQepUSrw3XM5BrwM4TMH-h-TBeLve9InC_zaPneMMnCs0NHQHt1EpH95A2Yhdk6Ge6HQ-4gN5L0THDywCO2vHKGucPxbd6g6wOSaOnR" decryptor = AuthTokenDecryptor.new(other_token, @key) decryptor.decrypt_token From 75119aff2eb148859412f9c6e35ba55ba960c92a Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 23 Jul 2018 12:23:05 +0300 Subject: [PATCH 19/60] Add registrant test class --- test/models/registrant_user_test.rb | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 test/models/registrant_user_test.rb diff --git a/test/models/registrant_user_test.rb b/test/models/registrant_user_test.rb new file mode 100644 index 000000000..112b4dbeb --- /dev/null +++ b/test/models/registrant_user_test.rb @@ -0,0 +1,49 @@ +class RegistrantUserTest < ActiveSupport::TestCase + def setup + super + end + + def teardown + super + end + + def test_find_or_create_by_api_data_creates_a_user + user_data = { + ident: '37710100070', + first_name: 'JOHN', + last_name: 'SMITH' + } + + RegistrantUser.find_or_create_by_api_data(user_data) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_mid_data_creates_a_user + user_data = OpenStruct.new(user_country: 'EE', user_id_code: '37710100070', + user_givenname: 'JOHN', user_surname: 'SMITH') + + RegistrantUser.find_or_create_by_mid_data(user_data) + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_idc_with_legacy_header_creates_a_user + header = '/C=EE/O=ESTEID/OU=authentication/CN=SMITH,JOHN,37710100070/SN=SMITH/GN=JOHN/serialNumber=37710100070' + + RegistrantUser.find_or_create_by_idc_data(header, RegistrantUser::ACCEPTED_ISSUER) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_idc_with_rfc2253_header_creates_a_user + header = 'serialNumber=37710100070,GN=JOHN,SN=SMITH,CN=SMITH\\,JOHN\\,37710100070,OU=authentication,O=ESTEID,C=EE' + + RegistrantUser.find_or_create_by_idc_data(header, RegistrantUser::ACCEPTED_ISSUER) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end +end From f92ece54673bb9d04fbb8ad9ba5ffefcc8656580 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 23 Jul 2018 14:29:16 +0300 Subject: [PATCH 20/60] Refactor common part of the find_or_create_by_x into a private method --- .../api/v1/registrant/auth_controller.rb | 5 +- app/models/registrant_user.rb | 64 +++++++++++-------- test/models/registrant_user_test.rb | 13 ++++ 3 files changed, 53 insertions(+), 29 deletions(-) diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 5de962437..e1bd37b1e 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -26,9 +26,12 @@ module Api private def eid_params - [:ident, :first_name, :last_name].each_with_object(params) do |key, obj| + required_params = [:ident, :first_name, :last_name] + required_params.each_with_object(params) do |key, obj| obj.require(key) end + + params.permit(required_params) end def create_token(user) diff --git a/app/models/registrant_user.rb b/app/models/registrant_user.rb index db851eb6a..da5ddc9f7 100644 --- a/app/models/registrant_user.rb +++ b/app/models/registrant_user.rb @@ -30,48 +30,56 @@ class RegistrantUser < User return false if issuer_organization != ACCEPTED_ISSUER idc_data.force_encoding('UTF-8') + user_data = {} # handling here new and old mode if idc_data.starts_with?("/") - identity_code = idc_data.scan(/serialNumber=(\d+)/).flatten.first - country = idc_data.scan(/^\/C=(.{2})/).flatten.first - first_name = idc_data.scan(%r{/GN=(.+)/serialNumber}).flatten.first - last_name = idc_data.scan(%r{/SN=(.+)/GN}).flatten.first + user_data[:ident] = idc_data.scan(/serialNumber=(\d+)/).flatten.first + user_data[:country_code] = idc_data.scan(/^\/C=(.{2})/).flatten.first + user_data[:first_name] = idc_data.scan(%r{/GN=(.+)/serialNumber}).flatten.first + user_data[:last_name] = idc_data.scan(%r{/SN=(.+)/GN}).flatten.first else parse_str = "," + idc_data - identity_code = parse_str.scan(/,serialNumber=(\d+)/).flatten.first - country = parse_str.scan(/,C=(.{2})/).flatten.first - first_name = parse_str.scan(/,GN=([^,]+)/).flatten.first - last_name = parse_str.scan(/,SN=([^,]+)/).flatten.first + user_data[:ident] = parse_str.scan(/,serialNumber=(\d+)/).flatten.first + user_data[:country_code] = parse_str.scan(/,C=(.{2})/).flatten.first + user_data[:first_name] = parse_str.scan(/,GN=([^,]+)/).flatten.first + user_data[:last_name] = parse_str.scan(/,SN=([^,]+)/).flatten.first end - u = where(registrant_ident: "#{country}-#{identity_code}").first_or_create - u.username = "#{first_name} #{last_name}" - u.save - - u + find_or_create_by_certificate_data(user_data) end - def find_or_create_by_api_data(api_data = {}) - return false unless api_data[:ident] - return false unless api_data[:first_name] - return false unless api_data[:last_name] + def find_or_create_by_api_data(user_data = {}) + return false unless user_data[:ident] + return false unless user_data[:first_name] + return false unless user_data[:last_name] - estonian_ident = "EE-#{api_data[:ident]}" + user_data.each { |k, v| v.upcase! if v.is_a?(String) } + user_data[:country_code] ||= "EE" - user = find_or_create_by(registrant_ident: estonian_ident) - user.username = "#{api_data[:first_name]} #{api_data[:last_name]}" + find_or_create_by_certificate_data(user_data) + end + + def find_or_create_by_mid_data(response) + user_data = { first_name: response.user_givenname, last_name: response.user_surname, + ident: response.user_id_code, country_code: response.user_country } + + find_or_create_by_certificate_data(user_data) + end + + private + + def find_or_create_by_certificate_data(opts = {}) + return unless opts[:first_name] + return unless opts[:last_name] + return unless opts[:ident] + return unless opts[:country_code] + + user = find_or_create_by(registrant_ident: "#{opts[:country_code]}-#{opts[:ident]}") + user.username = "#{opts[:first_name]} #{opts[:last_name]}" user.save user end - - def find_or_create_by_mid_data(response) - u = where(registrant_ident: "#{response.user_country}-#{response.user_id_code}").first_or_create - u.username = "#{response.user_givenname} #{response.user_surname}" - u.save - - u - end end end diff --git a/test/models/registrant_user_test.rb b/test/models/registrant_user_test.rb index 112b4dbeb..86ab5591a 100644 --- a/test/models/registrant_user_test.rb +++ b/test/models/registrant_user_test.rb @@ -20,6 +20,19 @@ class RegistrantUserTest < ActiveSupport::TestCase assert_equal('JOHN SMITH', user.username) end + def test_find_or_create_by_api_data_creates_a_user_after_upcasing_input + user_data = { + ident: '37710100070', + first_name: 'John', + last_name: 'Smith' + } + + RegistrantUser.find_or_create_by_api_data(user_data) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + def test_find_or_create_by_mid_data_creates_a_user user_data = OpenStruct.new(user_country: 'EE', user_id_code: '37710100070', user_givenname: 'JOHN', user_surname: 'SMITH') From 65676ae63721f8d38e419aeb4f0aafc4512cc3bf Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 23 Jul 2018 15:00:37 +0300 Subject: [PATCH 21/60] Rename private method --- app/models/registrant_user.rb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/app/models/registrant_user.rb b/app/models/registrant_user.rb index da5ddc9f7..850675f5e 100644 --- a/app/models/registrant_user.rb +++ b/app/models/registrant_user.rb @@ -46,7 +46,7 @@ class RegistrantUser < User user_data[:last_name] = parse_str.scan(/,SN=([^,]+)/).flatten.first end - find_or_create_by_certificate_data(user_data) + find_or_create_by_user_data(user_data) end def find_or_create_by_api_data(user_data = {}) @@ -57,26 +57,26 @@ class RegistrantUser < User user_data.each { |k, v| v.upcase! if v.is_a?(String) } user_data[:country_code] ||= "EE" - find_or_create_by_certificate_data(user_data) + find_or_create_by_user_data(user_data) end def find_or_create_by_mid_data(response) user_data = { first_name: response.user_givenname, last_name: response.user_surname, ident: response.user_id_code, country_code: response.user_country } - find_or_create_by_certificate_data(user_data) + find_or_create_by_user_data(user_data) end private - def find_or_create_by_certificate_data(opts = {}) - return unless opts[:first_name] - return unless opts[:last_name] - return unless opts[:ident] - return unless opts[:country_code] + def find_or_create_by_user_data(user_data = {}) + return unless user_data[:first_name] + return unless user_data[:last_name] + return unless user_data[:ident] + return unless user_data[:country_code] - user = find_or_create_by(registrant_ident: "#{opts[:country_code]}-#{opts[:ident]}") - user.username = "#{opts[:first_name]} #{opts[:last_name]}" + user = find_or_create_by(registrant_ident: "#{user_data[:country_code]}-#{user_data[:ident]}") + user.username = "#{user_data[:first_name]} #{user_data[:last_name]}" user.save user From 8f234a5852ffb29dd702a1f5fda70a9b48f9d96f Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 23 Jul 2018 16:23:56 +0300 Subject: [PATCH 22/60] Create base controller class --- .../api/v1/registrant/base_controller.rb | 31 +++++++++++++++++++ .../api/v1/registrant/domains_controller.rb | 23 +------------- lib/auth_token/auth_token_decryptor.rb | 2 +- .../auth_token/auth_token_decryptor_test.rb | 5 +++ .../registrant/registrant_api_domains_test.rb | 29 +++++++++++++++++ 5 files changed, 67 insertions(+), 23 deletions(-) create mode 100644 app/controllers/api/v1/registrant/base_controller.rb create mode 100644 test/system/api/registrant/registrant_api_domains_test.rb diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb new file mode 100644 index 000000000..5b01f94b5 --- /dev/null +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -0,0 +1,31 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_decryptor' + +module Api + module V1 + module Registrant + class BaseController < ActionController::API + before_action :authenticate + + private + + def bearer_token + pattern = /^Bearer / + header = request.headers['Authorization'] + header.gsub(pattern, '') if header && header.match(pattern) + end + + def authenticate + decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token) + decryptor.decrypt_token + + if decryptor.valid? + sign_in decryptor.user + else + render json: { error: 'Not authorized' }, status: 403 + end + end + end + end + end +end diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index 744692d80..cc53e6772 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -4,9 +4,7 @@ require 'auth_token/auth_token_decryptor' module Api module V1 module Registrant - class DomainsController < ActionController::API - before_filter :authenticate - + class DomainsController < BaseController def index registrant = ::Registrant.find_by(ident: current_user.registrant_ident) unless registrant @@ -16,25 +14,6 @@ module Api render json: domains end end - - private - - def bearer_token - pattern = /^Bearer / - header = request.headers['Authorization'] - header.gsub(pattern, '') if header && header.match(pattern) - end - - def authenticate - decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token) - decryptor.decrypt_token - - if decryptor.valid? - sign_in decryptor.user - else - render json: { error: "Not authorized" }, status: 403 - end - end end end end diff --git a/lib/auth_token/auth_token_decryptor.rb b/lib/auth_token/auth_token_decryptor.rb index 2af4be0a9..61146aa4d 100644 --- a/lib/auth_token/auth_token_decryptor.rb +++ b/lib/auth_token/auth_token_decryptor.rb @@ -18,7 +18,7 @@ class AuthTokenDecryptor decipher.decrypt decipher.key = key - base64_decoded = Base64.urlsafe_decode64(token) + base64_decoded = Base64.urlsafe_decode64(token.to_s) plain = decipher.update(base64_decoded) + decipher.final @decrypted_data = JSON.parse(plain, symbolize_names: true) diff --git a/test/lib/auth_token/auth_token_decryptor_test.rb b/test/lib/auth_token/auth_token_decryptor_test.rb index fbb18d6d3..49ca2b820 100644 --- a/test/lib/auth_token/auth_token_decryptor_test.rb +++ b/test/lib/auth_token/auth_token_decryptor_test.rb @@ -35,6 +35,11 @@ class AuthTokenDecryptorTest < ActiveSupport::TestCase refute(faulty_decryptor.decrypt_token) end + def test_decrypt_token_return_false_when_token_is_nil + faulty_decryptor = AuthTokenDecryptor.new(nil, @key) + refute(faulty_decryptor.decrypt_token) + end + def test_valid_returns_true_for_valid_token decryptor = AuthTokenDecryptor.new(@access_token, @key) decryptor.decrypt_token diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/system/api/registrant/registrant_api_domains_test.rb new file mode 100644 index 000000000..e7abe2cae --- /dev/null +++ b/test/system/api/registrant/registrant_api_domains_test.rb @@ -0,0 +1,29 @@ +require 'test_helper' +require 'auth_token/auth_token_creator' + +class RegistrantApiDomainsTest < ApplicationSystemTestCase + def setup + super + + @user = users(:registrant) + @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } + end + + def test_root_returns_domain_list + get '/api/v1/registrant/domains', {}, @auth_headers + assert_equal(200, response.status) + end + + def test_root_returns_403_without_authorization + get '/api/v1/registrant/domains', {}, {} + assert_equal(403, response.status) + end + + private + + def auth_token + token_creator = AuthTokenCreator.create_with_defaults(@user) + hash = token_creator.token_in_hash + "Bearer #{hash[:access_token]}" + end +end From 42004f933f9bda6f5bfe119a3f6ae50b76ab9ba2 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 24 Jul 2018 11:33:51 +0300 Subject: [PATCH 23/60] Add IP block on authentication via EID Also, correct mistakenly used 403 error code. Update aplication-example.yml to include new functionality. --- .../api/v1/registrant/auth_controller.rb | 10 ++++++++++ .../api/v1/registrant/base_controller.rb | 9 ++++++++- .../api/v1/registrant/domains_controller.rb | 6 +++--- config/application-example.yml | 2 ++ .../registrant_api_authentication_test.rb | 14 ++++++++++++++ .../api/registrant/registrant_api_domains_test.rb | 7 +++++-- 6 files changed, 42 insertions(+), 6 deletions(-) diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index e1bd37b1e..2bbaad973 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -5,6 +5,8 @@ module Api module V1 module Registrant class AuthController < ActionController::API + before_action :check_ip_whitelist + rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception| error = {} error[parameter_missing_exception.param] = ['parameter is required'] @@ -39,6 +41,14 @@ module Api hash = token_creator.token_in_hash hash end + + def check_ip_whitelist + allowed_ips = ENV['registrant_api_auth_allowed_ips'].to_s.split(',').map(&:strip) + + unless allowed_ips.include?(request.ip) || Rails.env.development? + render json: { error: 'Not authorized' }, status: 401 + end + end end end end diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb index 5b01f94b5..f18fd1eb2 100644 --- a/app/controllers/api/v1/registrant/base_controller.rb +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -7,6 +7,13 @@ module Api class BaseController < ActionController::API before_action :authenticate + rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception| + error = {} + error[parameter_missing_exception.param] = ['parameter is required'] + response = { errors: [error] } + render json: response, status: :unprocessable_entity + end + private def bearer_token @@ -22,7 +29,7 @@ module Api if decryptor.valid? sign_in decryptor.user else - render json: { error: 'Not authorized' }, status: 403 + render json: { error: 'Not authorized' }, status: 401 end end end diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index cc53e6772..fdfc6872c 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -7,11 +7,11 @@ module Api class DomainsController < BaseController def index registrant = ::Registrant.find_by(ident: current_user.registrant_ident) - unless registrant - render json: Domain.all - else + if registrant domains = Domain.where(registrant_id: registrant.id) render json: domains + else + render json: [] end end end diff --git a/config/application-example.yml b/config/application-example.yml index 7785aafb5..7a69aa9e2 100644 --- a/config/application-example.yml +++ b/config/application-example.yml @@ -96,6 +96,8 @@ arireg_host: 'http://demo-ariregxml.rik.ee:81/' sk_digi_doc_service_endpoint: 'https://tsp.demo.sk.ee' sk_digi_doc_service_name: 'Testimine' +# Registrant API +registrant_api_auth_allowed_ips: '127.0.0.1,0.0.0.0' #ips, separated with commas # # MISC diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb index 72da06fff..94693ddd5 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -33,6 +33,20 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase end end + def test_request_returns_401_from_a_not_whitelisted_ip + params = { foo: :bar, test: :test } + @original_whitelist_ip = ENV['registrant_api_auth_allowed_ips'] + ENV['registrant_api_auth_allowed_ips'] = '1.2.3.4' + + post '/api/v1/registrant/auth/eid', params + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({error: 'Not authorized'}, json_body) + + ENV['registrant_api_auth_allowed_ips'] = @original_whitelist_ip + end + def test_request_documented_parameters_are_required params = { foo: :bar, test: :test } diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/system/api/registrant/registrant_api_domains_test.rb index e7abe2cae..da5813518 100644 --- a/test/system/api/registrant/registrant_api_domains_test.rb +++ b/test/system/api/registrant/registrant_api_domains_test.rb @@ -14,9 +14,12 @@ class RegistrantApiDomainsTest < ApplicationSystemTestCase assert_equal(200, response.status) end - def test_root_returns_403_without_authorization + def test_root_returns_401_without_authorization get '/api/v1/registrant/domains', {}, {} - assert_equal(403, response.status) + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({error: 'Not authorized'}, json_body) end private From 06f5eb10d4b193e22b831d7e8f8208fec9048a3e Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 24 Jul 2018 11:54:37 +0300 Subject: [PATCH 24/60] Use inflector rule to acronym Api to API --- app/api/repp/api.rb | 2 +- app/controllers/admin/api_users_controller.rb | 10 +++++----- app/controllers/admin/certificates_controller.rb | 6 +++--- app/controllers/api/v1/registrant/auth_controller.rb | 2 +- app/controllers/api/v1/registrant/base_controller.rb | 2 +- .../api/v1/registrant/domains_controller.rb | 2 +- app/controllers/epp/sessions_controller.rb | 2 +- app/controllers/registrant/sessions_controller.rb | 2 +- app/controllers/registrar/current_user_controller.rb | 2 +- app/controllers/registrar/sessions_controller.rb | 8 ++++---- app/models/ability.rb | 4 ++-- app/models/api_user.rb | 2 +- app/models/concerns/versions.rb | 2 +- app/models/epp/domain.rb | 2 +- app/views/admin/api_users/_form.haml | 2 +- app/views/admin/registrars/_users.html.erb | 4 ++-- config/initializers/inflections.rb | 1 + lib/tasks/import.rake | 10 +++++----- spec/factories/api_user.rb | 2 +- spec/models/api_user_spec.rb | 6 +++--- spec/models/domain_spec.rb | 4 ++-- spec/presenters/user_presenter_spec.rb | 2 +- test/fixtures/users.yml | 4 ++-- .../registrant/registrant_api_authentication_test.rb | 2 +- .../api/registrant/registrant_api_domains_test.rb | 2 +- 25 files changed, 44 insertions(+), 43 deletions(-) diff --git a/app/api/repp/api.rb b/app/api/repp/api.rb index 7858cd625..a726d226c 100644 --- a/app/api/repp/api.rb +++ b/app/api/repp/api.rb @@ -4,7 +4,7 @@ module Repp prefix :repp http_basic do |username, password| - @current_user ||= ApiUser.find_by(username: username, password: password) + @current_user ||= APIUser.find_by(username: username, password: password) if @current_user true else diff --git a/app/controllers/admin/api_users_controller.rb b/app/controllers/admin/api_users_controller.rb index 84344c2e9..e7ac175e8 100644 --- a/app/controllers/admin/api_users_controller.rb +++ b/app/controllers/admin/api_users_controller.rb @@ -1,20 +1,20 @@ module Admin - class ApiUsersController < BaseController + class APIUsersController < BaseController load_and_authorize_resource before_action :set_api_user, only: [:show, :edit, :update, :destroy] def index - @q = ApiUser.includes(:registrar).search(params[:q]) + @q = APIUser.includes(:registrar).search(params[:q]) @api_users = @q.result.page(params[:page]) end def new @registrar = Registrar.find_by(id: params[:registrar_id]) - @api_user = ApiUser.new(registrar: @registrar) + @api_user = APIUser.new(registrar: @registrar) end def create - @api_user = ApiUser.new(api_user_params) + @api_user = APIUser.new(api_user_params) if @api_user.save flash[:notice] = I18n.t('record_created') @@ -55,7 +55,7 @@ module Admin private def set_api_user - @api_user = ApiUser.find(params[:id]) + @api_user = APIUser.find(params[:id]) end def api_user_params diff --git a/app/controllers/admin/certificates_controller.rb b/app/controllers/admin/certificates_controller.rb index a08654db3..f25651c39 100644 --- a/app/controllers/admin/certificates_controller.rb +++ b/app/controllers/admin/certificates_controller.rb @@ -7,12 +7,12 @@ module Admin end def new - @api_user = ApiUser.find(params[:api_user_id]) + @api_user = APIUser.find(params[:api_user_id]) @certificate = Certificate.new(api_user: @api_user) end def create - @api_user = ApiUser.find(params[:api_user_id]) + @api_user = APIUser.find(params[:api_user_id]) crt = certificate_params[:crt].open.read if certificate_params[:crt] csr = certificate_params[:csr].open.read if certificate_params[:csr] @@ -73,7 +73,7 @@ module Admin end def set_api_user - @api_user = ApiUser.find(params[:api_user_id]) + @api_user = APIUser.find(params[:api_user_id]) end def certificate_params diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 2bbaad973..656d1b4eb 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -1,7 +1,7 @@ require 'rails5_api_controller_backport' require 'auth_token/auth_token_creator' -module Api +module API module V1 module Registrant class AuthController < ActionController::API diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb index f18fd1eb2..01101bfb2 100644 --- a/app/controllers/api/v1/registrant/base_controller.rb +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -1,7 +1,7 @@ require 'rails5_api_controller_backport' require 'auth_token/auth_token_decryptor' -module Api +module API module V1 module Registrant class BaseController < ActionController::API diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index fdfc6872c..308f81709 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -1,7 +1,7 @@ require 'rails5_api_controller_backport' require 'auth_token/auth_token_decryptor' -module Api +module API module V1 module Registrant class DomainsController < BaseController diff --git a/app/controllers/epp/sessions_controller.rb b/app/controllers/epp/sessions_controller.rb index e3e9f3114..f463f4365 100644 --- a/app/controllers/epp/sessions_controller.rb +++ b/app/controllers/epp/sessions_controller.rb @@ -7,7 +7,7 @@ class Epp::SessionsController < EppController def login success = true - @api_user = ApiUser.find_by(login_params) + @api_user = APIUser.find_by(login_params) webclient_request = ENV['webclient_ips'].split(',').map(&:strip).include?(request.ip) if webclient_request && !Rails.env.test? && !Rails.env.development? diff --git a/app/controllers/registrant/sessions_controller.rb b/app/controllers/registrant/sessions_controller.rb index 80a23eb0a..cb51a94f5 100644 --- a/app/controllers/registrant/sessions_controller.rb +++ b/app/controllers/registrant/sessions_controller.rb @@ -95,6 +95,6 @@ class Registrant::SessionsController < Devise::SessionsController def find_user_by_idc(idc) return User.new unless idc - ApiUser.find_by(identity_code: idc) || User.new + APIUser.find_by(identity_code: idc) || User.new end end diff --git a/app/controllers/registrar/current_user_controller.rb b/app/controllers/registrar/current_user_controller.rb index 266e4b915..3f969ecb2 100644 --- a/app/controllers/registrar/current_user_controller.rb +++ b/app/controllers/registrar/current_user_controller.rb @@ -12,7 +12,7 @@ class Registrar private def new_user - @new_user ||= ApiUser.find(params[:new_user_id]) + @new_user ||= APIUser.find(params[:new_user_id]) end end end diff --git a/app/controllers/registrar/sessions_controller.rb b/app/controllers/registrar/sessions_controller.rb index 11841481d..c369051e6 100644 --- a/app/controllers/registrar/sessions_controller.rb +++ b/app/controllers/registrar/sessions_controller.rb @@ -26,7 +26,7 @@ class Registrar @depp_user.errors.add(:base, :webserver_client_cert_directive_should_be_required) end - @api_user = ApiUser.find_by(username: params[:depp_user][:tag], password: params[:depp_user][:password]) + @api_user = APIUser.find_by(username: params[:depp_user][:tag], password: params[:depp_user][:password]) unless @api_user @depp_user.errors.add(:base, t(:no_such_user)) @@ -53,7 +53,7 @@ class Registrar end def id - @user = ApiUser.find_by_idc_data_and_allowed(request.env['SSL_CLIENT_S_DN'], request.ip) + @user = APIUser.find_by_idc_data_and_allowed(request.env['SSL_CLIENT_S_DN'], request.ip) if @user sign_in(@user, event: :authentication) @@ -150,12 +150,12 @@ class Registrar def find_user_by_idc(idc) return User.new unless idc - ApiUser.find_by(identity_code: idc) || User.new + APIUser.find_by(identity_code: idc) || User.new end def find_user_by_idc_and_allowed(idc) return User.new unless idc - possible_users = ApiUser.where(identity_code: idc) || User.new + possible_users = APIUser.where(identity_code: idc) || User.new possible_users.each do |selected_user| if selected_user.registrar.white_ips.registrar_area.include_ip?(request.ip) return selected_user diff --git a/app/models/ability.rb b/app/models/ability.rb index 97086110b..1bc4ae386 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -10,7 +10,7 @@ class Ability case @user.class.to_s when 'AdminUser' @user.roles&.each { |role| send(role) } - when 'ApiUser' + when 'APIUser' @user.roles&.each { |role| send(role) } when 'RegistrantUser' static_registrant @@ -94,7 +94,7 @@ class Ability can :manage, ContactVersion can :manage, Billing::Price can :manage, User - can :manage, ApiUser + can :manage, APIUser can :manage, AdminUser can :manage, Certificate can :manage, Keyrelay diff --git a/app/models/api_user.rb b/app/models/api_user.rb index ce32c4045..bee04a954 100644 --- a/app/models/api_user.rb +++ b/app/models/api_user.rb @@ -1,6 +1,6 @@ require 'open3' -class ApiUser < User +class APIUser < User include EppErrors def epp_code_map diff --git a/app/models/concerns/versions.rb b/app/models/concerns/versions.rb index 5e2bad90c..50ea935d2 100644 --- a/app/models/concerns/versions.rb +++ b/app/models/concerns/versions.rb @@ -34,7 +34,7 @@ module Versions end def user_from_id_role_username(str) - user = ApiUser.find_by(id: $1) if str =~ /^(\d+)-(ApiUser:|api-)/ + user = APIUser.find_by(id: $1) if str =~ /^(\d+)-(APIUser:|api-)/ unless user.present? user = AdminUser.find_by(id: $1) if str =~ /^(\d+)-AdminUser:/ unless user.present? diff --git a/app/models/epp/domain.rb b/app/models/epp/domain.rb index 749f5310c..49049665c 100644 --- a/app/models/epp/domain.rb +++ b/app/models/epp/domain.rb @@ -490,7 +490,7 @@ class Epp::Domain < Domain def apply_pending_update! preclean_pendings - user = ApiUser.find(pending_json['current_user_id']) + user = APIUser.find(pending_json['current_user_id']) frame = Nokogiri::XML(pending_json['frame']) self.statuses.delete(DomainStatus::PENDING_UPDATE) diff --git a/app/views/admin/api_users/_form.haml b/app/views/admin/api_users/_form.haml index 9a26b9fc8..722b98d0d 100644 --- a/app/views/admin/api_users/_form.haml +++ b/app/views/admin/api_users/_form.haml @@ -38,7 +38,7 @@ = f.label :role, nil, class: 'required' .col-md-7 = select_tag 'api_user[roles][]', - options_for_select(ApiUser::ROLES.map {|x| [x, x] }, @api_user.roles.try(:first)), + options_for_select(APIUser::ROLES.map {|x| [x, x] }, @api_user.roles.try(:first)), class: 'form-control selectize' .checkbox %label{for: 'api_user_active'} diff --git a/app/views/admin/registrars/_users.html.erb b/app/views/admin/registrars/_users.html.erb index f182e4615..d85eaaf36 100644 --- a/app/views/admin/registrars/_users.html.erb +++ b/app/views/admin/registrars/_users.html.erb @@ -6,8 +6,8 @@ - - + + diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb index b4eccb451..b4a84b01d 100644 --- a/config/initializers/inflections.rb +++ b/config/initializers/inflections.rb @@ -12,4 +12,5 @@ ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'DNS' + inflect.acronym 'API' end diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake index 2fa67a827..1d83ec5ef 100644 --- a/lib/tasks/import.rake +++ b/lib/tasks/import.rake @@ -131,7 +131,7 @@ namespace :import do ips = [] temp = [] - existing_ids = ApiUser.pluck(:legacy_id) + existing_ids = APIUser.pluck(:legacy_id) existing_ips = WhiteIp.pluck(:ipv4) Legacy::Registrar.all.each do |x| @@ -143,7 +143,7 @@ namespace :import do if y.try(:cert) != 'pki' if y.try(:cert) == 'idkaart' - id_users << ApiUser.new({ + id_users << APIUser.new({ username: y.try(:password) ? y.try(:password) : y.try(:password), password: ('a'..'z').to_a.shuffle.first(8).join, identity_code: y.try(:password) ? y.try(:password) : y.try(:password), @@ -152,7 +152,7 @@ namespace :import do legacy_id: y.try(:id) }) else - temp << ApiUser.new({ + temp << APIUser.new({ username: x.handle.try(:strip), password: y.try(:password) ? y.try(:password) : ('a'..'z').to_a.shuffle.first(8).join, registrar_id: Registrar.find_by(legacy_id: x.try(:id)).try(:id), @@ -181,8 +181,8 @@ namespace :import do end end - ApiUser.import id_users, validate: false - ApiUser.import users, validate: false + APIUser.import id_users, validate: false + APIUser.import users, validate: false if ips WhiteIp.import ips, validate: false diff --git a/spec/factories/api_user.rb b/spec/factories/api_user.rb index a3f9623b6..31355f141 100644 --- a/spec/factories/api_user.rb +++ b/spec/factories/api_user.rb @@ -1,7 +1,7 @@ FactoryBot.define do factory :api_user do sequence(:username) { |n| "test#{n}" } - password 'a' * ApiUser.min_password_length + password 'a' * APIUser.min_password_length roles ['super'] registrar diff --git a/spec/models/api_user_spec.rb b/spec/models/api_user_spec.rb index 89feeac6d..b710a05c9 100644 --- a/spec/models/api_user_spec.rb +++ b/spec/models/api_user_spec.rb @@ -1,16 +1,16 @@ require 'rails_helper' -RSpec.describe ApiUser do +RSpec.describe APIUser do context 'with invalid attribute' do before do - @api_user = ApiUser.new + @api_user = APIUser.new end it 'should not be valid' do @api_user.valid? @api_user.errors.full_messages.should match_array([ "Password Password is missing", - "Password is too short (minimum is #{ApiUser.min_password_length} characters)", + "Password is too short (minimum is #{APIUser.min_password_length} characters)", "Registrar Registrar is missing", "Username Username is missing", "Roles is missing" diff --git a/spec/models/domain_spec.rb b/spec/models/domain_spec.rb index 6b282d651..007b1e3de 100644 --- a/spec/models/domain_spec.rb +++ b/spec/models/domain_spec.rb @@ -316,10 +316,10 @@ RSpec.describe Domain do @api_user = create(:api_user) @user.id.should == 1 @api_user.id.should == 2 - ::PaperTrail.whodunnit = '2-ApiUser: testuser' + ::PaperTrail.whodunnit = '2-APIUser: testuser' @domain = create(:domain) - @domain.creator_str.should == '2-ApiUser: testuser' + @domain.creator_str.should == '2-APIUser: testuser' @domain.creator.should == @api_user @domain.creator.should_not == @user diff --git a/spec/presenters/user_presenter_spec.rb b/spec/presenters/user_presenter_spec.rb index ba9e1673f..c0cff114b 100644 --- a/spec/presenters/user_presenter_spec.rb +++ b/spec/presenters/user_presenter_spec.rb @@ -4,7 +4,7 @@ RSpec.describe UserPresenter do let(:presenter) { described_class.new(user: user, view: view) } describe '#login_with_role' do - let(:user) { instance_double(ApiUser, + let(:user) { instance_double(APIUser, login: 'login', roles: %w[role], registrar_name: 'registrar') } diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml index 5fd2dc925..9d3001959 100644 --- a/test/fixtures/users.yml +++ b/test/fixtures/users.yml @@ -1,7 +1,7 @@ api_bestnames: username: test_bestnames password: testtest - type: ApiUser + type: APIUser registrar: bestnames active: true roles: @@ -10,7 +10,7 @@ api_bestnames: api_goodnames: username: test_goodnames password: testtest - type: ApiUser + type: APIUser registrar: goodnames active: true roles: diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb index 94693ddd5..9ed518caa 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrantApiAuthenticationTest < ApplicationSystemTestCase +class RegistrantAPIAuthenticationTest < ApplicationSystemTestCase def setup super diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/system/api/registrant/registrant_api_domains_test.rb index da5813518..ab08b4ba2 100644 --- a/test/system/api/registrant/registrant_api_domains_test.rb +++ b/test/system/api/registrant/registrant_api_domains_test.rb @@ -1,7 +1,7 @@ require 'test_helper' require 'auth_token/auth_token_creator' -class RegistrantApiDomainsTest < ApplicationSystemTestCase +class RegistrantAPIDomainsTest < ApplicationSystemTestCase def setup super From 90b2455032d783acee4f87dca3f16850e70d80d1 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 24 Jul 2018 12:18:38 +0300 Subject: [PATCH 25/60] Fix codeclimate issues --- app/controllers/api/v1/registrant/auth_controller.rb | 9 ++++----- app/controllers/api/v1/registrant/base_controller.rb | 4 ++-- app/models/registrant_user.rb | 4 ++-- lib/auth_token/auth_token_creator.rb | 8 ++++---- lib/auth_token/auth_token_decryptor.rb | 2 +- 5 files changed, 13 insertions(+), 14 deletions(-) diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 656d1b4eb..0e014da02 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -21,14 +21,14 @@ module API if token render json: token else - render json: { error: 'Cannot create generate session token'} + render json: { error: 'Cannot create generate session token' } end end private def eid_params - required_params = [:ident, :first_name, :last_name] + required_params = %i[ident first_name last_name] required_params.each_with_object(params) do |key, obj| obj.require(key) end @@ -44,10 +44,9 @@ module API def check_ip_whitelist allowed_ips = ENV['registrant_api_auth_allowed_ips'].to_s.split(',').map(&:strip) + return if allowed_ips.include?(request.ip) || Rails.env.development? - unless allowed_ips.include?(request.ip) || Rails.env.development? - render json: { error: 'Not authorized' }, status: 401 - end + render json: { error: 'Not authorized' }, status: :unauthorized end end end diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb index 01101bfb2..99ff9d90b 100644 --- a/app/controllers/api/v1/registrant/base_controller.rb +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -19,7 +19,7 @@ module API def bearer_token pattern = /^Bearer / header = request.headers['Authorization'] - header.gsub(pattern, '') if header && header.match(pattern) + header.gsub(pattern, '') if header&.match(pattern) end def authenticate @@ -29,7 +29,7 @@ module API if decryptor.valid? sign_in decryptor.user else - render json: { error: 'Not authorized' }, status: 401 + render json: { error: 'Not authorized' }, status: :unauthorized end end end diff --git a/app/models/registrant_user.rb b/app/models/registrant_user.rb index 850675f5e..889f2ca4c 100644 --- a/app/models/registrant_user.rb +++ b/app/models/registrant_user.rb @@ -54,8 +54,8 @@ class RegistrantUser < User return false unless user_data[:first_name] return false unless user_data[:last_name] - user_data.each { |k, v| v.upcase! if v.is_a?(String) } - user_data[:country_code] ||= "EE" + user_data.each_value { |v| v.upcase! if v.is_a?(String) } + user_data[:country_code] ||= 'EE' find_or_create_by_user_data(user_data) end diff --git a/lib/auth_token/auth_token_creator.rb b/lib/auth_token/auth_token_creator.rb index 0597e0489..9fff8e5cd 100644 --- a/lib/auth_token/auth_token_creator.rb +++ b/lib/auth_token/auth_token_creator.rb @@ -6,20 +6,20 @@ class AuthTokenCreator attr_reader :expires_at def self.create_with_defaults(user) - self.new(user, Rails.application.config.secret_key_base, Time.now + DEFAULT_VALIDITY) + new(user, Rails.application.config.secret_key_base, Time.now + DEFAULT_VALIDITY) end def initialize(user, key, expires_at) @user = user @key = key - @expires_at = expires_at.utc.strftime("%F %T %Z") + @expires_at = expires_at.utc.strftime('%F %T %Z') end def hashable { user_ident: user.registrant_ident, user_username: user.username, - expires_at: expires_at + expires_at: expires_at, }.to_json end @@ -35,7 +35,7 @@ class AuthTokenCreator { access_token: encrypted_token, expires_at: expires_at, - type: 'Bearer' + type: 'Bearer', } end end diff --git a/lib/auth_token/auth_token_decryptor.rb b/lib/auth_token/auth_token_decryptor.rb index 61146aa4d..be6bd99cd 100644 --- a/lib/auth_token/auth_token_decryptor.rb +++ b/lib/auth_token/auth_token_decryptor.rb @@ -5,7 +5,7 @@ class AuthTokenDecryptor attr_reader :user def self.create_with_defaults(token) - self.new(token, Rails.application.config.secret_key_base) + new(token, Rails.application.config.secret_key_base) end def initialize(token, key) From aac76b333cbe598cccf33071cacbcc7fb7bf9b34 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 24 Jul 2018 12:53:51 +0300 Subject: [PATCH 26/60] Revert "Use inflector rule to acronym Api to API" This reverts commit 06f5eb10d4b193e22b831d7e8f8208fec9048a3e. --- app/api/repp/api.rb | 2 +- app/controllers/admin/api_users_controller.rb | 10 +++++----- app/controllers/admin/certificates_controller.rb | 6 +++--- app/controllers/api/v1/registrant/auth_controller.rb | 2 +- app/controllers/api/v1/registrant/base_controller.rb | 2 +- .../api/v1/registrant/domains_controller.rb | 2 +- app/controllers/epp/sessions_controller.rb | 2 +- app/controllers/registrant/sessions_controller.rb | 2 +- app/controllers/registrar/current_user_controller.rb | 2 +- app/controllers/registrar/sessions_controller.rb | 8 ++++---- app/models/ability.rb | 4 ++-- app/models/api_user.rb | 2 +- app/models/concerns/versions.rb | 2 +- app/models/epp/domain.rb | 2 +- app/views/admin/api_users/_form.haml | 2 +- app/views/admin/registrars/_users.html.erb | 4 ++-- config/initializers/inflections.rb | 1 - lib/tasks/import.rake | 10 +++++----- spec/factories/api_user.rb | 2 +- spec/models/api_user_spec.rb | 6 +++--- spec/models/domain_spec.rb | 4 ++-- spec/presenters/user_presenter_spec.rb | 2 +- test/fixtures/users.yml | 4 ++-- .../registrant/registrant_api_authentication_test.rb | 2 +- .../api/registrant/registrant_api_domains_test.rb | 2 +- 25 files changed, 43 insertions(+), 44 deletions(-) diff --git a/app/api/repp/api.rb b/app/api/repp/api.rb index a726d226c..7858cd625 100644 --- a/app/api/repp/api.rb +++ b/app/api/repp/api.rb @@ -4,7 +4,7 @@ module Repp prefix :repp http_basic do |username, password| - @current_user ||= APIUser.find_by(username: username, password: password) + @current_user ||= ApiUser.find_by(username: username, password: password) if @current_user true else diff --git a/app/controllers/admin/api_users_controller.rb b/app/controllers/admin/api_users_controller.rb index e7ac175e8..84344c2e9 100644 --- a/app/controllers/admin/api_users_controller.rb +++ b/app/controllers/admin/api_users_controller.rb @@ -1,20 +1,20 @@ module Admin - class APIUsersController < BaseController + class ApiUsersController < BaseController load_and_authorize_resource before_action :set_api_user, only: [:show, :edit, :update, :destroy] def index - @q = APIUser.includes(:registrar).search(params[:q]) + @q = ApiUser.includes(:registrar).search(params[:q]) @api_users = @q.result.page(params[:page]) end def new @registrar = Registrar.find_by(id: params[:registrar_id]) - @api_user = APIUser.new(registrar: @registrar) + @api_user = ApiUser.new(registrar: @registrar) end def create - @api_user = APIUser.new(api_user_params) + @api_user = ApiUser.new(api_user_params) if @api_user.save flash[:notice] = I18n.t('record_created') @@ -55,7 +55,7 @@ module Admin private def set_api_user - @api_user = APIUser.find(params[:id]) + @api_user = ApiUser.find(params[:id]) end def api_user_params diff --git a/app/controllers/admin/certificates_controller.rb b/app/controllers/admin/certificates_controller.rb index f25651c39..a08654db3 100644 --- a/app/controllers/admin/certificates_controller.rb +++ b/app/controllers/admin/certificates_controller.rb @@ -7,12 +7,12 @@ module Admin end def new - @api_user = APIUser.find(params[:api_user_id]) + @api_user = ApiUser.find(params[:api_user_id]) @certificate = Certificate.new(api_user: @api_user) end def create - @api_user = APIUser.find(params[:api_user_id]) + @api_user = ApiUser.find(params[:api_user_id]) crt = certificate_params[:crt].open.read if certificate_params[:crt] csr = certificate_params[:csr].open.read if certificate_params[:csr] @@ -73,7 +73,7 @@ module Admin end def set_api_user - @api_user = APIUser.find(params[:api_user_id]) + @api_user = ApiUser.find(params[:api_user_id]) end def certificate_params diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 0e014da02..7ba0e9199 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -1,7 +1,7 @@ require 'rails5_api_controller_backport' require 'auth_token/auth_token_creator' -module API +module Api module V1 module Registrant class AuthController < ActionController::API diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb index 99ff9d90b..510f16745 100644 --- a/app/controllers/api/v1/registrant/base_controller.rb +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -1,7 +1,7 @@ require 'rails5_api_controller_backport' require 'auth_token/auth_token_decryptor' -module API +module Api module V1 module Registrant class BaseController < ActionController::API diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index 308f81709..fdfc6872c 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -1,7 +1,7 @@ require 'rails5_api_controller_backport' require 'auth_token/auth_token_decryptor' -module API +module Api module V1 module Registrant class DomainsController < BaseController diff --git a/app/controllers/epp/sessions_controller.rb b/app/controllers/epp/sessions_controller.rb index f463f4365..e3e9f3114 100644 --- a/app/controllers/epp/sessions_controller.rb +++ b/app/controllers/epp/sessions_controller.rb @@ -7,7 +7,7 @@ class Epp::SessionsController < EppController def login success = true - @api_user = APIUser.find_by(login_params) + @api_user = ApiUser.find_by(login_params) webclient_request = ENV['webclient_ips'].split(',').map(&:strip).include?(request.ip) if webclient_request && !Rails.env.test? && !Rails.env.development? diff --git a/app/controllers/registrant/sessions_controller.rb b/app/controllers/registrant/sessions_controller.rb index cb51a94f5..80a23eb0a 100644 --- a/app/controllers/registrant/sessions_controller.rb +++ b/app/controllers/registrant/sessions_controller.rb @@ -95,6 +95,6 @@ class Registrant::SessionsController < Devise::SessionsController def find_user_by_idc(idc) return User.new unless idc - APIUser.find_by(identity_code: idc) || User.new + ApiUser.find_by(identity_code: idc) || User.new end end diff --git a/app/controllers/registrar/current_user_controller.rb b/app/controllers/registrar/current_user_controller.rb index 3f969ecb2..266e4b915 100644 --- a/app/controllers/registrar/current_user_controller.rb +++ b/app/controllers/registrar/current_user_controller.rb @@ -12,7 +12,7 @@ class Registrar private def new_user - @new_user ||= APIUser.find(params[:new_user_id]) + @new_user ||= ApiUser.find(params[:new_user_id]) end end end diff --git a/app/controllers/registrar/sessions_controller.rb b/app/controllers/registrar/sessions_controller.rb index c369051e6..11841481d 100644 --- a/app/controllers/registrar/sessions_controller.rb +++ b/app/controllers/registrar/sessions_controller.rb @@ -26,7 +26,7 @@ class Registrar @depp_user.errors.add(:base, :webserver_client_cert_directive_should_be_required) end - @api_user = APIUser.find_by(username: params[:depp_user][:tag], password: params[:depp_user][:password]) + @api_user = ApiUser.find_by(username: params[:depp_user][:tag], password: params[:depp_user][:password]) unless @api_user @depp_user.errors.add(:base, t(:no_such_user)) @@ -53,7 +53,7 @@ class Registrar end def id - @user = APIUser.find_by_idc_data_and_allowed(request.env['SSL_CLIENT_S_DN'], request.ip) + @user = ApiUser.find_by_idc_data_and_allowed(request.env['SSL_CLIENT_S_DN'], request.ip) if @user sign_in(@user, event: :authentication) @@ -150,12 +150,12 @@ class Registrar def find_user_by_idc(idc) return User.new unless idc - APIUser.find_by(identity_code: idc) || User.new + ApiUser.find_by(identity_code: idc) || User.new end def find_user_by_idc_and_allowed(idc) return User.new unless idc - possible_users = APIUser.where(identity_code: idc) || User.new + possible_users = ApiUser.where(identity_code: idc) || User.new possible_users.each do |selected_user| if selected_user.registrar.white_ips.registrar_area.include_ip?(request.ip) return selected_user diff --git a/app/models/ability.rb b/app/models/ability.rb index 1bc4ae386..97086110b 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -10,7 +10,7 @@ class Ability case @user.class.to_s when 'AdminUser' @user.roles&.each { |role| send(role) } - when 'APIUser' + when 'ApiUser' @user.roles&.each { |role| send(role) } when 'RegistrantUser' static_registrant @@ -94,7 +94,7 @@ class Ability can :manage, ContactVersion can :manage, Billing::Price can :manage, User - can :manage, APIUser + can :manage, ApiUser can :manage, AdminUser can :manage, Certificate can :manage, Keyrelay diff --git a/app/models/api_user.rb b/app/models/api_user.rb index bee04a954..ce32c4045 100644 --- a/app/models/api_user.rb +++ b/app/models/api_user.rb @@ -1,6 +1,6 @@ require 'open3' -class APIUser < User +class ApiUser < User include EppErrors def epp_code_map diff --git a/app/models/concerns/versions.rb b/app/models/concerns/versions.rb index 50ea935d2..5e2bad90c 100644 --- a/app/models/concerns/versions.rb +++ b/app/models/concerns/versions.rb @@ -34,7 +34,7 @@ module Versions end def user_from_id_role_username(str) - user = APIUser.find_by(id: $1) if str =~ /^(\d+)-(APIUser:|api-)/ + user = ApiUser.find_by(id: $1) if str =~ /^(\d+)-(ApiUser:|api-)/ unless user.present? user = AdminUser.find_by(id: $1) if str =~ /^(\d+)-AdminUser:/ unless user.present? diff --git a/app/models/epp/domain.rb b/app/models/epp/domain.rb index 49049665c..749f5310c 100644 --- a/app/models/epp/domain.rb +++ b/app/models/epp/domain.rb @@ -490,7 +490,7 @@ class Epp::Domain < Domain def apply_pending_update! preclean_pendings - user = APIUser.find(pending_json['current_user_id']) + user = ApiUser.find(pending_json['current_user_id']) frame = Nokogiri::XML(pending_json['frame']) self.statuses.delete(DomainStatus::PENDING_UPDATE) diff --git a/app/views/admin/api_users/_form.haml b/app/views/admin/api_users/_form.haml index 722b98d0d..9a26b9fc8 100644 --- a/app/views/admin/api_users/_form.haml +++ b/app/views/admin/api_users/_form.haml @@ -38,7 +38,7 @@ = f.label :role, nil, class: 'required' .col-md-7 = select_tag 'api_user[roles][]', - options_for_select(APIUser::ROLES.map {|x| [x, x] }, @api_user.roles.try(:first)), + options_for_select(ApiUser::ROLES.map {|x| [x, x] }, @api_user.roles.try(:first)), class: 'form-control selectize' .checkbox %label{for: 'api_user_active'} diff --git a/app/views/admin/registrars/_users.html.erb b/app/views/admin/registrars/_users.html.erb index d85eaaf36..f182e4615 100644 --- a/app/views/admin/registrars/_users.html.erb +++ b/app/views/admin/registrars/_users.html.erb @@ -6,8 +6,8 @@
<%= ApiUser.human_attribute_name :username %><%= ApiUser.human_attribute_name :active %><%= APIUser.human_attribute_name :username %><%= APIUser.human_attribute_name :active %>
- - + + diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb index b4a84b01d..b4eccb451 100644 --- a/config/initializers/inflections.rb +++ b/config/initializers/inflections.rb @@ -12,5 +12,4 @@ ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'DNS' - inflect.acronym 'API' end diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake index 1d83ec5ef..2fa67a827 100644 --- a/lib/tasks/import.rake +++ b/lib/tasks/import.rake @@ -131,7 +131,7 @@ namespace :import do ips = [] temp = [] - existing_ids = APIUser.pluck(:legacy_id) + existing_ids = ApiUser.pluck(:legacy_id) existing_ips = WhiteIp.pluck(:ipv4) Legacy::Registrar.all.each do |x| @@ -143,7 +143,7 @@ namespace :import do if y.try(:cert) != 'pki' if y.try(:cert) == 'idkaart' - id_users << APIUser.new({ + id_users << ApiUser.new({ username: y.try(:password) ? y.try(:password) : y.try(:password), password: ('a'..'z').to_a.shuffle.first(8).join, identity_code: y.try(:password) ? y.try(:password) : y.try(:password), @@ -152,7 +152,7 @@ namespace :import do legacy_id: y.try(:id) }) else - temp << APIUser.new({ + temp << ApiUser.new({ username: x.handle.try(:strip), password: y.try(:password) ? y.try(:password) : ('a'..'z').to_a.shuffle.first(8).join, registrar_id: Registrar.find_by(legacy_id: x.try(:id)).try(:id), @@ -181,8 +181,8 @@ namespace :import do end end - APIUser.import id_users, validate: false - APIUser.import users, validate: false + ApiUser.import id_users, validate: false + ApiUser.import users, validate: false if ips WhiteIp.import ips, validate: false diff --git a/spec/factories/api_user.rb b/spec/factories/api_user.rb index 31355f141..a3f9623b6 100644 --- a/spec/factories/api_user.rb +++ b/spec/factories/api_user.rb @@ -1,7 +1,7 @@ FactoryBot.define do factory :api_user do sequence(:username) { |n| "test#{n}" } - password 'a' * APIUser.min_password_length + password 'a' * ApiUser.min_password_length roles ['super'] registrar diff --git a/spec/models/api_user_spec.rb b/spec/models/api_user_spec.rb index b710a05c9..89feeac6d 100644 --- a/spec/models/api_user_spec.rb +++ b/spec/models/api_user_spec.rb @@ -1,16 +1,16 @@ require 'rails_helper' -RSpec.describe APIUser do +RSpec.describe ApiUser do context 'with invalid attribute' do before do - @api_user = APIUser.new + @api_user = ApiUser.new end it 'should not be valid' do @api_user.valid? @api_user.errors.full_messages.should match_array([ "Password Password is missing", - "Password is too short (minimum is #{APIUser.min_password_length} characters)", + "Password is too short (minimum is #{ApiUser.min_password_length} characters)", "Registrar Registrar is missing", "Username Username is missing", "Roles is missing" diff --git a/spec/models/domain_spec.rb b/spec/models/domain_spec.rb index 007b1e3de..6b282d651 100644 --- a/spec/models/domain_spec.rb +++ b/spec/models/domain_spec.rb @@ -316,10 +316,10 @@ RSpec.describe Domain do @api_user = create(:api_user) @user.id.should == 1 @api_user.id.should == 2 - ::PaperTrail.whodunnit = '2-APIUser: testuser' + ::PaperTrail.whodunnit = '2-ApiUser: testuser' @domain = create(:domain) - @domain.creator_str.should == '2-APIUser: testuser' + @domain.creator_str.should == '2-ApiUser: testuser' @domain.creator.should == @api_user @domain.creator.should_not == @user diff --git a/spec/presenters/user_presenter_spec.rb b/spec/presenters/user_presenter_spec.rb index c0cff114b..ba9e1673f 100644 --- a/spec/presenters/user_presenter_spec.rb +++ b/spec/presenters/user_presenter_spec.rb @@ -4,7 +4,7 @@ RSpec.describe UserPresenter do let(:presenter) { described_class.new(user: user, view: view) } describe '#login_with_role' do - let(:user) { instance_double(APIUser, + let(:user) { instance_double(ApiUser, login: 'login', roles: %w[role], registrar_name: 'registrar') } diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml index 9d3001959..5fd2dc925 100644 --- a/test/fixtures/users.yml +++ b/test/fixtures/users.yml @@ -1,7 +1,7 @@ api_bestnames: username: test_bestnames password: testtest - type: APIUser + type: ApiUser registrar: bestnames active: true roles: @@ -10,7 +10,7 @@ api_bestnames: api_goodnames: username: test_goodnames password: testtest - type: APIUser + type: ApiUser registrar: goodnames active: true roles: diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/system/api/registrant/registrant_api_authentication_test.rb index 9ed518caa..94693ddd5 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/system/api/registrant/registrant_api_authentication_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrantAPIAuthenticationTest < ApplicationSystemTestCase +class RegistrantApiAuthenticationTest < ApplicationSystemTestCase def setup super diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/system/api/registrant/registrant_api_domains_test.rb index ab08b4ba2..da5813518 100644 --- a/test/system/api/registrant/registrant_api_domains_test.rb +++ b/test/system/api/registrant/registrant_api_domains_test.rb @@ -1,7 +1,7 @@ require 'test_helper' require 'auth_token/auth_token_creator' -class RegistrantAPIDomainsTest < ApplicationSystemTestCase +class RegistrantApiDomainsTest < ApplicationSystemTestCase def setup super From 3adb85001a435651654b316c9f619a46a4d7064a Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 26 Jul 2018 10:39:58 +0300 Subject: [PATCH 27/60] Insert space into configuration example --- config/application-example.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/application-example.yml b/config/application-example.yml index 7a69aa9e2..b9917e69e 100644 --- a/config/application-example.yml +++ b/config/application-example.yml @@ -97,7 +97,7 @@ sk_digi_doc_service_endpoint: 'https://tsp.demo.sk.ee' sk_digi_doc_service_name: 'Testimine' # Registrant API -registrant_api_auth_allowed_ips: '127.0.0.1,0.0.0.0' #ips, separated with commas +registrant_api_auth_allowed_ips: '127.0.0.1, 0.0.0.0' #ips, separated with commas # # MISC From 0ab9f6333fb53eb60f170abd7399d27448b98450 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 26 Jul 2018 14:46:03 +0300 Subject: [PATCH 28/60] Add API/Registrant/Domains route --- .../api/v1/registrant/domains_controller.rb | 17 +++++++++++++++++ config/routes.rb | 8 ++++++++ test/fixtures/domains.yml | 12 +++++++++++- .../registrant/registrant_api_domains_test.rb | 17 +++++++++++++++++ 4 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 app/controllers/api/v1/registrant/domains_controller.rb create mode 100644 test/system/api/registrant/registrant_api_domains_test.rb diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb new file mode 100644 index 000000000..44662c673 --- /dev/null +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -0,0 +1,17 @@ +require 'rails5_api_controller_backport' + +module Api + module V1 + module Registrant + class DomainsController < ActionController::API + def index + render json: { success: true } + end + + def show + render json: { success: true } + end + end + end + end +end diff --git a/config/routes.rb b/config/routes.rb index 8f50d5587..aa73eef3f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -18,6 +18,14 @@ Rails.application.routes.draw do mount Repp::API => '/' + namespace :api do + namespace :v1 do + namespace :registrant do + resources :domains, only: [:index, :show], param: :uuid + end + end + end + # REGISTRAR ROUTES namespace :registrar do resource :dashboard diff --git a/test/fixtures/domains.yml b/test/fixtures/domains.yml index 59a1b8ea5..38500e9cc 100644 --- a/test/fixtures/domains.yml +++ b/test/fixtures/domains.yml @@ -42,10 +42,20 @@ metro: period_unit: m uuid: ef97cb80-333b-4893-b9df-163f2b452798 +hospital: + name: hospital.test + registrar: goodnames + registrant: william + transfer_code: 23118v2 + valid_to: 2010-07-05 + period: 1 + period_unit: m + uuid: 5edda1a5-3548-41ee-8b65-6d60daf85a37 + invalid: name: invalid.test transfer_code: 1438d6 valid_to: <%= Time.zone.parse('2010-07-05').utc.to_s(:db) %> registrar: bestnames registrant: invalid - uuid: 3c430ead-bb17-4b5b-aaa1-caa7dde7e138 \ No newline at end of file + uuid: 3c430ead-bb17-4b5b-aaa1-caa7dde7e138 diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/system/api/registrant/registrant_api_domains_test.rb new file mode 100644 index 000000000..6a53f7720 --- /dev/null +++ b/test/system/api/registrant/registrant_api_domains_test.rb @@ -0,0 +1,17 @@ +require 'test_helper' + +class RegistrantApiDomainsTest < ApplicationSystemTestCase + def setup + super + + @registrant = contacts(:william) + end + + def teardown + super + end + + + def test_can_get_domain_details_by_uuid + end +end From c36b780c7131d41424010e234ead7155478b8637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timo=20V=C3=B5hmar?= Date: Fri, 27 Jul 2018 01:19:18 +0300 Subject: [PATCH 29/60] Changelog update 180726 --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecefbb279..44b66ef4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +26.07.2018 +* Grape (1.0.3), mustermann (1.0.2), multi_json (1.13.1) gem updates [#912](https://github.com/internetee/registry/issues/912) +* Capybara (3.3.1), mini_mime (0.1.3), nokogiri (1.8), rack (1.6.0), xpath (3.1) gem updates [#980](https://github.com/internetee/registry/issues/908) +* Webmock (3.4.2), addressable (2.5.2), hashdiff (0.3.7), public_suffix (3.0.2) gem updates [#907](https://github.com/internetee/registry/issues/907) +* fixed typo in assertions filename [#920](https://github.com/internetee/registry/issues/920) +* regenerate structure.sql [#915](https://github.com/internetee/registry/issues/915) + 12.07.2018 * Implemented JavaScript testing framework to catch web UI problems [#900](https://github.com/internetee/registry/issues/900) From 526a9ccd58df1c6b5228efb612b95fbdfef4ea1e Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Fri, 27 Jul 2018 09:36:27 +0300 Subject: [PATCH 30/60] Change test structure to follow closer newer Rails 5 rules * Create new class called ApplicationIntegrationTest, so we don't have to override ActionDispatch::IntegrationTest * Move UI tests to inherit from ApplicationSystemTestCase * Existing REST API or EPP tests inherit from ApplicationIntegrationTest. * Move `require 'application_system_test_case'` at the end of `test_helper` I don't particularly agree with the Rails' convention of treating UI tests as system tests and API tests as integration tests, but I see no benefit in actively fighting against it. --- test/application_system_test_case.rb | 2 +- test/integration/api/domain_contacts_test.rb | 2 +- test/integration/api/domain_transfers_test.rb | 2 +- test/integration/api/nameservers/put_test.rb | 2 +- test/integration/epp/domain/create/nameservers_test.rb | 2 +- test/integration/epp/domain/create/transfer_code_test.rb | 2 +- test/integration/epp/domain/domain_delete_test.rb | 2 +- test/integration/epp/domain/domain_renew_test.rb | 2 +- test/integration/epp/domain/domain_update_test.rb | 2 +- test/integration/epp/domain/transfer/base_test.rb | 2 +- test/integration/epp/domain/transfer/query_test.rb | 2 +- test/integration/epp/domain/transfer/request_test.rb | 2 +- test/integration/epp/login/credentials_test.rb | 2 +- test/integration/epp/login/session_limit_test.rb | 2 +- test/integration/epp/logout_test.rb | 2 +- test/integration/epp/poll_test.rb | 2 +- .../admin => system/admin_area}/contact_versions_test.rb | 2 +- .../admin => system/admin_area}/contacts_test.rb | 2 +- .../admin => system/admin_area}/domain_versions_test.rb | 2 +- .../admin => system/admin_area}/domains/details_test.rb | 2 +- .../admin_area}/domains/force_delete_test.rb | 2 +- .../admin => system/admin_area}/domains_test.rb | 2 +- .../admin => system/admin_area}/mail_templates/new_test.rb | 2 +- .../admin => system/admin_area}/registrars/delete_test.rb | 2 +- .../admin => system/admin_area}/registrars/details_test.rb | 2 +- .../admin => system/admin_area}/registrars/edit_test.rb | 2 +- .../admin => system/admin_area}/registrars/new_test.rb | 2 +- .../registrant => system/registrant_area}/domains_test.rb | 2 +- .../registrant => system/registrant_area}/layout_test.rb | 2 +- .../registrar_area}/billing/balance_top_up_test.rb | 2 +- .../registrar_area}/bulk_change/bulk_transfer_test.rb | 2 +- .../registrar_area}/bulk_change/nameserver_test.rb | 2 +- .../registrar_area}/bulk_change/tech_contact_test.rb | 2 +- .../registrar => system/registrar_area}/domains_test.rb | 2 +- .../registrar_area}/invoices/list_test.rb | 2 +- .../registrar_area}/invoices/new_invoice_payment_test.rb | 2 +- .../registrar_area}/invoices/new_test.rb | 2 +- .../registrar_area}/invoices/payment_callback_test.rb | 2 +- .../registrar_area}/invoices/payment_return_test.rb | 2 +- test/system/{registrar => registrar_area}/sign_in_test.rb | 0 test/test_helper.rb | 6 +++--- 41 files changed, 42 insertions(+), 42 deletions(-) rename test/{integration/admin => system/admin_area}/contact_versions_test.rb (96%) rename test/{integration/admin => system/admin_area}/contacts_test.rb (89%) rename test/{integration/admin => system/admin_area}/domain_versions_test.rb (97%) rename test/{integration/admin => system/admin_area}/domains/details_test.rb (85%) rename test/{integration/admin => system/admin_area}/domains/force_delete_test.rb (95%) rename test/{integration/admin => system/admin_area}/domains_test.rb (77%) rename test/{integration/admin => system/admin_area}/mail_templates/new_test.rb (79%) rename test/{integration/admin => system/admin_area}/registrars/delete_test.rb (91%) rename test/{integration/admin => system/admin_area}/registrars/details_test.rb (84%) rename test/{integration/admin => system/admin_area}/registrars/edit_test.rb (97%) rename test/{integration/admin => system/admin_area}/registrars/new_test.rb (95%) rename test/{integration/registrant => system/registrant_area}/domains_test.rb (90%) rename test/{integration/registrant => system/registrant_area}/layout_test.rb (88%) rename test/{integration/registrar => system/registrar_area}/billing/balance_top_up_test.rb (91%) rename test/{integration/registrar => system/registrar_area}/bulk_change/bulk_transfer_test.rb (95%) rename test/{integration/registrar => system/registrar_area}/bulk_change/nameserver_test.rb (96%) rename test/{integration/registrar => system/registrar_area}/bulk_change/tech_contact_test.rb (95%) rename test/{integration/registrar => system/registrar_area}/domains_test.rb (92%) rename test/{integration/registrar => system/registrar_area}/invoices/list_test.rb (90%) rename test/{integration/registrar => system/registrar_area}/invoices/new_invoice_payment_test.rb (95%) rename test/{integration/registrar => system/registrar_area}/invoices/new_test.rb (95%) rename test/{integration/registrar => system/registrar_area}/invoices/payment_callback_test.rb (96%) rename test/{integration/registrar => system/registrar_area}/invoices/payment_return_test.rb (98%) rename test/system/{registrar => registrar_area}/sign_in_test.rb (100%) diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb index 6c06ef937..cceeb27c5 100644 --- a/test/application_system_test_case.rb +++ b/test/application_system_test_case.rb @@ -3,7 +3,7 @@ require 'test_helper' require 'database_cleaner' require 'selenium/webdriver' -class ApplicationSystemTestCase < ActionDispatch::IntegrationTest; end +ApplicationSystemTestCase = Class.new(ApplicationIntegrationTest) class JavaScriptApplicationSystemTestCase < ApplicationSystemTestCase self.use_transactional_fixtures = false diff --git a/test/integration/api/domain_contacts_test.rb b/test/integration/api/domain_contacts_test.rb index a6d6376f7..e99a45825 100644 --- a/test/integration/api/domain_contacts_test.rb +++ b/test/integration/api/domain_contacts_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class APIDomainContactsTest < ActionDispatch::IntegrationTest +class APIDomainContactsTest < ApplicationIntegrationTest def test_replace_all_tech_contacts_of_the_current_registrar patch '/repp/v1/domains/contacts', { current_contact_id: 'william-001', new_contact_id: 'john-001' }, diff --git a/test/integration/api/domain_transfers_test.rb b/test/integration/api/domain_transfers_test.rb index 4b65b35de..d439a64e5 100644 --- a/test/integration/api/domain_transfers_test.rb +++ b/test/integration/api/domain_transfers_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class APIDomainTransfersTest < ActionDispatch::IntegrationTest +class APIDomainTransfersTest < ApplicationIntegrationTest setup do @domain = domains(:shop) @new_registrar = registrars(:goodnames) diff --git a/test/integration/api/nameservers/put_test.rb b/test/integration/api/nameservers/put_test.rb index 0967a1169..4c35d3e77 100644 --- a/test/integration/api/nameservers/put_test.rb +++ b/test/integration/api/nameservers/put_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class APINameserversPutTest < ActionDispatch::IntegrationTest +class APINameserversPutTest < ApplicationIntegrationTest def test_replaces_registrar_nameservers old_nameserver_ids = [nameservers(:shop_ns1).id, nameservers(:airport_ns1).id, diff --git a/test/integration/epp/domain/create/nameservers_test.rb b/test/integration/epp/domain/create/nameservers_test.rb index ddaddf2d1..954d1f300 100644 --- a/test/integration/epp/domain/create/nameservers_test.rb +++ b/test/integration/epp/domain/create/nameservers_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainCreateNameserversTest < ActionDispatch::IntegrationTest +class EppDomainCreateNameserversTest < ApplicationIntegrationTest # Glue record requirement def test_nameserver_ip_address_is_required_if_hostname_is_under_the_same_domain request_xml = <<-XML diff --git a/test/integration/epp/domain/create/transfer_code_test.rb b/test/integration/epp/domain/create/transfer_code_test.rb index 60133cb35..131baf67a 100644 --- a/test/integration/epp/domain/create/transfer_code_test.rb +++ b/test/integration/epp/domain/create/transfer_code_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainCreateTransferCodeTest < ActionDispatch::IntegrationTest +class EppDomainCreateTransferCodeTest < ApplicationIntegrationTest setup do travel_to Time.zone.parse('2010-07-05') end diff --git a/test/integration/epp/domain/domain_delete_test.rb b/test/integration/epp/domain/domain_delete_test.rb index eae4d39ff..61cd7d6f3 100644 --- a/test/integration/epp/domain/domain_delete_test.rb +++ b/test/integration/epp/domain/domain_delete_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainDeleteTest < ActionDispatch::IntegrationTest +class EppDomainDeleteTest < ApplicationIntegrationTest def test_bypasses_domain_and_registrant_and_contacts_validation request_xml = <<-XML diff --git a/test/integration/epp/domain/domain_renew_test.rb b/test/integration/epp/domain/domain_renew_test.rb index 338ecf766..ac48269ad 100644 --- a/test/integration/epp/domain/domain_renew_test.rb +++ b/test/integration/epp/domain/domain_renew_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainRenewTest < ActionDispatch::IntegrationTest +class EppDomainRenewTest < ApplicationIntegrationTest self.use_transactional_fixtures = false setup do diff --git a/test/integration/epp/domain/domain_update_test.rb b/test/integration/epp/domain/domain_update_test.rb index ac7160558..f1db1b087 100644 --- a/test/integration/epp/domain/domain_update_test.rb +++ b/test/integration/epp/domain/domain_update_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainUpdateTest < ActionDispatch::IntegrationTest +class EppDomainUpdateTest < ApplicationIntegrationTest def test_update_domain request_xml = <<-XML diff --git a/test/integration/epp/domain/transfer/base_test.rb b/test/integration/epp/domain/transfer/base_test.rb index aa9f841b6..e220f8ebd 100644 --- a/test/integration/epp/domain/transfer/base_test.rb +++ b/test/integration/epp/domain/transfer/base_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainTransferBaseTest < ActionDispatch::IntegrationTest +class EppDomainTransferBaseTest < ApplicationIntegrationTest def test_non_existent_domain request_xml = <<-XML diff --git a/test/integration/epp/domain/transfer/query_test.rb b/test/integration/epp/domain/transfer/query_test.rb index 1412dd9b3..8a9c589c8 100644 --- a/test/integration/epp/domain/transfer/query_test.rb +++ b/test/integration/epp/domain/transfer/query_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainTransferQueryTest < ActionDispatch::IntegrationTest +class EppDomainTransferQueryTest < ApplicationIntegrationTest def test_returns_domain_transfer_details post '/epp/command/transfer', { frame: request_xml }, { 'HTTP_COOKIE' => 'session=api_bestnames' } xml_doc = Nokogiri::XML(response.body) diff --git a/test/integration/epp/domain/transfer/request_test.rb b/test/integration/epp/domain/transfer/request_test.rb index 3e776331b..6335fb27e 100644 --- a/test/integration/epp/domain/transfer/request_test.rb +++ b/test/integration/epp/domain/transfer/request_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppDomainTransferRequestTest < ActionDispatch::IntegrationTest +class EppDomainTransferRequestTest < ApplicationIntegrationTest setup do @domain = domains(:shop) @new_registrar = registrars(:goodnames) diff --git a/test/integration/epp/login/credentials_test.rb b/test/integration/epp/login/credentials_test.rb index 6a27c7393..3eac10da5 100644 --- a/test/integration/epp/login/credentials_test.rb +++ b/test/integration/epp/login/credentials_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppLoginCredentialsTest < ActionDispatch::IntegrationTest +class EppLoginCredentialsTest < ApplicationIntegrationTest def test_correct_credentials request_xml = <<-XML diff --git a/test/integration/epp/login/session_limit_test.rb b/test/integration/epp/login/session_limit_test.rb index b2fdfe88f..de7f85a06 100644 --- a/test/integration/epp/login/session_limit_test.rb +++ b/test/integration/epp/login/session_limit_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppLoginSessionLimitTest < ActionDispatch::IntegrationTest +class EppLoginSessionLimitTest < ApplicationIntegrationTest setup do travel_to Time.zone.parse('2010-07-05') EppSession.delete_all diff --git a/test/integration/epp/logout_test.rb b/test/integration/epp/logout_test.rb index 75b26f2f3..dc8276e7e 100644 --- a/test/integration/epp/logout_test.rb +++ b/test/integration/epp/logout_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppLogoutTest < ActionDispatch::IntegrationTest +class EppLogoutTest < ApplicationIntegrationTest def test_success_response post '/epp/session/logout', { frame: request_xml }, { 'HTTP_COOKIE' => 'session=api_bestnames' } assert Nokogiri::XML(response.body).at_css('result[code="1500"]') diff --git a/test/integration/epp/poll_test.rb b/test/integration/epp/poll_test.rb index db6091cb0..30ee5c769 100644 --- a/test/integration/epp/poll_test.rb +++ b/test/integration/epp/poll_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class EppPollTest < ActionDispatch::IntegrationTest +class EppPollTest < ApplicationIntegrationTest def test_messages post '/epp/command/poll', { frame: request_xml }, { 'HTTP_COOKIE' => 'session=api_bestnames' } assert_equal '1301', Nokogiri::XML(response.body).at_css('result')[:code] diff --git a/test/integration/admin/contact_versions_test.rb b/test/system/admin_area/contact_versions_test.rb similarity index 96% rename from test/integration/admin/contact_versions_test.rb rename to test/system/admin_area/contact_versions_test.rb index daaba64e8..10d20615a 100644 --- a/test/integration/admin/contact_versions_test.rb +++ b/test/system/admin_area/contact_versions_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class ContactVersionsTest < ActionDispatch::IntegrationTest +class ContactVersionsTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/admin/contacts_test.rb b/test/system/admin_area/contacts_test.rb similarity index 89% rename from test/integration/admin/contacts_test.rb rename to test/system/admin_area/contacts_test.rb index 1d2d2e07e..c72004988 100644 --- a/test/integration/admin/contacts_test.rb +++ b/test/system/admin_area/contacts_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminContactsTest < ActionDispatch::IntegrationTest +class AdminContactsTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/admin/domain_versions_test.rb b/test/system/admin_area/domain_versions_test.rb similarity index 97% rename from test/integration/admin/domain_versions_test.rb rename to test/system/admin_area/domain_versions_test.rb index 760f4b4ef..6c375cefe 100644 --- a/test/integration/admin/domain_versions_test.rb +++ b/test/system/admin_area/domain_versions_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class DomainVersionsTest < ActionDispatch::IntegrationTest +class DomainVersionsTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/admin/domains/details_test.rb b/test/system/admin_area/domains/details_test.rb similarity index 85% rename from test/integration/admin/domains/details_test.rb rename to test/system/admin_area/domains/details_test.rb index cb9fb96f3..31a46a19b 100644 --- a/test/integration/admin/domains/details_test.rb +++ b/test/system/admin_area/domains/details_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaDomainDetailsTest < ActionDispatch::IntegrationTest +class AdminAreaDomainDetailsTest < ApplicationSystemTestCase setup do sign_in users(:admin) @domain = domains(:shop) diff --git a/test/integration/admin/domains/force_delete_test.rb b/test/system/admin_area/domains/force_delete_test.rb similarity index 95% rename from test/integration/admin/domains/force_delete_test.rb rename to test/system/admin_area/domains/force_delete_test.rb index 3e5d7d4d6..f98401173 100644 --- a/test/integration/admin/domains/force_delete_test.rb +++ b/test/system/admin_area/domains/force_delete_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaDomainForceDeleteTest < ActionDispatch::IntegrationTest +class AdminAreaDomainForceDeleteTest < ApplicationSystemTestCase include ActionMailer::TestHelper setup do diff --git a/test/integration/admin/domains_test.rb b/test/system/admin_area/domains_test.rb similarity index 77% rename from test/integration/admin/domains_test.rb rename to test/system/admin_area/domains_test.rb index 6ef6443fc..538de2604 100644 --- a/test/integration/admin/domains_test.rb +++ b/test/system/admin_area/domains_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminDomainsTestTest < ActionDispatch::IntegrationTest +class AdminDomainsTestTest < ApplicationSystemTestCase setup do sign_in users(:admin) end diff --git a/test/integration/admin/mail_templates/new_test.rb b/test/system/admin_area/mail_templates/new_test.rb similarity index 79% rename from test/integration/admin/mail_templates/new_test.rb rename to test/system/admin_area/mail_templates/new_test.rb index c2a01f3d0..dcaa5d592 100644 --- a/test/integration/admin/mail_templates/new_test.rb +++ b/test/system/admin_area/mail_templates/new_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaNewMailTemplateTest < ActionDispatch::IntegrationTest +class AdminAreaNewMailTemplateTest < ApplicationSystemTestCase setup do sign_in users(:admin) end diff --git a/test/integration/admin/registrars/delete_test.rb b/test/system/admin_area/registrars/delete_test.rb similarity index 91% rename from test/integration/admin/registrars/delete_test.rb rename to test/system/admin_area/registrars/delete_test.rb index 177564d79..f0ecaecc6 100644 --- a/test/integration/admin/registrars/delete_test.rb +++ b/test/system/admin_area/registrars/delete_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaDeleteRegistrarTest < ActionDispatch::IntegrationTest +class AdminAreaDeleteRegistrarTest < ApplicationSystemTestCase setup do sign_in users(:admin) end diff --git a/test/integration/admin/registrars/details_test.rb b/test/system/admin_area/registrars/details_test.rb similarity index 84% rename from test/integration/admin/registrars/details_test.rb rename to test/system/admin_area/registrars/details_test.rb index fe96f46e2..1dfb4b03a 100644 --- a/test/integration/admin/registrars/details_test.rb +++ b/test/system/admin_area/registrars/details_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaRegistrarDetailsTest < ActionDispatch::IntegrationTest +class AdminAreaRegistrarDetailsTest < ApplicationSystemTestCase include ActionView::Helpers::NumberHelper setup do diff --git a/test/integration/admin/registrars/edit_test.rb b/test/system/admin_area/registrars/edit_test.rb similarity index 97% rename from test/integration/admin/registrars/edit_test.rb rename to test/system/admin_area/registrars/edit_test.rb index 6c58fe4e5..9cb9d5020 100644 --- a/test/integration/admin/registrars/edit_test.rb +++ b/test/system/admin_area/registrars/edit_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaEditRegistrarTest < ActionDispatch::IntegrationTest +class AdminAreaEditRegistrarTest < ApplicationSystemTestCase setup do sign_in users(:admin) @registrar = registrars(:bestnames) diff --git a/test/integration/admin/registrars/new_test.rb b/test/system/admin_area/registrars/new_test.rb similarity index 95% rename from test/integration/admin/registrars/new_test.rb rename to test/system/admin_area/registrars/new_test.rb index e0e286938..90425a714 100644 --- a/test/integration/admin/registrars/new_test.rb +++ b/test/system/admin_area/registrars/new_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class AdminAreaNewRegistrarTest < ActionDispatch::IntegrationTest +class AdminAreaNewRegistrarTest < ApplicationSystemTestCase setup do sign_in users(:admin) end diff --git a/test/integration/registrant/domains_test.rb b/test/system/registrant_area/domains_test.rb similarity index 90% rename from test/integration/registrant/domains_test.rb rename to test/system/registrant_area/domains_test.rb index fbed651b6..7eeebb6e7 100644 --- a/test/integration/registrant/domains_test.rb +++ b/test/system/registrant_area/domains_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrantDomainsTest < ActionDispatch::IntegrationTest +class RegistrantDomainsTest < ApplicationSystemTestCase setup do sign_in users(:registrant) diff --git a/test/integration/registrant/layout_test.rb b/test/system/registrant_area/layout_test.rb similarity index 88% rename from test/integration/registrant/layout_test.rb rename to test/system/registrant_area/layout_test.rb index 131389b6c..90d6f8907 100644 --- a/test/integration/registrant/layout_test.rb +++ b/test/system/registrant_area/layout_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrantLayoutTest < ActionDispatch::IntegrationTest +class RegistrantLayoutTest < ApplicationSystemTestCase def setup super sign_in(users(:registrant)) diff --git a/test/integration/registrar/billing/balance_top_up_test.rb b/test/system/registrar_area/billing/balance_top_up_test.rb similarity index 91% rename from test/integration/registrar/billing/balance_top_up_test.rb rename to test/system/registrar_area/billing/balance_top_up_test.rb index d991bea45..2d44e8328 100644 --- a/test/integration/registrar/billing/balance_top_up_test.rb +++ b/test/system/registrar_area/billing/balance_top_up_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class BalanceTopUpTest < ActionDispatch::IntegrationTest +class BalanceTopUpTest < ApplicationSystemTestCase setup do sign_in users(:api_bestnames) end diff --git a/test/integration/registrar/bulk_change/bulk_transfer_test.rb b/test/system/registrar_area/bulk_change/bulk_transfer_test.rb similarity index 95% rename from test/integration/registrar/bulk_change/bulk_transfer_test.rb rename to test/system/registrar_area/bulk_change/bulk_transfer_test.rb index 4cd374862..3a663a9bc 100644 --- a/test/integration/registrar/bulk_change/bulk_transfer_test.rb +++ b/test/system/registrar_area/bulk_change/bulk_transfer_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrarAreaBulkTransferTest < ActionDispatch::IntegrationTest +class RegistrarAreaBulkTransferTest < ApplicationSystemTestCase setup do sign_in users(:api_goodnames) end diff --git a/test/integration/registrar/bulk_change/nameserver_test.rb b/test/system/registrar_area/bulk_change/nameserver_test.rb similarity index 96% rename from test/integration/registrar/bulk_change/nameserver_test.rb rename to test/system/registrar_area/bulk_change/nameserver_test.rb index 841e68db5..c5789a969 100644 --- a/test/integration/registrar/bulk_change/nameserver_test.rb +++ b/test/system/registrar_area/bulk_change/nameserver_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrarAreaNameserverBulkChangeTest < ActionDispatch::IntegrationTest +class RegistrarAreaNameserverBulkChangeTest < ApplicationSystemTestCase setup do sign_in users(:api_goodnames) end diff --git a/test/integration/registrar/bulk_change/tech_contact_test.rb b/test/system/registrar_area/bulk_change/tech_contact_test.rb similarity index 95% rename from test/integration/registrar/bulk_change/tech_contact_test.rb rename to test/system/registrar_area/bulk_change/tech_contact_test.rb index 9277cdb38..0b68b9db2 100644 --- a/test/integration/registrar/bulk_change/tech_contact_test.rb +++ b/test/system/registrar_area/bulk_change/tech_contact_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrarAreaTechContactBulkChangeTest < ActionDispatch::IntegrationTest +class RegistrarAreaTechContactBulkChangeTest < ApplicationSystemTestCase setup do sign_in users(:api_bestnames) end diff --git a/test/integration/registrar/domains_test.rb b/test/system/registrar_area/domains_test.rb similarity index 92% rename from test/integration/registrar/domains_test.rb rename to test/system/registrar_area/domains_test.rb index 55333dfb4..a01dd576b 100644 --- a/test/integration/registrar/domains_test.rb +++ b/test/system/registrar_area/domains_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrarDomainsTest < ActionDispatch::IntegrationTest +class RegistrarDomainsTest < ApplicationSystemTestCase def test_downloads_domain_list_as_csv sign_in users(:api_bestnames) travel_to Time.zone.parse('2010-07-05 10:30') diff --git a/test/integration/registrar/invoices/list_test.rb b/test/system/registrar_area/invoices/list_test.rb similarity index 90% rename from test/integration/registrar/invoices/list_test.rb rename to test/system/registrar_area/invoices/list_test.rb index e9b051df7..be344d034 100644 --- a/test/integration/registrar/invoices/list_test.rb +++ b/test/system/registrar_area/invoices/list_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class ListInvoicesTest < ActionDispatch::IntegrationTest +class ListInvoicesTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/registrar/invoices/new_invoice_payment_test.rb b/test/system/registrar_area/invoices/new_invoice_payment_test.rb similarity index 95% rename from test/integration/registrar/invoices/new_invoice_payment_test.rb rename to test/system/registrar_area/invoices/new_invoice_payment_test.rb index 2513751dd..6933ff9ad 100644 --- a/test/integration/registrar/invoices/new_invoice_payment_test.rb +++ b/test/system/registrar_area/invoices/new_invoice_payment_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class NewInvoicePaymentTest < ActionDispatch::IntegrationTest +class NewInvoicePaymentTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/registrar/invoices/new_test.rb b/test/system/registrar_area/invoices/new_test.rb similarity index 95% rename from test/integration/registrar/invoices/new_test.rb rename to test/system/registrar_area/invoices/new_test.rb index 35011826b..b9b6b6db4 100644 --- a/test/integration/registrar/invoices/new_test.rb +++ b/test/system/registrar_area/invoices/new_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class NewInvoiceTest < ActionDispatch::IntegrationTest +class NewInvoiceTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/registrar/invoices/payment_callback_test.rb b/test/system/registrar_area/invoices/payment_callback_test.rb similarity index 96% rename from test/integration/registrar/invoices/payment_callback_test.rb rename to test/system/registrar_area/invoices/payment_callback_test.rb index 20ecea3e5..c1920995d 100644 --- a/test/integration/registrar/invoices/payment_callback_test.rb +++ b/test/system/registrar_area/invoices/payment_callback_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class PaymentCallbackTest < ActionDispatch::IntegrationTest +class PaymentCallbackTest < ApplicationSystemTestCase def setup super diff --git a/test/integration/registrar/invoices/payment_return_test.rb b/test/system/registrar_area/invoices/payment_return_test.rb similarity index 98% rename from test/integration/registrar/invoices/payment_return_test.rb rename to test/system/registrar_area/invoices/payment_return_test.rb index 9530cf609..45e85118f 100644 --- a/test/integration/registrar/invoices/payment_return_test.rb +++ b/test/system/registrar_area/invoices/payment_return_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class PaymentReturnTest < ActionDispatch::IntegrationTest +class PaymentReturnTest < ApplicationSystemTestCase def setup super diff --git a/test/system/registrar/sign_in_test.rb b/test/system/registrar_area/sign_in_test.rb similarity index 100% rename from test/system/registrar/sign_in_test.rb rename to test/system/registrar_area/sign_in_test.rb diff --git a/test/test_helper.rb b/test/test_helper.rb index 56a4a7aeb..ee6923367 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -13,8 +13,6 @@ require 'capybara/minitest' require 'webmock/minitest' require 'support/rails5_assertions' # Remove once upgraded to Rails 5 -require 'application_system_test_case' - Setting.address_processing = false Setting.registry_country_code = 'US' @@ -29,7 +27,7 @@ class ActiveSupport::TestCase end end -class ActionDispatch::IntegrationTest +class ApplicationIntegrationTest < ActionDispatch::IntegrationTest include Capybara::DSL include Capybara::Minitest::Assertions include AbstractController::Translation @@ -41,3 +39,5 @@ class ActionDispatch::IntegrationTest Capybara.use_default_driver end end + +require 'application_system_test_case' From b33ad0d4e892bc6273f4c0b3b0632eb439b5bace Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Fri, 27 Jul 2018 11:00:35 +0300 Subject: [PATCH 31/60] Add show action --- .../api/v1/registrant/domains_controller.rb | 11 ++++++---- config/application.rb | 2 +- test/fixtures/domains.yml | 2 +- .../registrant/registrant_api_domains_test.rb | 21 +++++++++++++++++-- 4 files changed, 28 insertions(+), 8 deletions(-) diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index 44662c673..be755b55c 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -4,12 +4,15 @@ module Api module V1 module Registrant class DomainsController < ActionController::API - def index - render json: { success: true } - end def show - render json: { success: true } + @domain = Domain.find_by(uuid: params[:uuid]) + + if @domain + render json: @domain + else + render json: { errors: ["Domain not found"] }, status: :not_found + end end end end diff --git a/config/application.rb b/config/application.rb index 400e72124..1420d3cd3 100644 --- a/config/application.rb +++ b/config/application.rb @@ -36,7 +36,7 @@ module DomainNameRegistry config.i18n.default_locale = :en config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb') - config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] + # config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] # Autoload all model subdirs config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')] diff --git a/test/fixtures/domains.yml b/test/fixtures/domains.yml index 38500e9cc..4d6468c92 100644 --- a/test/fixtures/domains.yml +++ b/test/fixtures/domains.yml @@ -45,7 +45,7 @@ metro: hospital: name: hospital.test registrar: goodnames - registrant: william + registrant: john transfer_code: 23118v2 valid_to: 2010-07-05 period: 1 diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/system/api/registrant/registrant_api_domains_test.rb index 6a53f7720..36a9def35 100644 --- a/test/system/api/registrant/registrant_api_domains_test.rb +++ b/test/system/api/registrant/registrant_api_domains_test.rb @@ -4,14 +4,31 @@ class RegistrantApiDomainsTest < ApplicationSystemTestCase def setup super - @registrant = contacts(:william) + @domain = domains(:hospital) + @registrant = @domain.registrant end def teardown super end + def test_get_domain_details_by_uuid + get '/api/v1/registrant/domains/5edda1a5-3548-41ee-8b65-6d60daf85a37' + assert_equal(200, response.status) - def test_can_get_domain_details_by_uuid + domain = JSON.parse(response.body, symbolize_names: true) + assert_equal('hospital.test', domain[:name]) + end + + def test_get_non_existent_domain_details_by_uuid + get '/api/v1/registrant/domains/random-uuid' + assert_equal(404, response.status) + + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({errors: ['Domain not found']}, response_json) + end + + def test_get_non_registrar_domain_details_by_uuid + # no op end end From e75d962d39d6b5fc7a615168033405556d59b00d Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Fri, 27 Jul 2018 11:19:18 +0300 Subject: [PATCH 32/60] Remove inconsistent usage of error/errors --- doc/registrant-api/v1/domain.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index 80290fbac..2e249423c 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -157,5 +157,5 @@ Content-Type: application/json HTTP/1.1 404 Content-Type: application/json -{ "error": "Domain not found" } +{ "errors": ["Domain not found"] } ``` From c49d626f86150c76879de6a915a3f35b936c8349 Mon Sep 17 00:00:00 2001 From: Artur Beljajev Date: Sat, 28 Jul 2018 14:27:36 +0300 Subject: [PATCH 33/60] Remove dead code --- app/models/concerns/domain_version_observer.rb | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 app/models/concerns/domain_version_observer.rb diff --git a/app/models/concerns/domain_version_observer.rb b/app/models/concerns/domain_version_observer.rb deleted file mode 100644 index f1e732f21..000000000 --- a/app/models/concerns/domain_version_observer.rb +++ /dev/null @@ -1,3 +0,0 @@ -module DomainVersionObserver - extend ActiveSupport::Concern -end From ed1afb78f6ae6705df38d9cbaca3c80e56029838 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 30 Jul 2018 10:30:57 +0300 Subject: [PATCH 34/60] Make tests conform with #924 --- .../api/registrant/registrant_api_authentication_test.rb | 2 +- .../api/registrant/registrant_api_domains_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename test/{system => integration}/api/registrant/registrant_api_authentication_test.rb (95%) rename test/{system => integration}/api/registrant/registrant_api_domains_test.rb (92%) diff --git a/test/system/api/registrant/registrant_api_authentication_test.rb b/test/integration/api/registrant/registrant_api_authentication_test.rb similarity index 95% rename from test/system/api/registrant/registrant_api_authentication_test.rb rename to test/integration/api/registrant/registrant_api_authentication_test.rb index 94693ddd5..cdcd53025 100644 --- a/test/system/api/registrant/registrant_api_authentication_test.rb +++ b/test/integration/api/registrant/registrant_api_authentication_test.rb @@ -1,6 +1,6 @@ require 'test_helper' -class RegistrantApiAuthenticationTest < ApplicationSystemTestCase +class RegistrantApiAuthenticationTest < ActionDispatch::IntegrationTest def setup super diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb similarity index 92% rename from test/system/api/registrant/registrant_api_domains_test.rb rename to test/integration/api/registrant/registrant_api_domains_test.rb index da5813518..1c91d4775 100644 --- a/test/system/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -1,7 +1,7 @@ require 'test_helper' require 'auth_token/auth_token_creator' -class RegistrantApiDomainsTest < ApplicationSystemTestCase +class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest def setup super From c1ea79615f5d751141d5056331e898fd6658b7c8 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 30 Jul 2018 11:07:44 +0300 Subject: [PATCH 35/60] Make API return errors array --- app/controllers/api/v1/registrant/auth_controller.rb | 2 +- app/controllers/api/v1/registrant/base_controller.rb | 2 +- .../api/registrant/registrant_api_authentication_test.rb | 4 ++-- .../integration/api/registrant/registrant_api_domains_test.rb | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 7ba0e9199..5be48f558 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -46,7 +46,7 @@ module Api allowed_ips = ENV['registrant_api_auth_allowed_ips'].to_s.split(',').map(&:strip) return if allowed_ips.include?(request.ip) || Rails.env.development? - render json: { error: 'Not authorized' }, status: :unauthorized + render json: { errors: ['Not authorized'] }, status: :unauthorized end end end diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb index 510f16745..bc5fa21d7 100644 --- a/app/controllers/api/v1/registrant/base_controller.rb +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -29,7 +29,7 @@ module Api if decryptor.valid? sign_in decryptor.user else - render json: { error: 'Not authorized' }, status: :unauthorized + render json: { errors: ['Not authorized'] }, status: :unauthorized end end end diff --git a/test/integration/api/registrant/registrant_api_authentication_test.rb b/test/integration/api/registrant/registrant_api_authentication_test.rb index cdcd53025..14ef1c879 100644 --- a/test/integration/api/registrant/registrant_api_authentication_test.rb +++ b/test/integration/api/registrant/registrant_api_authentication_test.rb @@ -42,7 +42,7 @@ class RegistrantApiAuthenticationTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({error: 'Not authorized'}, json_body) + assert_equal({ errors: ['Not authorized'] }, json_body) ENV['registrant_api_auth_allowed_ips'] = @original_whitelist_ip end @@ -52,7 +52,7 @@ class RegistrantApiAuthenticationTest < ActionDispatch::IntegrationTest post '/api/v1/registrant/auth/eid', params json = JSON.parse(response.body, symbolize_names: true) - assert_equal({errors: [{ident: ['parameter is required']}]}, json) + assert_equal({ errors: [{ ident: ['parameter is required'] }] }, json) assert_equal(422, response.status) end end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb index 1c91d4775..2d0b83903 100644 --- a/test/integration/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -19,7 +19,7 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({error: 'Not authorized'}, json_body) + assert_equal({ errors: ['Not authorized'] }, json_body) end private From 13562aeb0687040b3464718e7f70b7bfb8e36ee6 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 30 Jul 2018 13:56:54 +0300 Subject: [PATCH 36/60] Move file to another folder --- .../registrant/registrant_api_domains_test.rb | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) rename test/{system => integration}/api/registrant/registrant_api_domains_test.rb (51%) diff --git a/test/system/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb similarity index 51% rename from test/system/api/registrant/registrant_api_domains_test.rb rename to test/integration/api/registrant/registrant_api_domains_test.rb index 36a9def35..bcf11cfc0 100644 --- a/test/system/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -1,6 +1,7 @@ require 'test_helper' +require 'auth_token/auth_token_creator' -class RegistrantApiDomainsTest < ApplicationSystemTestCase +class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest def setup super @@ -28,7 +29,24 @@ class RegistrantApiDomainsTest < ApplicationSystemTestCase assert_equal({errors: ['Domain not found']}, response_json) end - def test_get_non_registrar_domain_details_by_uuid - # no op + def test_root_returns_domain_list + get '/api/v1/registrant/domains', {}, @auth_headers + assert_equal(200, response.status) + end + + def test_root_returns_401_without_authorization + get '/api/v1/registrant/domains', {}, {} + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Not authorized'] }, json_body) + end + + private + + def auth_token + token_creator = AuthTokenCreator.create_with_defaults(@user) + hash = token_creator.token_in_hash + "Bearer #{hash[:access_token]}" end end From 10d42a0d74f250d019ed22fb99631196ad065f82 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Mon, 30 Jul 2018 15:09:48 +0300 Subject: [PATCH 37/60] Add domain index action (without pagination yet) --- .../api/v1/registrant/base_controller.rb | 38 ++++++++++++++++ .../api/v1/registrant/domains_controller.rb | 20 ++++++++- lib/auth_token/auth_token_creator.rb | 41 ++++++++++++++++++ lib/auth_token/auth_token_decryptor.rb | 43 +++++++++++++++++++ .../registrant/registrant_api_domains_test.rb | 17 +++++++- 5 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 app/controllers/api/v1/registrant/base_controller.rb create mode 100644 lib/auth_token/auth_token_creator.rb create mode 100644 lib/auth_token/auth_token_decryptor.rb diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb new file mode 100644 index 000000000..bc5fa21d7 --- /dev/null +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -0,0 +1,38 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_decryptor' + +module Api + module V1 + module Registrant + class BaseController < ActionController::API + before_action :authenticate + + rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception| + error = {} + error[parameter_missing_exception.param] = ['parameter is required'] + response = { errors: [error] } + render json: response, status: :unprocessable_entity + end + + private + + def bearer_token + pattern = /^Bearer / + header = request.headers['Authorization'] + header.gsub(pattern, '') if header&.match(pattern) + end + + def authenticate + decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token) + decryptor.decrypt_token + + if decryptor.valid? + sign_in decryptor.user + else + render json: { errors: ['Not authorized'] }, status: :unauthorized + end + end + end + end + end +end diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index be755b55c..96d767d38 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -3,10 +3,15 @@ require 'rails5_api_controller_backport' module Api module V1 module Registrant - class DomainsController < ActionController::API + class DomainsController < BaseController + def index + @domains = associated_domains(current_user) + render json: @domains + end def show - @domain = Domain.find_by(uuid: params[:uuid]) + domain_pool = associated_domains(current_user) + @domain = domain_pool.find_by(uuid: params[:uuid]) if @domain render json: @domain @@ -14,6 +19,17 @@ module Api render json: { errors: ["Domain not found"] }, status: :not_found end end + + private + + def associated_domains(user) + country_code, ident = user.registrant_ident.split('-') + + BusinessRegistryCache.fetch_associated_domains(ident, country_code) + rescue Soap::Arireg::NotAvailableError => error + Rails.logger.fatal("[EXCEPTION] #{error.to_s}") + user.domains + end end end end diff --git a/lib/auth_token/auth_token_creator.rb b/lib/auth_token/auth_token_creator.rb new file mode 100644 index 000000000..9fff8e5cd --- /dev/null +++ b/lib/auth_token/auth_token_creator.rb @@ -0,0 +1,41 @@ +class AuthTokenCreator + DEFAULT_VALIDITY = 2.hours + + attr_reader :user + attr_reader :key + attr_reader :expires_at + + def self.create_with_defaults(user) + new(user, Rails.application.config.secret_key_base, Time.now + DEFAULT_VALIDITY) + end + + def initialize(user, key, expires_at) + @user = user + @key = key + @expires_at = expires_at.utc.strftime('%F %T %Z') + end + + def hashable + { + user_ident: user.registrant_ident, + user_username: user.username, + expires_at: expires_at, + }.to_json + end + + def encrypted_token + encryptor = OpenSSL::Cipher::AES.new(256, :CBC) + encryptor.encrypt + encryptor.key = key + encrypted_bytes = encryptor.update(hashable) + encryptor.final + Base64.urlsafe_encode64(encrypted_bytes) + end + + def token_in_hash + { + access_token: encrypted_token, + expires_at: expires_at, + type: 'Bearer', + } + end +end diff --git a/lib/auth_token/auth_token_decryptor.rb b/lib/auth_token/auth_token_decryptor.rb new file mode 100644 index 000000000..be6bd99cd --- /dev/null +++ b/lib/auth_token/auth_token_decryptor.rb @@ -0,0 +1,43 @@ +class AuthTokenDecryptor + attr_reader :decrypted_data + attr_reader :token + attr_reader :key + attr_reader :user + + def self.create_with_defaults(token) + new(token, Rails.application.config.secret_key_base) + end + + def initialize(token, key) + @token = token + @key = key + end + + def decrypt_token + decipher = OpenSSL::Cipher::AES.new(256, :CBC) + decipher.decrypt + decipher.key = key + + base64_decoded = Base64.urlsafe_decode64(token.to_s) + plain = decipher.update(base64_decoded) + decipher.final + + @decrypted_data = JSON.parse(plain, symbolize_names: true) + rescue OpenSSL::Cipher::CipherError, ArgumentError + false + end + + def valid? + decrypted_data && valid_user? && still_valid? + end + + private + + def valid_user? + @user = RegistrantUser.find_by(registrant_ident: decrypted_data[:user_ident]) + @user&.username == decrypted_data[:user_username] + end + + def still_valid? + decrypted_data[:expires_at] > Time.now + end +end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb index bcf11cfc0..c892f088b 100644 --- a/test/integration/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -5,16 +5,25 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest def setup super + @original_registry_time = Setting.days_to_keep_business_registry_cache + Setting.days_to_keep_business_registry_cache = 1 + travel_to Time.zone.parse('2010-07-05') + @domain = domains(:hospital) @registrant = @domain.registrant + @user = users(:registrant) + @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } end def teardown super + + Setting.days_to_keep_business_registry_cache = @original_registry_time + travel_back end def test_get_domain_details_by_uuid - get '/api/v1/registrant/domains/5edda1a5-3548-41ee-8b65-6d60daf85a37' + get '/api/v1/registrant/domains/5edda1a5-3548-41ee-8b65-6d60daf85a37', {}, @auth_headers assert_equal(200, response.status) domain = JSON.parse(response.body, symbolize_names: true) @@ -22,7 +31,7 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest end def test_get_non_existent_domain_details_by_uuid - get '/api/v1/registrant/domains/random-uuid' + get '/api/v1/registrant/domains/random-uuid', {}, @auth_headers assert_equal(404, response.status) response_json = JSON.parse(response.body, symbolize_names: true) @@ -32,6 +41,10 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest def test_root_returns_domain_list get '/api/v1/registrant/domains', {}, @auth_headers assert_equal(200, response.status) + + response_json = JSON.parse(response.body, symbolize_names: true) + array_of_domain_names = response_json.map { |x| x[:name] } + assert(array_of_domain_names.include?('hospital.test')) end def test_root_returns_401_without_authorization From c476680a91fe24e534ccbd35b0f0832032e96da2 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 31 Jul 2018 15:14:21 +0300 Subject: [PATCH 38/60] Add pagination to index --- .../api/v1/registrant/domains_controller.rb | 19 ++++++++-- .../registrant/registrant_api_domains_test.rb | 37 +++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index 96d767d38..1e21f6770 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -5,7 +5,20 @@ module Api module Registrant class DomainsController < BaseController def index - @domains = associated_domains(current_user) + limit = params[:limit] || 200 + offset = params[:offset] || 0 + + if limit.to_i > 200 || limit.to_i < 1 + render(json: { errors: [{ limit: ['parameter is out of range'] }] }, + status: :bad_request) && return + end + + if offset.to_i.negative? + render(json: { errors: [{ offset: ['parameter is out of range'] }] }, + status: :bad_request) && return + end + + @domains = associated_domains(current_user).limit(limit).offset(offset) render json: @domains end @@ -16,7 +29,7 @@ module Api if @domain render json: @domain else - render json: { errors: ["Domain not found"] }, status: :not_found + render json: { errors: ['Domain not found'] }, status: :not_found end end @@ -27,7 +40,7 @@ module Api BusinessRegistryCache.fetch_associated_domains(ident, country_code) rescue Soap::Arireg::NotAvailableError => error - Rails.logger.fatal("[EXCEPTION] #{error.to_s}") + Rails.logger.fatal("[EXCEPTION] #{error}") user.domains end end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb index c892f088b..3e966b192 100644 --- a/test/integration/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -47,6 +47,35 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest assert(array_of_domain_names.include?('hospital.test')) end + def test_root_accepts_limit_and_offset_parameters + get '/api/v1/registrant/domains', { 'limit' => 2, 'offset' => 0 }, @auth_headers + response_json = JSON.parse(response.body, symbolize_names: true) + + assert_equal(200, response.status) + assert_equal(2, response_json.count) + + get '/api/v1/registrant/domains', {}, @auth_headers + response_json = JSON.parse(response.body, symbolize_names: true) + + assert_equal(5, response_json.count) + end + + def test_root_does_not_accept_limit_higher_than_200 + get '/api/v1/registrant/domains', { 'limit' => 400, 'offset' => 0 }, @auth_headers + + assert_equal(400, response.status) + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [{ limit: ['parameter is out of range'] }] }, response_json) + end + + def test_root_does_not_accept_offset_lower_than_0 + get '/api/v1/registrant/domains', { 'limit' => 200, 'offset' => "-10" }, @auth_headers + + assert_equal(400, response.status) + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [{ offset: ['parameter is out of range'] }] }, response_json) + end + def test_root_returns_401_without_authorization get '/api/v1/registrant/domains', {}, {} assert_equal(401, response.status) @@ -55,6 +84,14 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest assert_equal({ errors: ['Not authorized'] }, json_body) end + def test_details_returns_401_without_authorization + get '/api/v1/registrant/domains/5edda1a5-3548-41ee-8b65-6d60daf85a37', {}, {} + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Not authorized'] }, json_body) + end + private def auth_token From 3673c69319b87c82bc8b279583f3d463f347c50b Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 1 Aug 2018 14:57:41 +0300 Subject: [PATCH 39/60] Add Registrant/Contacts endpoint --- .../api/v1/registrant/contacts_controller.rb | 47 +++++++++++ config/routes.rb | 1 + .../registrant_api_contacts_test.rb | 79 +++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 app/controllers/api/v1/registrant/contacts_controller.rb create mode 100644 test/integration/api/registrant/registrant_api_contacts_test.rb diff --git a/app/controllers/api/v1/registrant/contacts_controller.rb b/app/controllers/api/v1/registrant/contacts_controller.rb new file mode 100644 index 000000000..31d56885b --- /dev/null +++ b/app/controllers/api/v1/registrant/contacts_controller.rb @@ -0,0 +1,47 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_decryptor' + +module Api + module V1 + module Registrant + class ContactsController < BaseController + before_action :set_contacts_pool + + def index + limit = params[:limit] || 200 + offset = params[:offset] || 0 + + if limit.to_i > 200 || limit.to_i < 1 + render(json: { errors: [{ limit: ['parameter is out of range'] }] }, + status: :bad_request) && return + end + + if offset.to_i.negative? + render(json: { errors: [{ offset: ['parameter is out of range'] }] }, + status: :bad_request) && return + end + + @contacts = @contacts_pool.limit(limit).offset(offset) + render json: @contacts + end + + def show + @contact = @contacts_pool.find_by(uuid: params[:uuid]) + + if @contact + render json: @contact + else + render json: { errors: ['Contact not found'] }, status: :not_found + end + end + + private + + def set_contacts_pool + country_code, ident = current_user.registrant_ident.to_s.split '-' + @contacts_pool = Contact.where(country_code: country_code, ident: ident) + end + end + end + end +end diff --git a/config/routes.rb b/config/routes.rb index 3ae18a7cd..9229eb1b2 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -24,6 +24,7 @@ Rails.application.routes.draw do post 'auth/eid', to: 'auth#eid' resources :domains, only: [:index] + resources :contacts, only: %i[index show] end end end diff --git a/test/integration/api/registrant/registrant_api_contacts_test.rb b/test/integration/api/registrant/registrant_api_contacts_test.rb new file mode 100644 index 000000000..a3367dd58 --- /dev/null +++ b/test/integration/api/registrant/registrant_api_contacts_test.rb @@ -0,0 +1,79 @@ +require 'test_helper' +require 'auth_token/auth_token_creator' + +class RegistrantApiContactsTest < ActionDispatch::IntegrationTest + def setup + super + + @user = users(:registrant) + @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } + end + + def test_root_returns_domain_list + get '/api/v1/registrant/contacts', {}, @auth_headers + assert_equal(200, response.status) + + json_body = JSON.parse(response.body, symbolize_names: true) + assert_equal(2, json_body.count) + array_of_contact_codes = json_body.map { |x| x[:code] } + assert(array_of_contact_codes.include?('william-001')) + assert(array_of_contact_codes.include?('william-002')) + end + + def test_root_accepts_limit_and_offset_parameters + get '/api/v1/registrant/contacts', { 'limit' => 1, 'offset' => 0 }, @auth_headers + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal(200, response.status) + assert_equal(1, response_json.count) + + get '/api/v1/registrant/contacts', {}, @auth_headers + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal(2, response_json.count) + end + + def test_root_does_not_accept_limit_higher_than_200 + get '/api/v1/registrant/contacts', { 'limit' => 400, 'offset' => 0 }, @auth_headers + assert_equal(400, response.status) + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [{ limit: ['parameter is out of range'] }] }, response_json) + end + + def test_root_does_not_accept_offset_lower_than_0 + get '/api/v1/registrant/contacts', { 'limit' => 200, 'offset' => "-10" }, @auth_headers + assert_equal(400, response.status) + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [{ offset: ['parameter is out of range'] }] }, response_json) + end + + def test_root_returns_401_without_authorization + get '/api/v1/registrant/contacts', {}, {} + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Not authorized'] }, json_body) + end + + def test_details_returns_401_without_authorization + get '/api/v1/registrant/contacts/c0a191d5-3793-4f0b-8f85-491612d0293e', {}, {} + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Not authorized'] }, json_body) + end + + def test_details_returns_404_for_non_existent_contact + get '/api/v1/registrant/contacts/some-random-uuid', {}, @auth_headers + assert_equal(404, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Contact not found'] }, json_body) + end + + private + + def auth_token + token_creator = AuthTokenCreator.create_with_defaults(@user) + hash = token_creator.token_in_hash + "Bearer #{hash[:access_token]}" + end +end From 39cc31ff7b1f467e8a6ce07fb4567e1d758f4533 Mon Sep 17 00:00:00 2001 From: Artur Beljajev Date: Wed, 1 Aug 2018 22:13:55 +0300 Subject: [PATCH 40/60] Remove unused view --- app/views/registrant/registrars/index.haml | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 app/views/registrant/registrars/index.haml diff --git a/app/views/registrant/registrars/index.haml b/app/views/registrant/registrars/index.haml deleted file mode 100644 index 03bd5a02a..000000000 --- a/app/views/registrant/registrars/index.haml +++ /dev/null @@ -1,21 +0,0 @@ -- content_for :actions do - = render 'shared/title', name: t(:registrars) - -.row - .col-md-12 - .table-responsive - %table.table.table-hover.table-bordered.table-condensed - %thead - %tr - %th{class: 'col-xs-6'} - = sort_link(@q, 'name') - %th{class: 'col-xs-6'} - = sort_link(@q, 'reg_no', Registrar.human_attribute_name(:reg_no)) - %tbody - - @registrars.each do |x| - %tr - %td= link_to(x, [:registrar, x]) - %td= x.reg_no -.row - .col-md-12 - = paginate @registrars From ad8dfcc28f07e9b13228577cf8abdcfb3af77d41 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 7 Aug 2018 14:52:33 +0300 Subject: [PATCH 41/60] Make authentication errors more consistent with other errors --- app/controllers/api/v1/registrant/auth_controller.rb | 4 ++-- app/controllers/api/v1/registrant/base_controller.rb | 2 +- .../api/registrant/registrant_api_authentication_test.rb | 2 +- .../integration/api/registrant/registrant_api_domains_test.rb | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb index 5be48f558..929d5b5c9 100644 --- a/app/controllers/api/v1/registrant/auth_controller.rb +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -21,7 +21,7 @@ module Api if token render json: token else - render json: { error: 'Cannot create generate session token' } + render json: { errors: [{ base: ['Cannot create generate session token'] }] } end end @@ -46,7 +46,7 @@ module Api allowed_ips = ENV['registrant_api_auth_allowed_ips'].to_s.split(',').map(&:strip) return if allowed_ips.include?(request.ip) || Rails.env.development? - render json: { errors: ['Not authorized'] }, status: :unauthorized + render json: { errors: [{ base: ['Not authorized'] }] }, status: :unauthorized end end end diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb index bc5fa21d7..4df0d226c 100644 --- a/app/controllers/api/v1/registrant/base_controller.rb +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -29,7 +29,7 @@ module Api if decryptor.valid? sign_in decryptor.user else - render json: { errors: ['Not authorized'] }, status: :unauthorized + render json: { errors: [{base: ['Not authorized']}] }, status: :unauthorized end end end diff --git a/test/integration/api/registrant/registrant_api_authentication_test.rb b/test/integration/api/registrant/registrant_api_authentication_test.rb index 14ef1c879..97651b029 100644 --- a/test/integration/api/registrant/registrant_api_authentication_test.rb +++ b/test/integration/api/registrant/registrant_api_authentication_test.rb @@ -42,7 +42,7 @@ class RegistrantApiAuthenticationTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({ errors: ['Not authorized'] }, json_body) + assert_equal({ errors: [base: ['Not authorized']] }, json_body) ENV['registrant_api_auth_allowed_ips'] = @original_whitelist_ip end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb index 2d0b83903..0f2be7db5 100644 --- a/test/integration/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -19,7 +19,7 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({ errors: ['Not authorized'] }, json_body) + assert_equal({ errors: [base: ['Not authorized']] }, json_body) end private From 079800172552ab94ff5bcc360288d76c5c2828ff Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 7 Aug 2018 15:04:37 +0300 Subject: [PATCH 42/60] Make returned API errors more consistent --- app/controllers/api/v1/registrant/contacts_controller.rb | 2 +- .../api/registrant/registrant_api_contacts_test.rb | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/controllers/api/v1/registrant/contacts_controller.rb b/app/controllers/api/v1/registrant/contacts_controller.rb index 31d56885b..f252b3acd 100644 --- a/app/controllers/api/v1/registrant/contacts_controller.rb +++ b/app/controllers/api/v1/registrant/contacts_controller.rb @@ -31,7 +31,7 @@ module Api if @contact render json: @contact else - render json: { errors: ['Contact not found'] }, status: :not_found + render json: { errors: [{ base: ['Contact not found'] }] }, status: :not_found end end diff --git a/test/integration/api/registrant/registrant_api_contacts_test.rb b/test/integration/api/registrant/registrant_api_contacts_test.rb index a3367dd58..ff51494af 100644 --- a/test/integration/api/registrant/registrant_api_contacts_test.rb +++ b/test/integration/api/registrant/registrant_api_contacts_test.rb @@ -50,7 +50,7 @@ class RegistrantApiContactsTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({ errors: ['Not authorized'] }, json_body) + assert_equal({ errors: [base: ['Not authorized']] }, json_body) end def test_details_returns_401_without_authorization @@ -58,7 +58,7 @@ class RegistrantApiContactsTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({ errors: ['Not authorized'] }, json_body) + assert_equal({ errors: [base: ['Not authorized']] }, json_body) end def test_details_returns_404_for_non_existent_contact @@ -66,7 +66,7 @@ class RegistrantApiContactsTest < ActionDispatch::IntegrationTest assert_equal(404, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({ errors: ['Contact not found'] }, json_body) + assert_equal({ errors: [base: ['Contact not found']] }, json_body) end private From abb1ad60e890b4a08a0bc063a362fa204ba89a7b Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 7 Aug 2018 14:56:19 +0300 Subject: [PATCH 43/60] Update failing test --- app/controllers/api/v1/registrant/domains_controller.rb | 2 +- .../integration/api/registrant/registrant_api_domains_test.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index 1e21f6770..27b7b6125 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -29,7 +29,7 @@ module Api if @domain render json: @domain else - render json: { errors: ['Domain not found'] }, status: :not_found + render json: { errors: [{ base: ['Domain not found'] }] }, status: :not_found end end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb index 1c77131c4..e297c921c 100644 --- a/test/integration/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -35,7 +35,7 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest assert_equal(404, response.status) response_json = JSON.parse(response.body, symbolize_names: true) - assert_equal({errors: ['Domain not found']}, response_json) + assert_equal({ errors: [base: ['Domain not found']] }, response_json) end def test_root_returns_domain_list @@ -89,7 +89,7 @@ class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest assert_equal(401, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal({ errors: ['Not authorized'] }, json_body) + assert_equal({ errors: [base: ['Not authorized']] }, json_body) end private From 738785fcb901bbd5a2536c19384be26e72ff09c6 Mon Sep 17 00:00:00 2001 From: Artur Beljajev Date: Tue, 7 Aug 2018 16:41:11 +0300 Subject: [PATCH 44/60] Add contact tests --- test/models/contact_test.rb | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 test/models/contact_test.rb diff --git a/test/models/contact_test.rb b/test/models/contact_test.rb new file mode 100644 index 000000000..b4ea6ec38 --- /dev/null +++ b/test/models/contact_test.rb @@ -0,0 +1,35 @@ +require 'test_helper' + +class ContactTest < ActiveSupport::TestCase + def setup + @contact = contacts(:john) + @original_address_processing_setting = Setting.address_processing + end + + def teardown + Setting.address_processing = @original_address_processing_setting + end + + def test_valid_fixture + assert @contact.valid? + end + + def test_email_validation + @contact.email = '' + assert @contact.invalid? + + @contact.email = 'test@bestmail.test' + assert @contact.valid? + end + + def test_phone_validation + @contact.phone = '' + assert @contact.invalid? + + @contact.phone = '+123.' + assert @contact.invalid? + + @contact.phone = '+123.4' + assert @contact.valid? + end +end \ No newline at end of file From f73a2551d3d61d542983be63ec7773999b57899a Mon Sep 17 00:00:00 2001 From: Artur Beljajev Date: Tue, 7 Aug 2018 22:53:02 +0300 Subject: [PATCH 45/60] Improve readability --- test/models/contact_test.rb | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/test/models/contact_test.rb b/test/models/contact_test.rb index b4ea6ec38..e63c0e589 100644 --- a/test/models/contact_test.rb +++ b/test/models/contact_test.rb @@ -14,18 +14,25 @@ class ContactTest < ActiveSupport::TestCase assert @contact.valid? end - def test_email_validation + def test_invalid_without_email @contact.email = '' assert @contact.invalid? + end + + def test_email_format_validation + @contact.email = 'invalid' + assert @contact.invalid? @contact.email = 'test@bestmail.test' assert @contact.valid? end - def test_phone_validation - @contact.phone = '' + def test_invalid_without_phone + @contact.email = '' assert @contact.invalid? + end + def test_phone_format_validation @contact.phone = '+123.' assert @contact.invalid? From e1881685b7c44a5287e13793047170e2f8bafe08 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 8 Aug 2018 09:13:46 +0300 Subject: [PATCH 46/60] Make tests inherit from ApplicationIntegrationTest class --- .../api/registrant/registrant_api_authentication_test.rb | 4 ++-- .../integration/api/registrant/registrant_api_domains_test.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/integration/api/registrant/registrant_api_authentication_test.rb b/test/integration/api/registrant/registrant_api_authentication_test.rb index 97651b029..10858d005 100644 --- a/test/integration/api/registrant/registrant_api_authentication_test.rb +++ b/test/integration/api/registrant/registrant_api_authentication_test.rb @@ -1,10 +1,10 @@ require 'test_helper' -class RegistrantApiAuthenticationTest < ActionDispatch::IntegrationTest +class RegistrantApiAuthenticationTest < ApplicationIntegrationTest def setup super - @user_hash = {ident: '37010100049', first_name: 'Adam', last_name: 'Baker'} + @user_hash = { ident: '37010100049', first_name: 'Adam', last_name: 'Baker' } @existing_user = RegistrantUser.find_or_create_by_api_data(@user_hash) end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb index 0f2be7db5..9fc92ce62 100644 --- a/test/integration/api/registrant/registrant_api_domains_test.rb +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -1,7 +1,7 @@ require 'test_helper' require 'auth_token/auth_token_creator' -class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest +class RegistrantApiDomainsTest < ApplicationIntegrationTest def setup super From 06dc954167b48f1854611282d02537cf6ced3a56 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 8 Aug 2018 09:15:18 +0300 Subject: [PATCH 47/60] Make tests inherit from ApplicationIntegrationTest class --- test/integration/api/registrant/registrant_api_contacts_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/api/registrant/registrant_api_contacts_test.rb b/test/integration/api/registrant/registrant_api_contacts_test.rb index ff51494af..c73c4a503 100644 --- a/test/integration/api/registrant/registrant_api_contacts_test.rb +++ b/test/integration/api/registrant/registrant_api_contacts_test.rb @@ -1,7 +1,7 @@ require 'test_helper' require 'auth_token/auth_token_creator' -class RegistrantApiContactsTest < ActionDispatch::IntegrationTest +class RegistrantApiContactsTest < ApplicationIntegrationTest def setup super From 3fc55866b23ce77b550fd7aad1f2bce23cb1b718 Mon Sep 17 00:00:00 2001 From: Artur Beljajev Date: Wed, 8 Aug 2018 13:55:54 +0300 Subject: [PATCH 48/60] Use setup callback --- test/models/contact_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/models/contact_test.rb b/test/models/contact_test.rb index e63c0e589..fc01388a3 100644 --- a/test/models/contact_test.rb +++ b/test/models/contact_test.rb @@ -1,7 +1,7 @@ require 'test_helper' class ContactTest < ActiveSupport::TestCase - def setup + setup do @contact = contacts(:john) @original_address_processing_setting = Setting.address_processing end From 9225d30914364a122fdbb058d4ae1abbc575fc7f Mon Sep 17 00:00:00 2001 From: Artur Beljajev Date: Wed, 8 Aug 2018 13:56:14 +0300 Subject: [PATCH 49/60] Remove dead code --- test/models/contact_test.rb | 5 ----- 1 file changed, 5 deletions(-) diff --git a/test/models/contact_test.rb b/test/models/contact_test.rb index fc01388a3..5651cc883 100644 --- a/test/models/contact_test.rb +++ b/test/models/contact_test.rb @@ -3,11 +3,6 @@ require 'test_helper' class ContactTest < ActiveSupport::TestCase setup do @contact = contacts(:john) - @original_address_processing_setting = Setting.address_processing - end - - def teardown - Setting.address_processing = @original_address_processing_setting end def test_valid_fixture From b18db190355fb38f5b7891ef32dd284a8025e39b Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 9 Aug 2018 14:07:06 +0300 Subject: [PATCH 50/60] Fix error introduced by merge conflict --- config/routes.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/routes.rb b/config/routes.rb index 7a802a7a1..6af6623f8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -23,7 +23,7 @@ Rails.application.routes.draw do namespace :registrant do post 'auth/eid', to: 'auth#eid' - resources :domains, only: %i[index, show], param: :uuid + resources :domains, only: %i[index show], param: :uuid resources :contacts, only: %i[index show], param: :uuid end end From 4cc06692868e15a910b41beb17658d309396cda9 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 9 Aug 2018 15:04:22 +0300 Subject: [PATCH 51/60] Add business registry support for contacts controller --- .../api/v1/registrant/contacts_controller.rb | 18 +++++++--- .../api/v1/registrant/domains_controller.rb | 2 -- .../registrant/contacts_controller.rb | 2 +- .../registrant_api_contacts_test.rb | 33 +++++++++++++++++-- 4 files changed, 45 insertions(+), 10 deletions(-) diff --git a/app/controllers/api/v1/registrant/contacts_controller.rb b/app/controllers/api/v1/registrant/contacts_controller.rb index f252b3acd..2c8a1f70e 100644 --- a/app/controllers/api/v1/registrant/contacts_controller.rb +++ b/app/controllers/api/v1/registrant/contacts_controller.rb @@ -1,6 +1,3 @@ -require 'rails5_api_controller_backport' -require 'auth_token/auth_token_decryptor' - module Api module V1 module Registrant @@ -39,7 +36,20 @@ module Api def set_contacts_pool country_code, ident = current_user.registrant_ident.to_s.split '-' - @contacts_pool = Contact.where(country_code: country_code, ident: ident) + associated_domain_ids = begin + BusinessRegistryCache.fetch_by_ident_and_cc(ident, country_code).associated_domain_ids + end + + available_contacts_ids = begin + DomainContact.where(domain_id: associated_domain_ids).pluck(:contact_id) | + Domain.where(id: associated_domain_ids).pluck(:registrant_id) + end + + @contacts_pool = Contact.where(id: available_contacts_ids) + rescue Soap::Arireg::NotAvailableError => error + Rails.logger.fatal("[EXCEPTION] #{error}") + render json: { errors: [{ base: ["Business Registry Not Available"] }] }, + status: :service_unavailable and return end end end diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb index 27b7b6125..7209f8a10 100644 --- a/app/controllers/api/v1/registrant/domains_controller.rb +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -1,5 +1,3 @@ -require 'rails5_api_controller_backport' - module Api module V1 module Registrant diff --git a/app/controllers/registrant/contacts_controller.rb b/app/controllers/registrant/contacts_controller.rb index f73650de2..267b4d68d 100644 --- a/app/controllers/registrant/contacts_controller.rb +++ b/app/controllers/registrant/contacts_controller.rb @@ -26,4 +26,4 @@ class Registrant::ContactsController < RegistrantController BusinessRegistryCache.fetch_by_ident_and_cc(ident, ident_cc).associated_domain_ids end end -end \ No newline at end of file +end diff --git a/test/integration/api/registrant/registrant_api_contacts_test.rb b/test/integration/api/registrant/registrant_api_contacts_test.rb index c73c4a503..28dd50d76 100644 --- a/test/integration/api/registrant/registrant_api_contacts_test.rb +++ b/test/integration/api/registrant/registrant_api_contacts_test.rb @@ -5,19 +5,30 @@ class RegistrantApiContactsTest < ApplicationIntegrationTest def setup super + @original_registry_time = Setting.days_to_keep_business_registry_cache + Setting.days_to_keep_business_registry_cache = 1 + travel_to Time.zone.parse('2010-07-05') + @user = users(:registrant) @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } end + def teardown + super + + Setting.days_to_keep_business_registry_cache = @original_registry_time + travel_back + end + def test_root_returns_domain_list get '/api/v1/registrant/contacts', {}, @auth_headers assert_equal(200, response.status) json_body = JSON.parse(response.body, symbolize_names: true) - assert_equal(2, json_body.count) + assert_equal(5, json_body.count) array_of_contact_codes = json_body.map { |x| x[:code] } assert(array_of_contact_codes.include?('william-001')) - assert(array_of_contact_codes.include?('william-002')) + assert(array_of_contact_codes.include?('jane-001')) end def test_root_accepts_limit_and_offset_parameters @@ -28,7 +39,23 @@ class RegistrantApiContactsTest < ApplicationIntegrationTest get '/api/v1/registrant/contacts', {}, @auth_headers response_json = JSON.parse(response.body, symbolize_names: true) - assert_equal(2, response_json.count) + assert_equal(5, response_json.count) + end + + def test_get_contact_details_by_uuid + get '/api/v1/registrant/contacts/0aa54704-d6f7-4ca9-b8ca-2827d9a4e4eb', {}, @auth_headers + assert_equal(200, response.status) + + contact = JSON.parse(response.body, symbolize_names: true) + assert_equal('william@inbox.test', contact[:email]) + end + + def test_get_contact_details_by_uuid_returns_404_for_non_existent_contact + get '/api/v1/registrant/contacts/nonexistent-uuid', {}, @auth_headers + assert_equal(404, response.status) + + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [{ base: ['Contact not found'] }] }, response_json) end def test_root_does_not_accept_limit_higher_than_200 From 256d2b7de424b914c7cd36628d73f58de3420086 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 9 Aug 2018 15:24:21 +0300 Subject: [PATCH 52/60] Add test for error in business registry --- .../api/v1/registrant/contacts_controller.rb | 2 +- .../api/registrant/registrant_api_contacts_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/controllers/api/v1/registrant/contacts_controller.rb b/app/controllers/api/v1/registrant/contacts_controller.rb index 2c8a1f70e..5db175265 100644 --- a/app/controllers/api/v1/registrant/contacts_controller.rb +++ b/app/controllers/api/v1/registrant/contacts_controller.rb @@ -48,7 +48,7 @@ module Api @contacts_pool = Contact.where(id: available_contacts_ids) rescue Soap::Arireg::NotAvailableError => error Rails.logger.fatal("[EXCEPTION] #{error}") - render json: { errors: [{ base: ["Business Registry Not Available"] }] }, + render json: { errors: [{ base: ["Business Registry not available"] }] }, status: :service_unavailable and return end end diff --git a/test/integration/api/registrant/registrant_api_contacts_test.rb b/test/integration/api/registrant/registrant_api_contacts_test.rb index 28dd50d76..ddeaee9f3 100644 --- a/test/integration/api/registrant/registrant_api_contacts_test.rb +++ b/test/integration/api/registrant/registrant_api_contacts_test.rb @@ -50,6 +50,17 @@ class RegistrantApiContactsTest < ApplicationIntegrationTest assert_equal('william@inbox.test', contact[:email]) end + def test_root_returns_503_when_business_registry_is_not_available + raise_not_available = -> (a, b) { raise Soap::Arireg::NotAvailableError.new({}) } + BusinessRegistryCache.stub :fetch_by_ident_and_cc, raise_not_available do + get '/api/v1/registrant/contacts', {}, @auth_headers + + assert_equal(503, response.status) + response_json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [base: ['Business Registry not available']] }, response_json) + end + end + def test_get_contact_details_by_uuid_returns_404_for_non_existent_contact get '/api/v1/registrant/contacts/nonexistent-uuid', {}, @auth_headers assert_equal(404, response.status) From c186929be4704ba2f1ea26a3b4e86286dce1ac26 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 9 Aug 2018 15:28:43 +0300 Subject: [PATCH 53/60] Use single quote instead of double quotes --- app/controllers/api/v1/registrant/contacts_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/api/v1/registrant/contacts_controller.rb b/app/controllers/api/v1/registrant/contacts_controller.rb index 5db175265..de5ef9dcf 100644 --- a/app/controllers/api/v1/registrant/contacts_controller.rb +++ b/app/controllers/api/v1/registrant/contacts_controller.rb @@ -48,7 +48,7 @@ module Api @contacts_pool = Contact.where(id: available_contacts_ids) rescue Soap::Arireg::NotAvailableError => error Rails.logger.fatal("[EXCEPTION] #{error}") - render json: { errors: [{ base: ["Business Registry not available"] }] }, + render json: { errors: [{ base: ['Business Registry not available'] }] }, status: :service_unavailable and return end end From 2f776f51ac6e09cf1b614137b42d2eca9dfb9743 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 14 Aug 2018 09:02:25 +0300 Subject: [PATCH 54/60] It seems like I made a mistake with the API URL prefix in docs This should be fixed now. I decided on fixing the documentation instead of the actual implementation, as it has no testing footprint --- doc/registrant-api/v1/authentication.md | 8 ++++---- doc/registrant-api/v1/contact.md | 12 ++++++------ doc/registrant-api/v1/domain.md | 12 ++++++------ doc/registrant-api/v1/domain_lock.md | 8 ++++---- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/doc/registrant-api/v1/authentication.md b/doc/registrant-api/v1/authentication.md index 558bb1880..20ad6edd6 100644 --- a/doc/registrant-api/v1/authentication.md +++ b/doc/registrant-api/v1/authentication.md @@ -7,7 +7,7 @@ authentication. API client should perform authentication with eID according to the approriate documentation, and then pass on values from the webserver's certificate to the API server. -## POST /repp/v1/registrant/auth/eid +## POST /api/v1/registrant/auth/eid Returns a bearer token to be used for further API requests. Tokens are valid for 2 hours since their creation. @@ -24,7 +24,7 @@ Values in brackets represent values that come from the id card certificate. #### Request ``` -POST /repp/v1/auth/token HTTP/1.1 +POST /api/v1/auth/token HTTP/1.1 Accept: application/json Content-type: application/json @@ -48,7 +48,7 @@ Content-Type: application.json } ``` -## POST /repp/v1/auth/username -- NOT IMPLEMENTED +## POST /api/v1/auth/username -- NOT IMPLEMENTED #### Paramaters @@ -62,7 +62,7 @@ Values in brackets represent values that come from the id card certificate #### Request ``` -POST /repp/v1/auth/token HTTP/1.1 +POST /api/v1/auth/token HTTP/1.1 Accept: application/json Content-type: application/json ``` diff --git a/doc/registrant-api/v1/contact.md b/doc/registrant-api/v1/contact.md index ea28294d0..4e1c12bec 100644 --- a/doc/registrant-api/v1/contact.md +++ b/doc/registrant-api/v1/contact.md @@ -1,4 +1,4 @@ -## GET /repp/v1/registrant/contacts +## GET /api/v1/registrant/contacts Returns contacts of the current registrar. @@ -11,7 +11,7 @@ Returns contacts of the current registrar. #### Request ``` -GET /repp/v1/registrant/contacts?limit=1 HTTP/1.1 +GET /api/v1/registrant/contacts?limit=1 HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json @@ -59,13 +59,13 @@ Content-Type: application/json } ``` -## GET /repp/v1/registrant/contacts/$UUID +## GET /api/v1/registrant/contacts/$UUID Returns contacts of the current registrar. #### Request ``` -GET /repp/v1/registrant/contacts/84c62f3d-e56f-40fa-9ca4-dc0137778949 HTTP/1.1 +GET /api/v1/registrant/contacts/84c62f3d-e56f-40fa-9ca4-dc0137778949 HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json @@ -107,7 +107,7 @@ Content-Type: application/json } ``` -## PUT/PATCH /repp/v1/registrant/contacts/$UUID +## PATCH /api/v1/registrant/contacts/$UUID Update contact details for a contact. @@ -127,7 +127,7 @@ Update contact details for a contact. #### Request ``` -PUT /repp/v1/registrant/contacts/84c62f3d-e56f-40fa-9ca4-dc0137778949 HTTP/1.1 +PATCH /api/v1/registrant/contacts/84c62f3d-e56f-40fa-9ca4-dc0137778949 HTTP/1.1 Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Accept: application/json Content-type: application/json diff --git a/doc/registrant-api/v1/domain.md b/doc/registrant-api/v1/domain.md index 2e249423c..09495220d 100644 --- a/doc/registrant-api/v1/domain.md +++ b/doc/registrant-api/v1/domain.md @@ -1,6 +1,6 @@ # Domain related actions -## GET /repp/v1/registrant/domains +## GET /api/v1/registrant/domains Returns domains of the current registrant. @@ -15,7 +15,7 @@ Returns domains of the current registrant. #### Request ``` -GET repp/v1/registrant/domains?limit=1&details=true HTTP/1.1 +GET api/v1/registrant/domains?limit=1&details=true HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json @@ -70,14 +70,14 @@ Content-Type: application/json } ``` -## GET repp/v1/registrant/domains +## GET api/v1/registrant/domains Returns domain names with offset. #### Request ``` -GET repp/v1/registrant/domains?offset=1 HTTP/1.1 +GET api/v1/registrant/domains?offset=1 HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json @@ -96,14 +96,14 @@ Content-Type: application/json } ``` -## GET repp/v1/registrant/domains/$UUID +## GET api/v1/registrant/domains/$UUID Returns a single domain object. #### Request ``` -GET repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535 HTTP/1.1 +GET api/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535 HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json diff --git a/doc/registrant-api/v1/domain_lock.md b/doc/registrant-api/v1/domain_lock.md index 0237a11cb..5f275edb4 100644 --- a/doc/registrant-api/v1/domain_lock.md +++ b/doc/registrant-api/v1/domain_lock.md @@ -1,12 +1,12 @@ # Domain locks -## POST repp/v1/registrant/domains/$UUID/registry_lock +## POST api/v1/registrant/domains/$UUID/registry_lock Set a registry lock on a domain. #### Request ``` -POST repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535/registry_lock HTTP/1.1 +POST api/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535/registry_lock HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json @@ -82,13 +82,13 @@ Content-Type: application/json ``` -## DELETE repp/v1/registrant/domains/$UUID/registry_lock +## DELETE api/v1/registrant/domains/$UUID/registry_lock Remove a registry lock. #### Request ``` -DELETE repp/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535/registry_lock HTTP/1.1 +DELETE api/v1/registrant/domains/98d1083a-8863-4153-93e4-caee4a013535/registry_lock HTTP/1.1 Accept: application/json Authorization: Bearer Z2l0bGFiOmdoeXQ5ZTRmdQ== Content-Type: application/json From d4b0fecd4042c0e61aa43fdd6f921102a14e0ff9 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Tue, 14 Aug 2018 10:13:59 +0300 Subject: [PATCH 55/60] Get rid of CVE-2018-3769 by updating Grape --- Gemfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile.lock b/Gemfile.lock index a8d6434e6..3285380f7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -186,7 +186,7 @@ GEM thor (~> 0.14) globalid (0.4.1) activesupport (>= 4.2.0) - grape (1.0.3) + grape (1.1.0) activesupport builder mustermann-grape (~> 1.0.0) From b4b404888bd23c2f4a20ef88cb968916b26963e0 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 15 Aug 2018 12:25:19 +0300 Subject: [PATCH 56/60] Disallow deposits that are lower than 0.01 EUR --- .../registrar/deposits_controller.rb | 6 +- app/models/deposit.rb | 16 +++-- spec/models/deposit_spec.rb | 39 ------------ test/models/deposit_test.rb | 59 +++++++++++++++++++ .../registrar_area/invoices/new_test.rb | 10 +--- 5 files changed, 76 insertions(+), 54 deletions(-) delete mode 100644 spec/models/deposit_spec.rb create mode 100644 test/models/deposit_test.rb diff --git a/app/controllers/registrar/deposits_controller.rb b/app/controllers/registrar/deposits_controller.rb index ec6d13977..818e38c6d 100644 --- a/app/controllers/registrar/deposits_controller.rb +++ b/app/controllers/registrar/deposits_controller.rb @@ -10,12 +10,12 @@ class Registrar @deposit = Deposit.new(deposit_params.merge(registrar: current_user.registrar)) @invoice = @deposit.issue_prepayment_invoice - if @invoice&.persisted? + if @invoice flash[:notice] = t(:please_pay_the_following_invoice) redirect_to [:registrar, @invoice] else - flash.now[:alert] = t(:failed_to_create_record) - render 'new' + flash[:alert] = @deposit.errors.full_messages.join(', ') + redirect_to new_registrar_deposit_path end end diff --git a/app/models/deposit.rb b/app/models/deposit.rb index 23045196a..589856437 100644 --- a/app/models/deposit.rb +++ b/app/models/deposit.rb @@ -4,13 +4,17 @@ class Deposit extend ActiveModel::Naming include DisableHtml5Validation - attr_accessor :amount, :description, :registrar, :registrar_id + attr_accessor :description, :registrar, :registrar_id + attr_writer :amount validates :amount, :registrar, presence: true validate :validate_amount + def validate_amount - return if BigDecimal.new(amount) >= Setting.minimum_deposit - errors.add(:amount, I18n.t(:is_too_small_minimum_deposit_is, amount: Setting.minimum_deposit, currency: 'EUR')) + minimum_deposit = [0.01, Setting.minimum_deposit].max + return if amount >= minimum_deposit + errors.add(:amount, I18n.t(:is_too_small_minimum_deposit_is, amount: minimum_deposit, + currency: 'EUR')) end def initialize(attributes = {}) @@ -24,10 +28,12 @@ class Deposit end def amount - BigDecimal.new(@amount.to_s.sub(/,/, '.')) + return BigDecimal.new('0.0') if @amount.blank? + BigDecimal.new(@amount, 10) end def issue_prepayment_invoice - valid? && registrar.issue_prepayment_invoice(amount, description) + return unless valid? + registrar.issue_prepayment_invoice(amount, description) end end diff --git a/spec/models/deposit_spec.rb b/spec/models/deposit_spec.rb deleted file mode 100644 index ff77dbd98..000000000 --- a/spec/models/deposit_spec.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'rails_helper' - -describe Deposit do - context 'with invalid attribute' do - before :all do - @deposit = Deposit.new - end - - it 'should not be valid' do - @deposit.valid? - @deposit.errors.full_messages.should match_array([ - "Registrar is missing" - ]) - end - - it 'should have 0 amount' do - @deposit.amount.should == 0 - end - - it 'should not be presisted' do - @deposit.persisted?.should == false - end - - it 'should replace comma with point for 0' do - @deposit.amount = '0,0' - @deposit.amount.should == 0.0 - end - - it 'should replace comma with points' do - @deposit.amount = '10,11' - @deposit.amount.should == 10.11 - end - - it 'should work with float as well' do - @deposit.amount = 0.123 - @deposit.amount.should == 0.123 - end - end -end diff --git a/test/models/deposit_test.rb b/test/models/deposit_test.rb new file mode 100644 index 000000000..09f7de7f3 --- /dev/null +++ b/test/models/deposit_test.rb @@ -0,0 +1,59 @@ +require 'test_helper' + +class DepositTest < ActiveSupport::TestCase + def setup + super + + @deposit = Deposit.new(registrar: registrars(:bestnames)) + @minimum_deposit = Setting.minimum_deposit + Setting.minimum_deposit = 1.00 + end + + def teardown + super + + Setting.minimum_deposit = @minimum_deposit + end + + def test_validate_amount_cannot_be_lower_than_0_01 + Setting.minimum_deposit = 0.0 + @deposit.amount = -10 + refute(@deposit.valid?) + assert(@deposit.errors.full_messages.include?("Amount is too small. Minimum deposit is 0.01 EUR")) + end + + def test_validate_amount_cannot_be_lower_than_minimum_deposit + @deposit.amount = 0.10 + refute(@deposit.valid?) + + assert(@deposit.errors.full_messages.include?("Amount is too small. Minimum deposit is 1.0 EUR")) + end + + def test_registrar_must_be_set + deposit = Deposit.new(amount: 120) + refute(deposit.valid?) + + assert(deposit.errors.full_messages.include?("Registrar is missing")) + end + + def test_amount_is_converted_from_string + @deposit.amount = "12.00" + assert_equal(BigDecimal.new("12.00"), @deposit.amount) + + @deposit.amount = "12,00" + assert_equal(BigDecimal.new("12.00"), @deposit.amount) + end + + def test_amount_is_converted_from_float + @deposit.amount = 12.0044 + assert_equal(BigDecimal.new("12.0044"), @deposit.amount) + + @deposit.amount = 12.0144 + assert_equal(BigDecimal.new("12.0144"), @deposit.amount) + end + + def test_amount_is_converted_from_nil + @deposit.amount = nil + assert_equal(BigDecimal.new("0.00"), @deposit.amount) + end +end diff --git a/test/system/registrar_area/invoices/new_test.rb b/test/system/registrar_area/invoices/new_test.rb index b9b6b6db4..282b109dd 100644 --- a/test/system/registrar_area/invoices/new_test.rb +++ b/test/system/registrar_area/invoices/new_test.rb @@ -29,20 +29,16 @@ class NewInvoiceTest < ApplicationSystemTestCase assert_text 'Pay invoice' end - # This test case should fail once issue #651 gets fixed - def test_create_new_invoice_with_amount_0_goes_through + def test_create_new_invoice_fails_when_amount_is_0 visit registrar_invoices_path click_link_or_button 'Add deposit' fill_in 'Amount', with: '0.00' fill_in 'Description', with: 'My first invoice' - assert_difference 'Invoice.count', 1 do + assert_no_difference 'Invoice.count' do click_link_or_button 'Add' end - assert_text 'Please pay the following invoice' - assert_text 'Invoice no. 131050' - assert_text 'Subtotal 0,00 €' - assert_text 'Pay invoice' + assert_text 'Amount is too small. Minimum deposit is 0.01 EUR' end end From 0ea10452593cf5251b53fd0f95b476c23d896647 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 15 Aug 2018 12:46:36 +0300 Subject: [PATCH 57/60] Fix rubocop issues --- app/models/deposit.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/models/deposit.rb b/app/models/deposit.rb index 589856437..05197c5a1 100644 --- a/app/models/deposit.rb +++ b/app/models/deposit.rb @@ -14,7 +14,7 @@ class Deposit minimum_deposit = [0.01, Setting.minimum_deposit].max return if amount >= minimum_deposit errors.add(:amount, I18n.t(:is_too_small_minimum_deposit_is, amount: minimum_deposit, - currency: 'EUR')) + currency: 'EUR')) end def initialize(attributes = {}) @@ -28,8 +28,8 @@ class Deposit end def amount - return BigDecimal.new('0.0') if @amount.blank? - BigDecimal.new(@amount, 10) + return BigDecimal('0.0') if @amount.blank? + BigDecimal(@amount, 10) end def issue_prepayment_invoice From b8c082090e223e3a77f8c26f0dd56464db256fe2 Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 15 Aug 2018 16:32:42 +0300 Subject: [PATCH 58/60] Rename a variable from minimum_deposit to minimum_allowed_amount --- app/models/deposit.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/models/deposit.rb b/app/models/deposit.rb index 05197c5a1..41d59ac4c 100644 --- a/app/models/deposit.rb +++ b/app/models/deposit.rb @@ -11,9 +11,9 @@ class Deposit validate :validate_amount def validate_amount - minimum_deposit = [0.01, Setting.minimum_deposit].max - return if amount >= minimum_deposit - errors.add(:amount, I18n.t(:is_too_small_minimum_deposit_is, amount: minimum_deposit, + minimum_allowed_amount = [0.01, Setting.minimum_deposit].max + return if amount >= minimum_allowed_amount + errors.add(:amount, I18n.t(:is_too_small_minimum_deposit_is, amount: minimum_allowed_amount, currency: 'EUR')) end From c028c0e4771ac1f7815156a10b57d5790572693d Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Wed, 15 Aug 2018 20:15:17 +0300 Subject: [PATCH 59/60] Add more tests to deposit handling --- app/models/deposit.rb | 2 +- test/models/deposit_test.rb | 4 +-- .../registrar_area/invoices/new_test.rb | 29 +++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/app/models/deposit.rb b/app/models/deposit.rb index 41d59ac4c..a3b898047 100644 --- a/app/models/deposit.rb +++ b/app/models/deposit.rb @@ -29,7 +29,7 @@ class Deposit def amount return BigDecimal('0.0') if @amount.blank? - BigDecimal(@amount, 10) + BigDecimal(@amount.to_s.gsub(/,/, '.'), 10) end def issue_prepayment_invoice diff --git a/test/models/deposit_test.rb b/test/models/deposit_test.rb index 09f7de7f3..b7510b960 100644 --- a/test/models/deposit_test.rb +++ b/test/models/deposit_test.rb @@ -40,8 +40,8 @@ class DepositTest < ActiveSupport::TestCase @deposit.amount = "12.00" assert_equal(BigDecimal.new("12.00"), @deposit.amount) - @deposit.amount = "12,00" - assert_equal(BigDecimal.new("12.00"), @deposit.amount) + @deposit.amount = "12,11" + assert_equal(BigDecimal.new("12.11"), @deposit.amount) end def test_amount_is_converted_from_float diff --git a/test/system/registrar_area/invoices/new_test.rb b/test/system/registrar_area/invoices/new_test.rb index 282b109dd..a5a72fbe8 100644 --- a/test/system/registrar_area/invoices/new_test.rb +++ b/test/system/registrar_area/invoices/new_test.rb @@ -29,6 +29,22 @@ class NewInvoiceTest < ApplicationSystemTestCase assert_text 'Pay invoice' end + def test_create_new_invoice_with_comma_in_number + visit registrar_invoices_path + click_link_or_button 'Add deposit' + fill_in 'Amount', with: '200,00' + fill_in 'Description', with: 'My first invoice' + + assert_difference 'Invoice.count', 1 do + click_link_or_button 'Add' + end + + assert_text 'Please pay the following invoice' + assert_text 'Invoice no. 131050' + assert_text 'Subtotal 200,00 €' + assert_text 'Pay invoice' + end + def test_create_new_invoice_fails_when_amount_is_0 visit registrar_invoices_path click_link_or_button 'Add deposit' @@ -41,4 +57,17 @@ class NewInvoiceTest < ApplicationSystemTestCase assert_text 'Amount is too small. Minimum deposit is 0.01 EUR' end + + def test_create_new_invoice_fails_when_amount_is_negative + visit registrar_invoices_path + click_link_or_button 'Add deposit' + fill_in 'Amount', with: '-120.00' + fill_in 'Description', with: 'My first invoice' + + assert_no_difference 'Invoice.count' do + click_link_or_button 'Add' + end + + assert_text 'Amount is too small. Minimum deposit is 0.01 EUR' + end end From 066123bcf731fb568c1dda01c41344e1ec572bbc Mon Sep 17 00:00:00 2001 From: Maciej Szlosarczyk Date: Thu, 16 Aug 2018 13:33:09 +0300 Subject: [PATCH 60/60] Replace gsub with tr for better performance --- app/models/deposit.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/deposit.rb b/app/models/deposit.rb index a3b898047..2eff26bcc 100644 --- a/app/models/deposit.rb +++ b/app/models/deposit.rb @@ -29,7 +29,7 @@ class Deposit def amount return BigDecimal('0.0') if @amount.blank? - BigDecimal(@amount.to_s.gsub(/,/, '.'), 10) + BigDecimal(@amount.to_s.tr(',', '.'), 10) end def issue_prepayment_invoice
<%= APIUser.human_attribute_name :username %><%= APIUser.human_attribute_name :active %><%= ApiUser.human_attribute_name :username %><%= ApiUser.human_attribute_name :active %>