mirror of
https://github.com/cisagov/manage.get.gov.git
synced 2025-07-21 18:25:58 +02:00
MERGE main to nl/981
This commit is contained in:
commit
f379a99127
38 changed files with 2550 additions and 964 deletions
|
@ -4,7 +4,7 @@ Date: 2023-13-10
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
In Review
|
Accepted
|
||||||
|
|
||||||
## Context
|
## Context
|
||||||
|
|
||||||
|
|
|
@ -46,7 +46,7 @@ This is a standard Django secret key. See Django documentation for tips on gener
|
||||||
|
|
||||||
This is the base64 encoded private key used in the OpenID Connect authentication flow with Login.gov. It is used to sign a token during user login; the signature is examined by Login.gov before their API grants access to user data.
|
This is the base64 encoded private key used in the OpenID Connect authentication flow with Login.gov. It is used to sign a token during user login; the signature is examined by Login.gov before their API grants access to user data.
|
||||||
|
|
||||||
Generate a new key using this command (or whatever is most recently recommended by Login.gov):
|
Generate a new key using this command (or whatever is most recently [recommended by Login.gov](https://developers.login.gov/testing/#creating-a-public-certificate)):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
openssl req -nodes -x509 -days 365 -newkey rsa:2048 -keyout private.pem -out public.crt
|
openssl req -nodes -x509 -days 365 -newkey rsa:2048 -keyout private.pem -out public.crt
|
||||||
|
|
|
@ -25,7 +25,10 @@ django-phonenumber-field = {extras = ["phonenumberslite"], version = "*"}
|
||||||
boto3 = "*"
|
boto3 = "*"
|
||||||
typing-extensions ='*'
|
typing-extensions ='*'
|
||||||
django-login-required-middleware = "*"
|
django-login-required-middleware = "*"
|
||||||
|
greenlet = "*"
|
||||||
|
gevent = "*"
|
||||||
fred-epplib = {git = "https://github.com/cisagov/epplib.git", ref = "master"}
|
fred-epplib = {git = "https://github.com/cisagov/epplib.git", ref = "master"}
|
||||||
|
geventconnpool = {git = "https://github.com/rasky/geventconnpool.git", ref = "1bbb93a714a331a069adf27265fe582d9ba7ecd4"}
|
||||||
|
|
||||||
[dev-packages]
|
[dev-packages]
|
||||||
django-debug-toolbar = "*"
|
django-debug-toolbar = "*"
|
||||||
|
|
1707
src/Pipfile.lock
generated
1707
src/Pipfile.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -5,14 +5,13 @@ import json
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from django.test import RequestFactory
|
from django.test import RequestFactory
|
||||||
|
|
||||||
from ..views import available, in_domains
|
from ..views import available, check_domain_available
|
||||||
from .common import less_console_noise
|
from .common import less_console_noise
|
||||||
from registrar.tests.common import MockEppLib
|
from registrar.tests.common import MockEppLib
|
||||||
from unittest.mock import call
|
from unittest.mock import call
|
||||||
|
|
||||||
from epplibwrapper import (
|
from epplibwrapper import (
|
||||||
commands,
|
commands,
|
||||||
RegistryError,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
API_BASE_PATH = "/api/v1/available/"
|
API_BASE_PATH = "/api/v1/available/"
|
||||||
|
@ -37,10 +36,10 @@ class AvailableViewTest(MockEppLib):
|
||||||
response_object = json.loads(response.content)
|
response_object = json.loads(response.content)
|
||||||
self.assertIn("available", response_object)
|
self.assertIn("available", response_object)
|
||||||
|
|
||||||
def test_in_domains_makes_calls_(self):
|
def test_domain_available_makes_calls_(self):
|
||||||
"""Domain searches successfully make correct mock EPP calls"""
|
"""Domain searches successfully make correct mock EPP calls"""
|
||||||
gsa_available = in_domains("gsa.gov")
|
gsa_available = check_domain_available("gsa.gov")
|
||||||
igorville_available = in_domains("igorvilleremixed.gov")
|
igorville_available = check_domain_available("igorville.gov")
|
||||||
|
|
||||||
"""Domain searches successfully make mock EPP calls"""
|
"""Domain searches successfully make mock EPP calls"""
|
||||||
self.mockedSendFunction.assert_has_calls(
|
self.mockedSendFunction.assert_has_calls(
|
||||||
|
@ -53,29 +52,32 @@ class AvailableViewTest(MockEppLib):
|
||||||
),
|
),
|
||||||
call(
|
call(
|
||||||
commands.CheckDomain(
|
commands.CheckDomain(
|
||||||
["igorvilleremixed.gov"],
|
["igorville.gov"],
|
||||||
),
|
),
|
||||||
cleaned=True,
|
cleaned=True,
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
"""Domain searches return correct availability results"""
|
"""Domain searches return correct availability results"""
|
||||||
self.assertTrue(gsa_available)
|
self.assertFalse(gsa_available)
|
||||||
self.assertFalse(igorville_available)
|
self.assertTrue(igorville_available)
|
||||||
|
|
||||||
def test_in_domains_capitalized(self):
|
def test_domain_available_capitalized(self):
|
||||||
"""Domain searches work without case sensitivity"""
|
"""Domain searches work without case sensitivity"""
|
||||||
self.assertTrue(in_domains("gsa.gov"))
|
self.assertFalse(check_domain_available("gsa.gov"))
|
||||||
# input is lowercased so GSA.GOV should be found
|
self.assertTrue(check_domain_available("igorville.gov"))
|
||||||
self.assertTrue(in_domains("GSA.gov"))
|
# input is lowercased so GSA.GOV should also not be available
|
||||||
|
self.assertFalse(check_domain_available("GSA.gov"))
|
||||||
|
# input is lowercased so IGORVILLE.GOV should also not be available
|
||||||
|
self.assertFalse(check_domain_available("IGORVILLE.gov"))
|
||||||
|
|
||||||
def test_in_domains_dotgov(self):
|
def test_domain_available_dotgov(self):
|
||||||
"""Domain searches work without trailing .gov"""
|
"""Domain searches work without trailing .gov"""
|
||||||
self.assertTrue(in_domains("gsa"))
|
self.assertFalse(check_domain_available("gsa"))
|
||||||
# input is lowercased so GSA.GOV should be found
|
# input is lowercased so GSA.GOV should be found
|
||||||
self.assertTrue(in_domains("GSA"))
|
self.assertFalse(check_domain_available("GSA"))
|
||||||
# This domain should not have been registered
|
# This domain should be available to register
|
||||||
self.assertFalse(in_domains("igorvilleremixed"))
|
self.assertTrue(check_domain_available("igorville"))
|
||||||
|
|
||||||
def test_not_available_domain(self):
|
def test_not_available_domain(self):
|
||||||
"""gsa.gov is not available"""
|
"""gsa.gov is not available"""
|
||||||
|
@ -85,17 +87,17 @@ class AvailableViewTest(MockEppLib):
|
||||||
self.assertFalse(json.loads(response.content)["available"])
|
self.assertFalse(json.loads(response.content)["available"])
|
||||||
|
|
||||||
def test_available_domain(self):
|
def test_available_domain(self):
|
||||||
"""igorvilleremixed.gov is still available"""
|
"""igorville.gov is still available"""
|
||||||
request = self.factory.get(API_BASE_PATH + "igorvilleremixed.gov")
|
request = self.factory.get(API_BASE_PATH + "igorville.gov")
|
||||||
request.user = self.user
|
request.user = self.user
|
||||||
response = available(request, domain="igorvilleremixed.gov")
|
response = available(request, domain="igorville.gov")
|
||||||
self.assertTrue(json.loads(response.content)["available"])
|
self.assertTrue(json.loads(response.content)["available"])
|
||||||
|
|
||||||
def test_available_domain_dotgov(self):
|
def test_available_domain_dotgov(self):
|
||||||
"""igorvilleremixed.gov is still available even without the .gov suffix"""
|
"""igorville.gov is still available even without the .gov suffix"""
|
||||||
request = self.factory.get(API_BASE_PATH + "igorvilleremixed")
|
request = self.factory.get(API_BASE_PATH + "igorville")
|
||||||
request.user = self.user
|
request.user = self.user
|
||||||
response = available(request, domain="igorvilleremixed")
|
response = available(request, domain="igorville")
|
||||||
self.assertTrue(json.loads(response.content)["available"])
|
self.assertTrue(json.loads(response.content)["available"])
|
||||||
|
|
||||||
def test_error_handling(self):
|
def test_error_handling(self):
|
||||||
|
@ -105,8 +107,7 @@ class AvailableViewTest(MockEppLib):
|
||||||
request.user = self.user
|
request.user = self.user
|
||||||
response = available(request, domain=bad_string)
|
response = available(request, domain=bad_string)
|
||||||
self.assertFalse(json.loads(response.content)["available"])
|
self.assertFalse(json.loads(response.content)["available"])
|
||||||
# domain set to raise error successfully raises error
|
# domain set to raise error returns false for availability
|
||||||
with self.assertRaises(RegistryError):
|
|
||||||
error_domain_available = available(request, "errordomain.gov")
|
error_domain_available = available(request, "errordomain.gov")
|
||||||
self.assertFalse(json.loads(error_domain_available.content)["available"])
|
self.assertFalse(json.loads(error_domain_available.content)["available"])
|
||||||
|
|
||||||
|
|
|
@ -5,6 +5,8 @@ from django.http import JsonResponse
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
from login_required import login_not_required
|
||||||
|
|
||||||
from cachetools.func import ttl_cache
|
from cachetools.func import ttl_cache
|
||||||
|
|
||||||
|
|
||||||
|
@ -23,6 +25,7 @@ DOMAIN_API_MESSAGES = {
|
||||||
"invalid": "Enter a domain using only letters,"
|
"invalid": "Enter a domain using only letters,"
|
||||||
" numbers, or hyphens (though we don't recommend using hyphens).",
|
" numbers, or hyphens (though we don't recommend using hyphens).",
|
||||||
"success": "That domain is available!",
|
"success": "That domain is available!",
|
||||||
|
"error": "Error finding domain availability.",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -50,22 +53,26 @@ def _domains():
|
||||||
return domains
|
return domains
|
||||||
|
|
||||||
|
|
||||||
def in_domains(domain):
|
def check_domain_available(domain):
|
||||||
"""Return true if the given domain is in the domains list.
|
"""Return true if the given domain is available.
|
||||||
|
|
||||||
The given domain is lowercased to match against the domains list. If the
|
The given domain is lowercased to match against the domains list. If the
|
||||||
given domain doesn't end with .gov, ".gov" is added when looking for
|
given domain doesn't end with .gov, ".gov" is added when looking for
|
||||||
a match.
|
a match.
|
||||||
"""
|
"""
|
||||||
Domain = apps.get_model("registrar.Domain")
|
Domain = apps.get_model("registrar.Domain")
|
||||||
|
try:
|
||||||
if domain.endswith(".gov"):
|
if domain.endswith(".gov"):
|
||||||
return Domain.available(domain)
|
return Domain.available(domain)
|
||||||
else:
|
else:
|
||||||
# domain search string doesn't end with .gov, add it on here
|
# domain search string doesn't end with .gov, add it on here
|
||||||
return Domain.available(domain + ".gov")
|
return Domain.available(domain + ".gov")
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(["GET"])
|
@require_http_methods(["GET"])
|
||||||
|
@login_not_required
|
||||||
def available(request, domain=""):
|
def available(request, domain=""):
|
||||||
"""Is a given domain available or not.
|
"""Is a given domain available or not.
|
||||||
|
|
||||||
|
@ -83,11 +90,16 @@ def available(request, domain=""):
|
||||||
{"available": False, "message": DOMAIN_API_MESSAGES["invalid"]}
|
{"available": False, "message": DOMAIN_API_MESSAGES["invalid"]}
|
||||||
)
|
)
|
||||||
# a domain is available if it is NOT in the list of current domains
|
# a domain is available if it is NOT in the list of current domains
|
||||||
if in_domains(domain):
|
try:
|
||||||
return JsonResponse(
|
if check_domain_available(domain):
|
||||||
{"available": False, "message": DOMAIN_API_MESSAGES["unavailable"]}
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{"available": True, "message": DOMAIN_API_MESSAGES["success"]}
|
{"available": True, "message": DOMAIN_API_MESSAGES["success"]}
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
return JsonResponse(
|
||||||
|
{"available": False, "message": DOMAIN_API_MESSAGES["unavailable"]}
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
return JsonResponse(
|
||||||
|
{"available": False, "message": DOMAIN_API_MESSAGES["error"]}
|
||||||
|
)
|
||||||
|
|
|
@ -45,7 +45,7 @@ except NameError:
|
||||||
# Attn: these imports should NOT be at the top of the file
|
# Attn: these imports should NOT be at the top of the file
|
||||||
try:
|
try:
|
||||||
from .client import CLIENT, commands
|
from .client import CLIENT, commands
|
||||||
from .errors import RegistryError, ErrorCode, CANNOT_CONTACT_REGISTRY, GENERIC_ERROR
|
from .errors import RegistryError, ErrorCode
|
||||||
from epplib.models import common, info
|
from epplib.models import common, info
|
||||||
from epplib.responses import extensions
|
from epplib.responses import extensions
|
||||||
from epplib import responses
|
from epplib import responses
|
||||||
|
@ -61,6 +61,4 @@ __all__ = [
|
||||||
"info",
|
"info",
|
||||||
"ErrorCode",
|
"ErrorCode",
|
||||||
"RegistryError",
|
"RegistryError",
|
||||||
"CANNOT_CONTACT_REGISTRY",
|
|
||||||
"GENERIC_ERROR",
|
|
||||||
]
|
]
|
||||||
|
|
|
@ -1,7 +1,10 @@
|
||||||
"""Provide a wrapper around epplib to handle authentication and errors."""
|
"""Provide a wrapper around epplib to handle authentication and errors."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from time import sleep
|
from time import sleep
|
||||||
|
from gevent import Timeout
|
||||||
|
from epplibwrapper.utility.pool_status import PoolStatus
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from epplib.client import Client
|
from epplib.client import Client
|
||||||
|
@ -16,6 +19,7 @@ from django.conf import settings
|
||||||
from .cert import Cert, Key
|
from .cert import Cert, Key
|
||||||
from .errors import LoginError, RegistryError
|
from .errors import LoginError, RegistryError
|
||||||
from .socket import Socket
|
from .socket import Socket
|
||||||
|
from .utility.pool import EPPConnectionPool
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -39,9 +43,8 @@ class EPPLibWrapper:
|
||||||
ATTN: This should not be used directly. Use `Domain` from domain.py.
|
ATTN: This should not be used directly. Use `Domain` from domain.py.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self, start_connection_pool=True) -> None:
|
||||||
"""Initialize settings which will be used for all connections."""
|
"""Initialize settings which will be used for all connections."""
|
||||||
|
|
||||||
# prepare (but do not send) a Login command
|
# prepare (but do not send) a Login command
|
||||||
self._login = commands.Login(
|
self._login = commands.Login(
|
||||||
cl_id=settings.SECRET_REGISTRY_CL_ID,
|
cl_id=settings.SECRET_REGISTRY_CL_ID,
|
||||||
|
@ -51,6 +54,7 @@ class EPPLibWrapper:
|
||||||
"urn:ietf:params:xml:ns:contact-1.0",
|
"urn:ietf:params:xml:ns:contact-1.0",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
# establish a client object with a TCP socket transport
|
# establish a client object with a TCP socket transport
|
||||||
self._client = Client(
|
self._client = Client(
|
||||||
SocketTransport(
|
SocketTransport(
|
||||||
|
@ -60,37 +64,77 @@ class EPPLibWrapper:
|
||||||
password=settings.SECRET_REGISTRY_KEY_PASSPHRASE,
|
password=settings.SECRET_REGISTRY_KEY_PASSPHRASE,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
# prepare a context manager which will connect and login when invoked
|
|
||||||
# (it will also logout and disconnect when the context manager exits)
|
self.pool_options = {
|
||||||
self._connect = Socket(self._client, self._login)
|
# Pool size
|
||||||
|
"size": settings.EPP_CONNECTION_POOL_SIZE,
|
||||||
|
# Which errors the pool should look out for.
|
||||||
|
# Avoid changing this unless necessary,
|
||||||
|
# it can and will break things.
|
||||||
|
"exc_classes": (TransportError,),
|
||||||
|
# Occasionally pings the registry to keep the connection alive.
|
||||||
|
# Value in seconds => (keepalive / size)
|
||||||
|
"keepalive": settings.POOL_KEEP_ALIVE,
|
||||||
|
}
|
||||||
|
|
||||||
|
self._pool = None
|
||||||
|
|
||||||
|
# Tracks the status of the pool
|
||||||
|
self.pool_status = PoolStatus()
|
||||||
|
|
||||||
|
if start_connection_pool:
|
||||||
|
self.start_connection_pool()
|
||||||
|
|
||||||
def _send(self, command):
|
def _send(self, command):
|
||||||
"""Helper function used by `send`."""
|
"""Helper function used by `send`."""
|
||||||
try:
|
|
||||||
cmd_type = command.__class__.__name__
|
cmd_type = command.__class__.__name__
|
||||||
with self._connect as wire:
|
|
||||||
response = wire.send(command)
|
# Start a timeout to check if the pool is hanging
|
||||||
|
timeout = Timeout(settings.POOL_TIMEOUT)
|
||||||
|
timeout.start()
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not self.pool_status.connection_success:
|
||||||
|
raise LoginError(
|
||||||
|
"Couldn't connect to the registry after three attempts"
|
||||||
|
)
|
||||||
|
with self._pool.get() as connection:
|
||||||
|
response = connection.send(command)
|
||||||
|
except Timeout as t:
|
||||||
|
# If more than one pool exists,
|
||||||
|
# multiple timeouts can be floating around.
|
||||||
|
# We need to be specific as to which we are targeting.
|
||||||
|
if t is timeout:
|
||||||
|
# Flag that the pool is frozen,
|
||||||
|
# then restart the pool.
|
||||||
|
self.pool_status.pool_hanging = True
|
||||||
|
self.start_connection_pool()
|
||||||
except (ValueError, ParsingError) as err:
|
except (ValueError, ParsingError) as err:
|
||||||
message = "%s failed to execute due to some syntax error."
|
message = f"{cmd_type} failed to execute due to some syntax error."
|
||||||
logger.warning(message, cmd_type, exc_info=True)
|
logger.error(f"{message} Error: {err}", exc_info=True)
|
||||||
raise RegistryError(message) from err
|
raise RegistryError(message) from err
|
||||||
except TransportError as err:
|
except TransportError as err:
|
||||||
message = "%s failed to execute due to a connection error."
|
message = f"{cmd_type} failed to execute due to a connection error."
|
||||||
logger.warning(message, cmd_type, exc_info=True)
|
logger.error(f"{message} Error: {err}", exc_info=True)
|
||||||
raise RegistryError(message) from err
|
raise RegistryError(message) from err
|
||||||
except LoginError as err:
|
except LoginError as err:
|
||||||
message = "%s failed to execute due to a registry login error."
|
# For linter due to it not liking this line length
|
||||||
logger.warning(message, cmd_type, exc_info=True)
|
text = "failed to execute due to a registry login error."
|
||||||
|
message = f"{cmd_type} {text}"
|
||||||
|
logger.error(f"{message} Error: {err}", exc_info=True)
|
||||||
raise RegistryError(message) from err
|
raise RegistryError(message) from err
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
message = "%s failed to execute due to an unknown error." % err
|
message = f"{cmd_type} failed to execute due to an unknown error."
|
||||||
logger.warning(message, cmd_type, exc_info=True)
|
logger.error(f"{message} Error: {err}", exc_info=True)
|
||||||
raise RegistryError(message) from err
|
raise RegistryError(message) from err
|
||||||
else:
|
else:
|
||||||
if response.code >= 2000:
|
if response.code >= 2000:
|
||||||
raise RegistryError(response.msg, code=response.code)
|
raise RegistryError(response.msg, code=response.code)
|
||||||
else:
|
else:
|
||||||
return response
|
return response
|
||||||
|
finally:
|
||||||
|
# Close the timeout no matter what happens
|
||||||
|
timeout.close()
|
||||||
|
|
||||||
def send(self, command, *, cleaned=False):
|
def send(self, command, *, cleaned=False):
|
||||||
"""Login, send the command, then close the connection. Tries 3 times."""
|
"""Login, send the command, then close the connection. Tries 3 times."""
|
||||||
|
@ -98,6 +142,23 @@ class EPPLibWrapper:
|
||||||
if not cleaned:
|
if not cleaned:
|
||||||
raise ValueError("Please sanitize user input before sending it.")
|
raise ValueError("Please sanitize user input before sending it.")
|
||||||
|
|
||||||
|
# Reopen the pool if its closed
|
||||||
|
# Only occurs when a login error is raised, after connection is successful
|
||||||
|
if not self.pool_status.pool_running:
|
||||||
|
# We want to reopen the connection pool,
|
||||||
|
# but we don't want the end user to wait while it opens.
|
||||||
|
# Raise syntax doesn't allow this, so we use a try/catch
|
||||||
|
# block.
|
||||||
|
try:
|
||||||
|
logger.error("Can't contact the Registry. Pool was not running.")
|
||||||
|
raise RegistryError("Can't contact the Registry. Pool was not running.")
|
||||||
|
except RegistryError as err:
|
||||||
|
raise err
|
||||||
|
finally:
|
||||||
|
# Code execution will halt after here.
|
||||||
|
# The end user will need to recall .send.
|
||||||
|
self.start_connection_pool()
|
||||||
|
|
||||||
counter = 0 # we'll try 3 times
|
counter = 0 # we'll try 3 times
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
@ -109,11 +170,73 @@ class EPPLibWrapper:
|
||||||
else: # don't try again
|
else: # don't try again
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
|
def get_pool(self):
|
||||||
|
"""Get the current pool instance"""
|
||||||
|
return self._pool
|
||||||
|
|
||||||
|
def _create_pool(self, client, login, options):
|
||||||
|
"""Creates and returns new pool instance"""
|
||||||
|
return EPPConnectionPool(client, login, options)
|
||||||
|
|
||||||
|
def start_connection_pool(self, restart_pool_if_exists=True):
|
||||||
|
"""Starts a connection pool for the registry.
|
||||||
|
|
||||||
|
restart_pool_if_exists -> bool:
|
||||||
|
If an instance of the pool already exists,
|
||||||
|
then then that instance will be killed first.
|
||||||
|
It is generally recommended to keep this enabled.
|
||||||
|
"""
|
||||||
|
# Since we reuse the same creds for each pool, we can test on
|
||||||
|
# one socket, and if successful, then we know we can connect.
|
||||||
|
if not self._test_registry_connection_success():
|
||||||
|
logger.warning("Cannot contact the Registry")
|
||||||
|
self.pool_status.connection_success = False
|
||||||
|
else:
|
||||||
|
self.pool_status.connection_success = True
|
||||||
|
|
||||||
|
# If this function is reinvoked, then ensure
|
||||||
|
# that we don't have duplicate data sitting around.
|
||||||
|
if self._pool is not None and restart_pool_if_exists:
|
||||||
|
logger.info("Connection pool restarting...")
|
||||||
|
self.kill_pool()
|
||||||
|
|
||||||
|
self._pool = self._create_pool(self._client, self._login, self.pool_options)
|
||||||
|
|
||||||
|
self.pool_status.pool_running = True
|
||||||
|
self.pool_status.pool_hanging = False
|
||||||
|
|
||||||
|
logger.info("Connection pool started")
|
||||||
|
|
||||||
|
def kill_pool(self):
|
||||||
|
"""Kills the existing pool. Use this instead
|
||||||
|
of self._pool = None, as that doesn't clear
|
||||||
|
gevent instances."""
|
||||||
|
if self._pool is not None:
|
||||||
|
self._pool.kill_all_connections()
|
||||||
|
self._pool = None
|
||||||
|
self.pool_status.pool_running = False
|
||||||
|
return None
|
||||||
|
logger.info("kill_pool() was invoked but there was no pool to delete")
|
||||||
|
|
||||||
|
def _test_registry_connection_success(self):
|
||||||
|
"""Check that determines if our login
|
||||||
|
credentials are valid, and/or if the Registrar
|
||||||
|
can be contacted
|
||||||
|
"""
|
||||||
|
socket = Socket(self._client, self._login)
|
||||||
|
can_login = False
|
||||||
|
|
||||||
|
# Something went wrong if this doesn't exist
|
||||||
|
if hasattr(socket, "test_connection_success"):
|
||||||
|
can_login = socket.test_connection_success()
|
||||||
|
|
||||||
|
return can_login
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Initialize epplib
|
# Initialize epplib
|
||||||
CLIENT = EPPLibWrapper()
|
CLIENT = EPPLibWrapper()
|
||||||
logger.debug("registry client initialized")
|
logger.info("registry client initialized")
|
||||||
except Exception:
|
except Exception:
|
||||||
CLIENT = None # type: ignore
|
CLIENT = None # type: ignore
|
||||||
logger.warning(
|
logger.warning(
|
||||||
|
|
|
@ -1,8 +1,5 @@
|
||||||
from enum import IntEnum
|
from enum import IntEnum
|
||||||
|
|
||||||
CANNOT_CONTACT_REGISTRY = "Update failed. Cannot contact the registry."
|
|
||||||
GENERIC_ERROR = "Value entered was wrong."
|
|
||||||
|
|
||||||
|
|
||||||
class ErrorCode(IntEnum):
|
class ErrorCode(IntEnum):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
import logging
|
import logging
|
||||||
|
from time import sleep
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from epplib import commands
|
from epplib import commands
|
||||||
|
from epplib.client import Client
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -14,24 +16,84 @@ logger = logging.getLogger(__name__)
|
||||||
class Socket:
|
class Socket:
|
||||||
"""Context manager which establishes a TCP connection with registry."""
|
"""Context manager which establishes a TCP connection with registry."""
|
||||||
|
|
||||||
def __init__(self, client, login) -> None:
|
def __init__(self, client: Client, login: commands.Login) -> None:
|
||||||
"""Save the epplib client and login details."""
|
"""Save the epplib client and login details."""
|
||||||
self.client = client
|
self.client = client
|
||||||
self.login = login
|
self.login = login
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
|
"""Runs connect(), which opens a connection with EPPLib."""
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
def __exit__(self, *args, **kwargs):
|
||||||
|
"""Runs disconnect(), which closes a connection with EPPLib."""
|
||||||
|
self.disconnect()
|
||||||
|
|
||||||
|
def connect(self):
|
||||||
"""Use epplib to connect."""
|
"""Use epplib to connect."""
|
||||||
self.client.connect()
|
self.client.connect()
|
||||||
response = self.client.send(self.login)
|
response = self.client.send(self.login)
|
||||||
if response.code >= 2000:
|
if self.is_login_error(response.code):
|
||||||
self.client.close()
|
self.client.close()
|
||||||
raise LoginError(response.msg)
|
raise LoginError(response.msg)
|
||||||
return self.client
|
return self.client
|
||||||
|
|
||||||
def __exit__(self, *args, **kwargs):
|
def disconnect(self):
|
||||||
"""Close the connection."""
|
"""Close the connection."""
|
||||||
try:
|
try:
|
||||||
self.client.send(commands.Logout())
|
self.client.send(commands.Logout())
|
||||||
self.client.close()
|
self.client.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.warning("Connection to registry was not cleanly closed.")
|
logger.warning("Connection to registry was not cleanly closed.")
|
||||||
|
|
||||||
|
def send(self, command):
|
||||||
|
"""Sends a command to the registry.
|
||||||
|
If the RegistryError code is >= 2000,
|
||||||
|
then this function raises a LoginError.
|
||||||
|
The calling function should handle this."""
|
||||||
|
response = self.client.send(command)
|
||||||
|
if self.is_login_error(response.code):
|
||||||
|
self.client.close()
|
||||||
|
raise LoginError(response.msg)
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
def is_login_error(self, code):
|
||||||
|
"""Returns the result of code >= 2000 for RegistryError.
|
||||||
|
This indicates that something weird happened on the Registry,
|
||||||
|
and that we should return a LoginError."""
|
||||||
|
return code >= 2000
|
||||||
|
|
||||||
|
def test_connection_success(self):
|
||||||
|
"""Tests if a successful connection can be made with the registry.
|
||||||
|
Tries 3 times."""
|
||||||
|
# Something went wrong if this doesn't exist
|
||||||
|
if not hasattr(self.client, "connect"):
|
||||||
|
logger.warning("self.client does not have a connect attribute")
|
||||||
|
return False
|
||||||
|
|
||||||
|
counter = 0 # we'll try 3 times
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
self.client.connect()
|
||||||
|
response = self.client.send(self.login)
|
||||||
|
except LoginError as err:
|
||||||
|
if err.should_retry() and counter < 3:
|
||||||
|
counter += 1
|
||||||
|
sleep((counter * 50) / 1000) # sleep 50 ms to 150 ms
|
||||||
|
else: # don't try again
|
||||||
|
return False
|
||||||
|
# Occurs when an invalid creds are passed in - such as on localhost
|
||||||
|
except OSError as err:
|
||||||
|
logger.error(err)
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
self.disconnect()
|
||||||
|
|
||||||
|
# If we encounter a login error, fail
|
||||||
|
if self.is_login_error(response.code):
|
||||||
|
logger.warning("A login error was found in test_connection_success")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Otherwise, just return true
|
||||||
|
return True
|
||||||
|
|
0
src/epplibwrapper/tests/__init__.py
Normal file
0
src/epplibwrapper/tests/__init__.py
Normal file
258
src/epplibwrapper/tests/test_pool.py
Normal file
258
src/epplibwrapper/tests/test_pool.py
Normal file
|
@ -0,0 +1,258 @@
|
||||||
|
import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
from dateutil.tz import tzlocal # type: ignore
|
||||||
|
from django.test import TestCase
|
||||||
|
from epplibwrapper.client import EPPLibWrapper
|
||||||
|
from epplibwrapper.errors import RegistryError
|
||||||
|
from epplibwrapper.socket import Socket
|
||||||
|
from epplibwrapper.utility.pool import EPPConnectionPool
|
||||||
|
from registrar.models.domain import registry
|
||||||
|
from contextlib import ExitStack
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
try:
|
||||||
|
from epplib import commands
|
||||||
|
from epplib.client import Client
|
||||||
|
from epplib.exceptions import TransportError
|
||||||
|
from epplib.transport import SocketTransport
|
||||||
|
from epplib.models import common, info
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class TestConnectionPool(TestCase):
|
||||||
|
"""Tests for our connection pooling behaviour"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
# Mimic the settings added to settings.py
|
||||||
|
self.pool_options = {
|
||||||
|
# Current pool size
|
||||||
|
"size": 1,
|
||||||
|
# Which errors the pool should look out for
|
||||||
|
"exc_classes": (TransportError,),
|
||||||
|
# Occasionally pings the registry to keep the connection alive.
|
||||||
|
# Value in seconds => (keepalive / size)
|
||||||
|
"keepalive": 60,
|
||||||
|
}
|
||||||
|
|
||||||
|
def fake_socket(self, login, client):
|
||||||
|
# Linter reasons
|
||||||
|
pw = "none"
|
||||||
|
# Create a fake client object
|
||||||
|
fake_client = Client(
|
||||||
|
SocketTransport(
|
||||||
|
"none",
|
||||||
|
cert_file="path/to/cert_file",
|
||||||
|
key_file="path/to/key_file",
|
||||||
|
password=pw,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return Socket(fake_client, MagicMock())
|
||||||
|
|
||||||
|
def patch_success(self):
|
||||||
|
return True
|
||||||
|
|
||||||
|
def fake_send(self, command, cleaned=None):
|
||||||
|
mock = MagicMock(
|
||||||
|
code=1000,
|
||||||
|
msg="Command completed successfully",
|
||||||
|
res_data=None,
|
||||||
|
cl_tr_id="xkw1uo#2023-10-17T15:29:09.559376",
|
||||||
|
sv_tr_id="5CcH4gxISuGkq8eqvr1UyQ==-35a",
|
||||||
|
extensions=[],
|
||||||
|
msg_q=None,
|
||||||
|
)
|
||||||
|
return mock
|
||||||
|
|
||||||
|
def fake_client(mock_client):
|
||||||
|
pw = "none"
|
||||||
|
client = Client(
|
||||||
|
SocketTransport(
|
||||||
|
"none",
|
||||||
|
cert_file="path/to/cert_file",
|
||||||
|
key_file="path/to/key_file",
|
||||||
|
password=pw,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return client
|
||||||
|
|
||||||
|
@patch.object(EPPLibWrapper, "_test_registry_connection_success", patch_success)
|
||||||
|
def test_pool_sends_data(self):
|
||||||
|
"""A .send is invoked on the pool successfully"""
|
||||||
|
expected_result = {
|
||||||
|
"cl_tr_id": None,
|
||||||
|
"code": 1000,
|
||||||
|
"extensions": [],
|
||||||
|
"msg": "Command completed successfully",
|
||||||
|
"msg_q": None,
|
||||||
|
"res_data": [
|
||||||
|
info.InfoDomainResultData(
|
||||||
|
roid="DF1340360-GOV",
|
||||||
|
statuses=[
|
||||||
|
common.Status(
|
||||||
|
state="serverTransferProhibited",
|
||||||
|
description=None,
|
||||||
|
lang="en",
|
||||||
|
),
|
||||||
|
common.Status(state="inactive", description=None, lang="en"),
|
||||||
|
],
|
||||||
|
cl_id="gov2023-ote",
|
||||||
|
cr_id="gov2023-ote",
|
||||||
|
cr_date=datetime.datetime(
|
||||||
|
2023, 8, 15, 23, 56, 36, tzinfo=tzlocal()
|
||||||
|
),
|
||||||
|
up_id="gov2023-ote",
|
||||||
|
up_date=datetime.datetime(2023, 8, 17, 2, 3, 19, tzinfo=tzlocal()),
|
||||||
|
tr_date=None,
|
||||||
|
name="test3.gov",
|
||||||
|
registrant="TuaWnx9hnm84GCSU",
|
||||||
|
admins=[],
|
||||||
|
nsset=None,
|
||||||
|
keyset=None,
|
||||||
|
ex_date=datetime.date(2024, 8, 15),
|
||||||
|
auth_info=info.DomainAuthInfo(pw="2fooBAR123fooBaz"),
|
||||||
|
)
|
||||||
|
],
|
||||||
|
"sv_tr_id": "wRRNVhKhQW2m6wsUHbo/lA==-29a",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Mock a response from EPP
|
||||||
|
def fake_receive(command, cleaned=None):
|
||||||
|
location = Path(__file__).parent / "utility" / "infoDomain.xml"
|
||||||
|
xml = (location).read_bytes()
|
||||||
|
return xml
|
||||||
|
|
||||||
|
# Mock what happens inside the "with"
|
||||||
|
with ExitStack() as stack:
|
||||||
|
stack.enter_context(
|
||||||
|
patch.object(EPPConnectionPool, "_create_socket", self.fake_socket)
|
||||||
|
)
|
||||||
|
stack.enter_context(patch.object(Socket, "connect", self.fake_client))
|
||||||
|
stack.enter_context(patch.object(SocketTransport, "send", self.fake_send))
|
||||||
|
stack.enter_context(patch.object(SocketTransport, "receive", fake_receive))
|
||||||
|
# Restart the connection pool
|
||||||
|
registry.start_connection_pool()
|
||||||
|
# Pool should be running, and be the right size
|
||||||
|
self.assertEqual(registry.pool_status.connection_success, True)
|
||||||
|
self.assertEqual(registry.pool_status.pool_running, True)
|
||||||
|
|
||||||
|
# Send a command
|
||||||
|
result = registry.send(commands.InfoDomain(name="test.gov"), cleaned=True)
|
||||||
|
|
||||||
|
# Should this ever fail, it either means that the schema has changed,
|
||||||
|
# or the pool is broken.
|
||||||
|
# If the schema has changed: Update the associated infoDomain.xml file
|
||||||
|
self.assertEqual(result.__dict__, expected_result)
|
||||||
|
|
||||||
|
# The number of open pools should match the number of requested ones.
|
||||||
|
# If it is 0, then they failed to open
|
||||||
|
self.assertEqual(len(registry._pool.conn), self.pool_options["size"])
|
||||||
|
|
||||||
|
@patch.object(EPPLibWrapper, "_test_registry_connection_success", patch_success)
|
||||||
|
def test_pool_restarts_on_send(self):
|
||||||
|
"""A .send is invoked, but the pool isn't running.
|
||||||
|
The pool should restart."""
|
||||||
|
expected_result = {
|
||||||
|
"cl_tr_id": None,
|
||||||
|
"code": 1000,
|
||||||
|
"extensions": [],
|
||||||
|
"msg": "Command completed successfully",
|
||||||
|
"msg_q": None,
|
||||||
|
"res_data": [
|
||||||
|
info.InfoDomainResultData(
|
||||||
|
roid="DF1340360-GOV",
|
||||||
|
statuses=[
|
||||||
|
common.Status(
|
||||||
|
state="serverTransferProhibited",
|
||||||
|
description=None,
|
||||||
|
lang="en",
|
||||||
|
),
|
||||||
|
common.Status(state="inactive", description=None, lang="en"),
|
||||||
|
],
|
||||||
|
cl_id="gov2023-ote",
|
||||||
|
cr_id="gov2023-ote",
|
||||||
|
cr_date=datetime.datetime(
|
||||||
|
2023, 8, 15, 23, 56, 36, tzinfo=tzlocal()
|
||||||
|
),
|
||||||
|
up_id="gov2023-ote",
|
||||||
|
up_date=datetime.datetime(2023, 8, 17, 2, 3, 19, tzinfo=tzlocal()),
|
||||||
|
tr_date=None,
|
||||||
|
name="test3.gov",
|
||||||
|
registrant="TuaWnx9hnm84GCSU",
|
||||||
|
admins=[],
|
||||||
|
nsset=None,
|
||||||
|
keyset=None,
|
||||||
|
ex_date=datetime.date(2024, 8, 15),
|
||||||
|
auth_info=info.DomainAuthInfo(pw="2fooBAR123fooBaz"),
|
||||||
|
)
|
||||||
|
],
|
||||||
|
"sv_tr_id": "wRRNVhKhQW2m6wsUHbo/lA==-29a",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Mock a response from EPP
|
||||||
|
def fake_receive(command, cleaned=None):
|
||||||
|
location = Path(__file__).parent / "utility" / "infoDomain.xml"
|
||||||
|
xml = (location).read_bytes()
|
||||||
|
return xml
|
||||||
|
|
||||||
|
# Mock what happens inside the "with"
|
||||||
|
with ExitStack() as stack:
|
||||||
|
stack.enter_context(
|
||||||
|
patch.object(EPPConnectionPool, "_create_socket", self.fake_socket)
|
||||||
|
)
|
||||||
|
stack.enter_context(patch.object(Socket, "connect", self.fake_client))
|
||||||
|
stack.enter_context(patch.object(SocketTransport, "send", self.fake_send))
|
||||||
|
stack.enter_context(patch.object(SocketTransport, "receive", fake_receive))
|
||||||
|
# Kill the connection pool
|
||||||
|
registry.kill_pool()
|
||||||
|
|
||||||
|
self.assertEqual(registry.pool_status.connection_success, False)
|
||||||
|
self.assertEqual(registry.pool_status.pool_running, False)
|
||||||
|
|
||||||
|
# An exception should be raised as end user will be informed
|
||||||
|
# that they cannot connect to EPP
|
||||||
|
with self.assertRaises(RegistryError):
|
||||||
|
expected = "InfoDomain failed to execute due to a connection error."
|
||||||
|
result = registry.send(
|
||||||
|
commands.InfoDomain(name="test.gov"), cleaned=True
|
||||||
|
)
|
||||||
|
self.assertEqual(result, expected)
|
||||||
|
|
||||||
|
# A subsequent command should be successful, as the pool restarts
|
||||||
|
result = registry.send(commands.InfoDomain(name="test.gov"), cleaned=True)
|
||||||
|
# Should this ever fail, it either means that the schema has changed,
|
||||||
|
# or the pool is broken.
|
||||||
|
# If the schema has changed: Update the associated infoDomain.xml file
|
||||||
|
self.assertEqual(result.__dict__, expected_result)
|
||||||
|
|
||||||
|
# The number of open pools should match the number of requested ones.
|
||||||
|
# If it is 0, then they failed to open
|
||||||
|
self.assertEqual(len(registry._pool.conn), self.pool_options["size"])
|
||||||
|
|
||||||
|
@patch.object(EPPLibWrapper, "_test_registry_connection_success", patch_success)
|
||||||
|
def test_raises_connection_error(self):
|
||||||
|
"""A .send is invoked on the pool, but registry connection is lost
|
||||||
|
right as we send a command."""
|
||||||
|
|
||||||
|
with ExitStack() as stack:
|
||||||
|
stack.enter_context(
|
||||||
|
patch.object(EPPConnectionPool, "_create_socket", self.fake_socket)
|
||||||
|
)
|
||||||
|
stack.enter_context(patch.object(Socket, "connect", self.fake_client))
|
||||||
|
|
||||||
|
# Pool should be running
|
||||||
|
self.assertEqual(registry.pool_status.connection_success, True)
|
||||||
|
self.assertEqual(registry.pool_status.pool_running, True)
|
||||||
|
|
||||||
|
# Try to send a command out - should fail
|
||||||
|
with self.assertRaises(RegistryError):
|
||||||
|
expected = "InfoDomain failed to execute due to a connection error."
|
||||||
|
result = registry.send(
|
||||||
|
commands.InfoDomain(name="test.gov"), cleaned=True
|
||||||
|
)
|
||||||
|
self.assertEqual(result, expected)
|
33
src/epplibwrapper/tests/utility/infoDomain.xml
Normal file
33
src/epplibwrapper/tests/utility/infoDomain.xml
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
|
|
||||||
|
<epp xmlns:domain="urn:ietf:params:xml:ns:domain-1.0" xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xmlns:fee="urn:ietf:params:xml:ns:fee-0.6" xmlns:packageToken="urn:google:params:xml:ns:packageToken-1.0" xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:fee11="urn:ietf:params:xml:ns:fee-0.11" xmlns:fee12="urn:ietf:params:xml:ns:fee-0.12" xmlns:launch="urn:ietf:params:xml:ns:launch-1.0" xmlns:secDNS="urn:ietf:params:xml:ns:secDNS-1.1" xmlns:host="urn:ietf:params:xml:ns:host-1.0">
|
||||||
|
<response>
|
||||||
|
<result code="1000">
|
||||||
|
<msg>Command completed successfully</msg>
|
||||||
|
</result>
|
||||||
|
<resData>
|
||||||
|
<domain:infData>
|
||||||
|
<domain:name>test3.gov</domain:name>
|
||||||
|
<domain:roid>DF1340360-GOV</domain:roid>
|
||||||
|
<domain:status s="serverTransferProhibited"/>
|
||||||
|
<domain:status s="inactive"/>
|
||||||
|
<domain:registrant>TuaWnx9hnm84GCSU</domain:registrant>
|
||||||
|
<domain:contact type="security">CONT2</domain:contact>
|
||||||
|
<domain:contact type="tech">CONT3</domain:contact>
|
||||||
|
<domain:clID>gov2023-ote</domain:clID>
|
||||||
|
<domain:crID>gov2023-ote</domain:crID>
|
||||||
|
<domain:crDate>2023-08-15T23:56:36Z</domain:crDate>
|
||||||
|
<domain:upID>gov2023-ote</domain:upID>
|
||||||
|
<domain:upDate>2023-08-17T02:03:19Z</domain:upDate>
|
||||||
|
<domain:exDate>2024-08-15T23:56:36Z</domain:exDate>
|
||||||
|
<domain:authInfo>
|
||||||
|
<domain:pw>2fooBAR123fooBaz</domain:pw>
|
||||||
|
</domain:authInfo>
|
||||||
|
</domain:infData>
|
||||||
|
</resData>
|
||||||
|
<trID>
|
||||||
|
<svTRID>wRRNVhKhQW2m6wsUHbo/lA==-29a</svTRID>
|
||||||
|
</trID>
|
||||||
|
</response>
|
||||||
|
|
||||||
|
</epp>
|
134
src/epplibwrapper/utility/pool.py
Normal file
134
src/epplibwrapper/utility/pool.py
Normal file
|
@ -0,0 +1,134 @@
|
||||||
|
import logging
|
||||||
|
from typing import List
|
||||||
|
import gevent
|
||||||
|
from geventconnpool import ConnectionPool
|
||||||
|
from epplibwrapper.socket import Socket
|
||||||
|
from epplibwrapper.utility.pool_error import PoolError, PoolErrorCodes
|
||||||
|
|
||||||
|
try:
|
||||||
|
from epplib.commands import Hello
|
||||||
|
from epplib.exceptions import TransportError
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
from gevent.lock import BoundedSemaphore
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class EPPConnectionPool(ConnectionPool):
|
||||||
|
"""A connection pool for EPPLib.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
client (Client): The client
|
||||||
|
login (commands.Login): Login creds
|
||||||
|
options (dict): Options for the ConnectionPool
|
||||||
|
base class
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, client, login, options: dict):
|
||||||
|
# For storing shared credentials
|
||||||
|
self._client = client
|
||||||
|
self._login = login
|
||||||
|
|
||||||
|
# Keep track of each greenlet
|
||||||
|
self.greenlets: List[gevent.Greenlet] = []
|
||||||
|
|
||||||
|
# Define optional pool settings.
|
||||||
|
# Kept in a dict so that the parent class,
|
||||||
|
# client.py, can maintain seperation/expandability
|
||||||
|
self.size = 1
|
||||||
|
if "size" in options:
|
||||||
|
self.size = options["size"]
|
||||||
|
|
||||||
|
self.exc_classes = tuple((TransportError,))
|
||||||
|
if "exc_classes" in options:
|
||||||
|
self.exc_classes = options["exc_classes"]
|
||||||
|
|
||||||
|
self.keepalive = None
|
||||||
|
if "keepalive" in options:
|
||||||
|
self.keepalive = options["keepalive"]
|
||||||
|
|
||||||
|
# Determines the period in which new
|
||||||
|
# gevent threads are spun up.
|
||||||
|
# This time period is in seconds. So for instance, .1 would be .1 seconds.
|
||||||
|
self.spawn_frequency = 0.1
|
||||||
|
if "spawn_frequency" in options:
|
||||||
|
self.spawn_frequency = options["spawn_frequency"]
|
||||||
|
|
||||||
|
self.conn: deque = deque()
|
||||||
|
self.lock = BoundedSemaphore(self.size)
|
||||||
|
|
||||||
|
self.populate_all_connections()
|
||||||
|
|
||||||
|
def _new_connection(self):
|
||||||
|
socket = self._create_socket(self._client, self._login)
|
||||||
|
try:
|
||||||
|
connection = socket.connect()
|
||||||
|
return connection
|
||||||
|
except Exception as err:
|
||||||
|
message = f"Failed to execute due to a registry error: {err}"
|
||||||
|
logger.error(message, exc_info=True)
|
||||||
|
# We want to raise a pool error rather than a LoginError here
|
||||||
|
# because if this occurs internally, we should handle this
|
||||||
|
# differently than we otherwise would for LoginError.
|
||||||
|
raise PoolError(code=PoolErrorCodes.NEW_CONNECTION_FAILED) from err
|
||||||
|
|
||||||
|
def _keepalive(self, c):
|
||||||
|
"""Sends a command to the server to keep the connection alive."""
|
||||||
|
try:
|
||||||
|
# Sends a ping to the registry via EPPLib
|
||||||
|
c.send(Hello())
|
||||||
|
except Exception as err:
|
||||||
|
message = "Failed to keep the connection alive."
|
||||||
|
logger.error(message, exc_info=True)
|
||||||
|
raise PoolError(code=PoolErrorCodes.KEEP_ALIVE_FAILED) from err
|
||||||
|
|
||||||
|
def _create_socket(self, client, login) -> Socket:
|
||||||
|
"""Creates and returns a socket instance"""
|
||||||
|
socket = Socket(client, login)
|
||||||
|
return socket
|
||||||
|
|
||||||
|
def get_connections(self):
|
||||||
|
"""Returns the connection queue"""
|
||||||
|
return self.conn
|
||||||
|
|
||||||
|
def kill_all_connections(self):
|
||||||
|
"""Kills all active connections in the pool."""
|
||||||
|
try:
|
||||||
|
if len(self.conn) > 0:
|
||||||
|
gevent.killall(self.greenlets)
|
||||||
|
|
||||||
|
self.greenlets.clear()
|
||||||
|
self.conn.clear()
|
||||||
|
|
||||||
|
# Clear the semaphore
|
||||||
|
self.lock = BoundedSemaphore(self.size)
|
||||||
|
else:
|
||||||
|
logger.info("No connections to kill.")
|
||||||
|
except Exception as err:
|
||||||
|
logger.error("Could not kill all connections.")
|
||||||
|
raise PoolError(code=PoolErrorCodes.KILL_ALL_FAILED) from err
|
||||||
|
|
||||||
|
def populate_all_connections(self):
|
||||||
|
"""Generates the connection pool.
|
||||||
|
If any connections exist, kill them first.
|
||||||
|
Based off of the __init__ definition for geventconnpool.
|
||||||
|
"""
|
||||||
|
if len(self.conn) > 0:
|
||||||
|
self.kill_all_connections()
|
||||||
|
|
||||||
|
# Setup the lock
|
||||||
|
for i in range(self.size):
|
||||||
|
self.lock.acquire()
|
||||||
|
|
||||||
|
# Open multiple connections
|
||||||
|
for i in range(self.size):
|
||||||
|
self.greenlets.append(
|
||||||
|
gevent.spawn_later(self.spawn_frequency * i, self._addOne)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Open a "keepalive" thread if we want to ping open connections
|
||||||
|
if self.keepalive:
|
||||||
|
self.greenlets.append(gevent.spawn(self._keepalive_periodic))
|
52
src/epplibwrapper/utility/pool_error.py
Normal file
52
src/epplibwrapper/utility/pool_error.py
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
from enum import IntEnum
|
||||||
|
|
||||||
|
|
||||||
|
class PoolErrorCodes(IntEnum):
|
||||||
|
"""Used in the PoolError class for
|
||||||
|
error mapping.
|
||||||
|
|
||||||
|
Overview of contact error codes:
|
||||||
|
- 2000 KILL_ALL_FAILED
|
||||||
|
- 2001 NEW_CONNECTION_FAILED
|
||||||
|
- 2002 KEEP_ALIVE_FAILED
|
||||||
|
"""
|
||||||
|
|
||||||
|
KILL_ALL_FAILED = 2000
|
||||||
|
NEW_CONNECTION_FAILED = 2001
|
||||||
|
KEEP_ALIVE_FAILED = 2002
|
||||||
|
|
||||||
|
|
||||||
|
class PoolError(Exception):
|
||||||
|
"""
|
||||||
|
Overview of contact error codes:
|
||||||
|
- 2000 KILL_ALL_FAILED
|
||||||
|
- 2001 NEW_CONNECTION_FAILED
|
||||||
|
- 2002 KEEP_ALIVE_FAILED
|
||||||
|
|
||||||
|
Note: These are separate from the error codes returned from EppLib
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Used variables due to linter requirements
|
||||||
|
kill_failed = "Could not kill all connections. Are multiple pools running?"
|
||||||
|
conn_failed = (
|
||||||
|
"Failed to execute due to a registry error."
|
||||||
|
" See previous logs to determine the cause of the error."
|
||||||
|
)
|
||||||
|
alive_failed = (
|
||||||
|
"Failed to keep the connection alive. "
|
||||||
|
"It is likely that the registry returned a LoginError."
|
||||||
|
)
|
||||||
|
_error_mapping = {
|
||||||
|
PoolErrorCodes.KILL_ALL_FAILED: kill_failed,
|
||||||
|
PoolErrorCodes.NEW_CONNECTION_FAILED: conn_failed,
|
||||||
|
PoolErrorCodes.KEEP_ALIVE_FAILED: alive_failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
def __init__(self, *args, code=None, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.code = code
|
||||||
|
if self.code in self._error_mapping:
|
||||||
|
self.message = self._error_mapping.get(self.code)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"{self.message}"
|
12
src/epplibwrapper/utility/pool_status.py
Normal file
12
src/epplibwrapper/utility/pool_status.py
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
class PoolStatus:
|
||||||
|
"""A list of Booleans to keep track of Pool Status.
|
||||||
|
|
||||||
|
pool_running -> bool: Tracks if the pool itself is active or not.
|
||||||
|
connection_success -> bool: Tracks if connection is possible with the registry.
|
||||||
|
pool_hanging -> pool: Tracks if the pool has exceeded its timeout period.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.pool_running = False
|
||||||
|
self.connection_success = False
|
||||||
|
self.pool_hanging = False
|
|
@ -231,41 +231,15 @@ function handleValidationClick(e) {
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An IIFE that attaches a click handler for our dynamic nameservers form
|
* Prepare the namerservers and DS data forms delete buttons
|
||||||
|
* We will call this on the forms init, and also every time we add a form
|
||||||
*
|
*
|
||||||
* Only does something on a single page, but it should be fast enough to run
|
|
||||||
* it everywhere.
|
|
||||||
*/
|
*/
|
||||||
(function prepareNameserverForms() {
|
function prepareDeleteButtons(formLabel) {
|
||||||
let serverForm = document.querySelectorAll(".server-form");
|
|
||||||
let container = document.querySelector("#form-container");
|
|
||||||
let addButton = document.querySelector("#add-nameserver-form");
|
|
||||||
let totalForms = document.querySelector("#id_form-TOTAL_FORMS");
|
|
||||||
|
|
||||||
let formNum = serverForm.length-1;
|
|
||||||
if (addButton)
|
|
||||||
addButton.addEventListener('click', addForm);
|
|
||||||
|
|
||||||
function addForm(e){
|
|
||||||
let newForm = serverForm[2].cloneNode(true);
|
|
||||||
let formNumberRegex = RegExp(`form-(\\d){1}-`,'g');
|
|
||||||
let formLabelRegex = RegExp(`Name server (\\d){1}`, 'g');
|
|
||||||
let formExampleRegex = RegExp(`ns(\\d){1}`, 'g');
|
|
||||||
|
|
||||||
formNum++;
|
|
||||||
newForm.innerHTML = newForm.innerHTML.replace(formNumberRegex, `form-${formNum}-`);
|
|
||||||
newForm.innerHTML = newForm.innerHTML.replace(formLabelRegex, `Name server ${formNum+1}`);
|
|
||||||
newForm.innerHTML = newForm.innerHTML.replace(formExampleRegex, `ns${formNum+1}`);
|
|
||||||
container.insertBefore(newForm, addButton);
|
|
||||||
newForm.querySelector("input").value = "";
|
|
||||||
|
|
||||||
totalForms.setAttribute('value', `${formNum+1}`);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
function prepareDeleteButtons() {
|
|
||||||
let deleteButtons = document.querySelectorAll(".delete-record");
|
let deleteButtons = document.querySelectorAll(".delete-record");
|
||||||
let totalForms = document.querySelector("#id_form-TOTAL_FORMS");
|
let totalForms = document.querySelector("#id_form-TOTAL_FORMS");
|
||||||
|
let isNameserversForm = document.title.includes("DNS name servers |");
|
||||||
|
let addButton = document.querySelector("#add-form");
|
||||||
|
|
||||||
// Loop through each delete button and attach the click event listener
|
// Loop through each delete button and attach the click event listener
|
||||||
deleteButtons.forEach((deleteButton) => {
|
deleteButtons.forEach((deleteButton) => {
|
||||||
|
@ -273,13 +247,15 @@ function prepareDeleteButtons() {
|
||||||
});
|
});
|
||||||
|
|
||||||
function removeForm(e){
|
function removeForm(e){
|
||||||
let formToRemove = e.target.closest(".ds-record");
|
let formToRemove = e.target.closest(".repeatable-form");
|
||||||
formToRemove.remove();
|
formToRemove.remove();
|
||||||
let forms = document.querySelectorAll(".ds-record");
|
let forms = document.querySelectorAll(".repeatable-form");
|
||||||
totalForms.setAttribute('value', `${forms.length}`);
|
totalForms.setAttribute('value', `${forms.length}`);
|
||||||
|
|
||||||
let formNumberRegex = RegExp(`form-(\\d){1}-`, 'g');
|
let formNumberRegex = RegExp(`form-(\\d){1}-`, 'g');
|
||||||
let formLabelRegex = RegExp(`DS Data record (\\d){1}`, 'g');
|
let formLabelRegex = RegExp(`${formLabel} (\\d+){1}`, 'g');
|
||||||
|
// For the example on Nameservers
|
||||||
|
let formExampleRegex = RegExp(`ns(\\d+){1}`, 'g');
|
||||||
|
|
||||||
forms.forEach((form, index) => {
|
forms.forEach((form, index) => {
|
||||||
// Iterate over child nodes of the current element
|
// Iterate over child nodes of the current element
|
||||||
|
@ -294,48 +270,88 @@ function prepareDeleteButtons() {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
Array.from(form.querySelectorAll('h2, legend')).forEach((node) => {
|
// h2 and legend for DS form, label for nameservers
|
||||||
node.textContent = node.textContent.replace(formLabelRegex, `DS Data record ${index + 1}`);
|
Array.from(form.querySelectorAll('h2, legend, label, p')).forEach((node) => {
|
||||||
|
|
||||||
|
// Ticket: 1192
|
||||||
|
// if (isNameserversForm && index <= 1 && !node.innerHTML.includes('*')) {
|
||||||
|
// // Create a new element
|
||||||
|
// const newElement = document.createElement('abbr');
|
||||||
|
// newElement.textContent = '*';
|
||||||
|
// // TODO: finish building abbr
|
||||||
|
|
||||||
|
// // Append the new element to the parent
|
||||||
|
// node.appendChild(newElement);
|
||||||
|
// // Find the next sibling that is an input element
|
||||||
|
// let nextInputElement = node.nextElementSibling;
|
||||||
|
|
||||||
|
// while (nextInputElement) {
|
||||||
|
// if (nextInputElement.tagName === 'INPUT') {
|
||||||
|
// // Found the next input element
|
||||||
|
// console.log(nextInputElement);
|
||||||
|
// break;
|
||||||
|
// }
|
||||||
|
// nextInputElement = nextInputElement.nextElementSibling;
|
||||||
|
// }
|
||||||
|
// nextInputElement.required = true;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// Ticket: 1192 - remove if
|
||||||
|
if (!(isNameserversForm && index <= 1)) {
|
||||||
|
node.textContent = node.textContent.replace(formLabelRegex, `${formLabel} ${index + 1}`);
|
||||||
|
node.textContent = node.textContent.replace(formExampleRegex, `ns${index + 1}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Display the add more button if we have less than 13 forms
|
||||||
|
if (isNameserversForm && forms.length <= 13) {
|
||||||
|
addButton.classList.remove("display-none")
|
||||||
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An IIFE that attaches a click handler for our dynamic DNSSEC forms
|
* An IIFE that attaches a click handler for our dynamic formsets
|
||||||
*
|
*
|
||||||
|
* Only does something on a few pages, but it should be fast enough to run
|
||||||
|
* it everywhere.
|
||||||
*/
|
*/
|
||||||
(function prepareDNSSECForms() {
|
(function prepareFormsetsForms() {
|
||||||
let serverForm = document.querySelectorAll(".ds-record");
|
let repeatableForm = document.querySelectorAll(".repeatable-form");
|
||||||
let container = document.querySelector("#form-container");
|
let container = document.querySelector("#form-container");
|
||||||
let addButton = document.querySelector("#add-ds-form");
|
let addButton = document.querySelector("#add-form");
|
||||||
let totalForms = document.querySelector("#id_form-TOTAL_FORMS");
|
let totalForms = document.querySelector("#id_form-TOTAL_FORMS");
|
||||||
|
let cloneIndex = 0;
|
||||||
|
let formLabel = '';
|
||||||
|
let isNameserversForm = document.title.includes("DNS name servers |");
|
||||||
|
if (isNameserversForm) {
|
||||||
|
cloneIndex = 2;
|
||||||
|
formLabel = "Name server";
|
||||||
|
} else if ((document.title.includes("DS Data |")) || (document.title.includes("Key Data |"))) {
|
||||||
|
formLabel = "DS Data record";
|
||||||
|
}
|
||||||
|
|
||||||
// Attach click event listener on the delete buttons of the existing forms
|
// Attach click event listener on the delete buttons of the existing forms
|
||||||
prepareDeleteButtons();
|
prepareDeleteButtons(formLabel);
|
||||||
|
|
||||||
// Attack click event listener on the add button
|
|
||||||
if (addButton)
|
if (addButton)
|
||||||
addButton.addEventListener('click', addForm);
|
addButton.addEventListener('click', addForm);
|
||||||
|
|
||||||
/*
|
|
||||||
* Add a formset to the end of the form.
|
|
||||||
* For each element in the added formset, name the elements with the prefix,
|
|
||||||
* form-{#}-{element_name} where # is the index of the formset and element_name
|
|
||||||
* is the element's name.
|
|
||||||
* Additionally, update the form element's metadata, including totalForms' value.
|
|
||||||
*/
|
|
||||||
function addForm(e){
|
function addForm(e){
|
||||||
let forms = document.querySelectorAll(".ds-record");
|
let forms = document.querySelectorAll(".repeatable-form");
|
||||||
let formNum = forms.length;
|
let formNum = forms.length;
|
||||||
let newForm = serverForm[0].cloneNode(true);
|
let newForm = repeatableForm[cloneIndex].cloneNode(true);
|
||||||
let formNumberRegex = RegExp(`form-(\\d){1}-`,'g');
|
let formNumberRegex = RegExp(`form-(\\d){1}-`,'g');
|
||||||
let formLabelRegex = RegExp(`DS Data record (\\d){1}`, 'g');
|
let formLabelRegex = RegExp(`${formLabel} (\\d){1}`, 'g');
|
||||||
|
// For the eample on Nameservers
|
||||||
|
let formExampleRegex = RegExp(`ns(\\d){1}`, 'g');
|
||||||
|
|
||||||
formNum++;
|
formNum++;
|
||||||
newForm.innerHTML = newForm.innerHTML.replace(formNumberRegex, `form-${formNum-1}-`);
|
newForm.innerHTML = newForm.innerHTML.replace(formNumberRegex, `form-${formNum-1}-`);
|
||||||
newForm.innerHTML = newForm.innerHTML.replace(formLabelRegex, `DS Data record ${formNum}`);
|
newForm.innerHTML = newForm.innerHTML.replace(formLabelRegex, `${formLabel} ${formNum}`);
|
||||||
|
newForm.innerHTML = newForm.innerHTML.replace(formExampleRegex, `ns${formNum}`);
|
||||||
container.insertBefore(newForm, addButton);
|
container.insertBefore(newForm, addButton);
|
||||||
|
|
||||||
let inputs = newForm.querySelectorAll("input");
|
let inputs = newForm.querySelectorAll("input");
|
||||||
|
@ -379,9 +395,13 @@ function prepareDeleteButtons() {
|
||||||
totalForms.setAttribute('value', `${formNum}`);
|
totalForms.setAttribute('value', `${formNum}`);
|
||||||
|
|
||||||
// Attach click event listener on the delete buttons of the new form
|
// Attach click event listener on the delete buttons of the new form
|
||||||
prepareDeleteButtons();
|
prepareDeleteButtons(formLabel);
|
||||||
}
|
|
||||||
|
|
||||||
|
// Hide the add more button if we have 13 forms
|
||||||
|
if (isNameserversForm && formNum == 13) {
|
||||||
|
addButton.classList.add("display-none")
|
||||||
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -4,6 +4,10 @@
|
||||||
margin-top: units(3);
|
margin-top: units(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.usa-form .usa-button.margin-bottom-075 {
|
||||||
|
margin-bottom: units(1.5);
|
||||||
|
}
|
||||||
|
|
||||||
.usa-form .usa-button.margin-top-1 {
|
.usa-form .usa-button.margin-top-1 {
|
||||||
margin-top: units(1);
|
margin-top: units(1);
|
||||||
}
|
}
|
||||||
|
|
|
@ -534,6 +534,20 @@ SECRET_REGISTRY_KEY = secret_registry_key
|
||||||
SECRET_REGISTRY_KEY_PASSPHRASE = secret_registry_key_passphrase
|
SECRET_REGISTRY_KEY_PASSPHRASE = secret_registry_key_passphrase
|
||||||
SECRET_REGISTRY_HOSTNAME = secret_registry_hostname
|
SECRET_REGISTRY_HOSTNAME = secret_registry_hostname
|
||||||
|
|
||||||
|
# Use this variable to set the size of our connection pool in client.py
|
||||||
|
# WARNING: Setting this value too high could cause frequent app crashes!
|
||||||
|
# Having too many connections open could cause the sandbox to timeout,
|
||||||
|
# as the spinup time could exceed the timeout time.
|
||||||
|
EPP_CONNECTION_POOL_SIZE = 1
|
||||||
|
|
||||||
|
# Determines the interval in which we ping open connections in seconds
|
||||||
|
# Calculated as POOL_KEEP_ALIVE / EPP_CONNECTION_POOL_SIZE
|
||||||
|
POOL_KEEP_ALIVE = 60
|
||||||
|
|
||||||
|
# Determines how long we try to keep a pool alive for,
|
||||||
|
# before restarting it.
|
||||||
|
POOL_TIMEOUT = 60
|
||||||
|
|
||||||
# endregion
|
# endregion
|
||||||
# region: Security and Privacy----------------------------------------------###
|
# region: Security and Privacy----------------------------------------------###
|
||||||
|
|
||||||
|
|
|
@ -5,8 +5,12 @@ from django.core.validators import MinValueValidator, MaxValueValidator, RegexVa
|
||||||
from django.forms import formset_factory
|
from django.forms import formset_factory
|
||||||
|
|
||||||
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
from phonenumber_field.widgets import RegionalPhoneNumberWidget
|
||||||
|
from registrar.utility.errors import (
|
||||||
|
NameserverError,
|
||||||
|
NameserverErrorCodes as nsErrorCodes,
|
||||||
|
)
|
||||||
|
|
||||||
from ..models import Contact, DomainInformation
|
from ..models import Contact, DomainInformation, Domain
|
||||||
from .common import (
|
from .common import (
|
||||||
ALGORITHM_CHOICES,
|
ALGORITHM_CHOICES,
|
||||||
DIGEST_TYPE_CHOICES,
|
DIGEST_TYPE_CHOICES,
|
||||||
|
@ -19,16 +23,78 @@ class DomainAddUserForm(forms.Form):
|
||||||
email = forms.EmailField(label="Email")
|
email = forms.EmailField(label="Email")
|
||||||
|
|
||||||
|
|
||||||
|
class IPAddressField(forms.CharField):
|
||||||
|
def validate(self, value):
|
||||||
|
super().validate(value) # Run the default CharField validation
|
||||||
|
|
||||||
|
|
||||||
class DomainNameserverForm(forms.Form):
|
class DomainNameserverForm(forms.Form):
|
||||||
"""Form for changing nameservers."""
|
"""Form for changing nameservers."""
|
||||||
|
|
||||||
|
domain = forms.CharField(widget=forms.HiddenInput, required=False)
|
||||||
|
|
||||||
server = forms.CharField(label="Name server", strip=True)
|
server = forms.CharField(label="Name server", strip=True)
|
||||||
# when adding IPs to this form ensure they are stripped as well
|
|
||||||
|
ip = forms.CharField(label="IP Address (IPv4 or IPv6)", strip=True, required=False)
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
# clean is called from clean_forms, which is called from is_valid
|
||||||
|
# after clean_fields. it is used to determine form level errors.
|
||||||
|
# is_valid is typically called from view during a post
|
||||||
|
cleaned_data = super().clean()
|
||||||
|
self.clean_empty_strings(cleaned_data)
|
||||||
|
server = cleaned_data.get("server", "")
|
||||||
|
ip = cleaned_data.get("ip", None)
|
||||||
|
# remove ANY spaces in the ip field
|
||||||
|
ip = ip.replace(" ", "")
|
||||||
|
domain = cleaned_data.get("domain", "")
|
||||||
|
|
||||||
|
ip_list = self.extract_ip_list(ip)
|
||||||
|
|
||||||
|
if ip and not server and ip_list:
|
||||||
|
self.add_error("server", NameserverError(code=nsErrorCodes.MISSING_HOST))
|
||||||
|
elif server:
|
||||||
|
self.validate_nameserver_ip_combo(domain, server, ip_list)
|
||||||
|
|
||||||
|
return cleaned_data
|
||||||
|
|
||||||
|
def clean_empty_strings(self, cleaned_data):
|
||||||
|
ip = cleaned_data.get("ip", "")
|
||||||
|
if ip and len(ip.strip()) == 0:
|
||||||
|
cleaned_data["ip"] = None
|
||||||
|
|
||||||
|
def extract_ip_list(self, ip):
|
||||||
|
return [ip.strip() for ip in ip.split(",")] if ip else []
|
||||||
|
|
||||||
|
def validate_nameserver_ip_combo(self, domain, server, ip_list):
|
||||||
|
try:
|
||||||
|
Domain.checkHostIPCombo(domain, server, ip_list)
|
||||||
|
except NameserverError as e:
|
||||||
|
if e.code == nsErrorCodes.GLUE_RECORD_NOT_ALLOWED:
|
||||||
|
self.add_error(
|
||||||
|
"server",
|
||||||
|
NameserverError(
|
||||||
|
code=nsErrorCodes.GLUE_RECORD_NOT_ALLOWED,
|
||||||
|
nameserver=domain,
|
||||||
|
ip=ip_list,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
elif e.code == nsErrorCodes.MISSING_IP:
|
||||||
|
self.add_error(
|
||||||
|
"ip",
|
||||||
|
NameserverError(
|
||||||
|
code=nsErrorCodes.MISSING_IP, nameserver=domain, ip=ip_list
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.add_error("ip", str(e))
|
||||||
|
|
||||||
|
|
||||||
NameserverFormset = formset_factory(
|
NameserverFormset = formset_factory(
|
||||||
DomainNameserverForm,
|
DomainNameserverForm,
|
||||||
extra=1,
|
extra=1,
|
||||||
|
max_num=13,
|
||||||
|
validate_max=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
20
src/registrar/migrations/0043_domain_expiration_date.py
Normal file
20
src/registrar/migrations/0043_domain_expiration_date.py
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
# Generated by Django 4.2.6 on 2023-10-30 15:37
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("registrar", "0042_create_groups_v03"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="domain",
|
||||||
|
name="expiration_date",
|
||||||
|
field=models.DateField(
|
||||||
|
help_text="Duplication of registry's expirationdate saved for ease of reporting",
|
||||||
|
null=True,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
|
@ -1,5 +1,4 @@
|
||||||
from auditlog.registry import auditlog # type: ignore
|
from auditlog.registry import auditlog # type: ignore
|
||||||
|
|
||||||
from .contact import Contact
|
from .contact import Contact
|
||||||
from .domain_application import DomainApplication
|
from .domain_application import DomainApplication
|
||||||
from .domain_information import DomainInformation
|
from .domain_information import DomainInformation
|
||||||
|
|
|
@ -5,10 +5,19 @@ import re
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from string import digits
|
from string import digits
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from django_fsm import FSMField, transition, TransitionNotAllowed # type: ignore
|
from django_fsm import FSMField, transition, TransitionNotAllowed # type: ignore
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
from registrar.utility.errors import (
|
||||||
|
ActionNotAllowed,
|
||||||
|
NameserverError,
|
||||||
|
NameserverErrorCodes as nsErrorCodes,
|
||||||
|
)
|
||||||
|
|
||||||
from epplibwrapper import (
|
from epplibwrapper import (
|
||||||
CLIENT as registry,
|
CLIENT as registry,
|
||||||
commands,
|
commands,
|
||||||
|
@ -19,15 +28,9 @@ from epplibwrapper import (
|
||||||
ErrorCode,
|
ErrorCode,
|
||||||
)
|
)
|
||||||
|
|
||||||
from registrar.utility.errors import (
|
|
||||||
ActionNotAllowed,
|
|
||||||
NameserverError,
|
|
||||||
NameserverErrorCodes as nsErrorCodes,
|
|
||||||
)
|
|
||||||
|
|
||||||
from registrar.models.utility.contact_error import ContactError, ContactErrorCodes
|
from registrar.models.utility.contact_error import ContactError, ContactErrorCodes
|
||||||
|
|
||||||
|
from django.db.models import DateField
|
||||||
from .utility.domain_field import DomainField
|
from .utility.domain_field import DomainField
|
||||||
from .utility.domain_helper import DomainHelper
|
from .utility.domain_helper import DomainHelper
|
||||||
from .utility.time_stamped_model import TimeStampedModel
|
from .utility.time_stamped_model import TimeStampedModel
|
||||||
|
@ -208,12 +211,12 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
return self._get_property("up_date")
|
return self._get_property("up_date")
|
||||||
|
|
||||||
@Cache
|
@Cache
|
||||||
def expiration_date(self) -> date:
|
def registry_expiration_date(self) -> date:
|
||||||
"""Get or set the `ex_date` element from the registry."""
|
"""Get or set the `ex_date` element from the registry."""
|
||||||
return self._get_property("ex_date")
|
return self._get_property("ex_date")
|
||||||
|
|
||||||
@expiration_date.setter # type: ignore
|
@registry_expiration_date.setter # type: ignore
|
||||||
def expiration_date(self, ex_date: date):
|
def registry_expiration_date(self, ex_date: date):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@Cache
|
@Cache
|
||||||
|
@ -253,15 +256,17 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
hostList = []
|
hostList = []
|
||||||
for host in hosts:
|
for host in hosts:
|
||||||
hostList.append((host["name"], host["addrs"]))
|
hostList.append((host["name"], host["addrs"]))
|
||||||
|
|
||||||
return hostList
|
return hostList
|
||||||
|
|
||||||
def _create_host(self, host, addrs):
|
def _create_host(self, host, addrs):
|
||||||
"""Creates the host object in the registry
|
"""Creates the host object in the registry
|
||||||
doesn't add the created host to the domain
|
doesn't add the created host to the domain
|
||||||
returns ErrorCode (int)"""
|
returns ErrorCode (int)"""
|
||||||
if addrs is not None:
|
if addrs is not None and addrs != []:
|
||||||
addresses = [epp.Ip(addr=addr) for addr in addrs]
|
addresses = [
|
||||||
|
epp.Ip(addr=addr, ip="v6" if self.is_ipv6(addr) else None)
|
||||||
|
for addr in addrs
|
||||||
|
]
|
||||||
request = commands.CreateHost(name=host, addrs=addresses)
|
request = commands.CreateHost(name=host, addrs=addresses)
|
||||||
else:
|
else:
|
||||||
request = commands.CreateHost(name=host)
|
request = commands.CreateHost(name=host)
|
||||||
|
@ -272,7 +277,7 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
return response.code
|
return response.code
|
||||||
except RegistryError as e:
|
except RegistryError as e:
|
||||||
logger.error("Error _create_host, code was %s error was %s" % (e.code, e))
|
logger.error("Error _create_host, code was %s error was %s" % (e.code, e))
|
||||||
return e.code
|
raise e
|
||||||
|
|
||||||
def _convert_list_to_dict(self, listToConvert: list[tuple[str, list]]):
|
def _convert_list_to_dict(self, listToConvert: list[tuple[str, list]]):
|
||||||
"""converts a list of hosts into a dictionary
|
"""converts a list of hosts into a dictionary
|
||||||
|
@ -291,14 +296,16 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
newDict[tup[0]] = tup[1]
|
newDict[tup[0]] = tup[1]
|
||||||
return newDict
|
return newDict
|
||||||
|
|
||||||
def isSubdomain(self, nameserver: str):
|
@classmethod
|
||||||
|
def isSubdomain(cls, name: str, nameserver: str):
|
||||||
"""Returns boolean if the domain name is found in the argument passed"""
|
"""Returns boolean if the domain name is found in the argument passed"""
|
||||||
subdomain_pattern = r"([\w-]+\.)*"
|
subdomain_pattern = r"([\w-]+\.)*"
|
||||||
full_pattern = subdomain_pattern + self.name
|
full_pattern = subdomain_pattern + name
|
||||||
regex = re.compile(full_pattern)
|
regex = re.compile(full_pattern)
|
||||||
return bool(regex.match(nameserver))
|
return bool(regex.match(nameserver))
|
||||||
|
|
||||||
def checkHostIPCombo(self, nameserver: str, ip: list[str]):
|
@classmethod
|
||||||
|
def checkHostIPCombo(cls, name: str, nameserver: str, ip: list[str]):
|
||||||
"""Checks the parameters past for a valid combination
|
"""Checks the parameters past for a valid combination
|
||||||
raises error if:
|
raises error if:
|
||||||
- nameserver is a subdomain but is missing ip
|
- nameserver is a subdomain but is missing ip
|
||||||
|
@ -312,22 +319,23 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
NameserverError (if exception hit)
|
NameserverError (if exception hit)
|
||||||
Returns:
|
Returns:
|
||||||
None"""
|
None"""
|
||||||
if self.isSubdomain(nameserver) and (ip is None or ip == []):
|
if cls.isSubdomain(name, nameserver) and (ip is None or ip == []):
|
||||||
raise NameserverError(code=nsErrorCodes.MISSING_IP, nameserver=nameserver)
|
raise NameserverError(code=nsErrorCodes.MISSING_IP, nameserver=nameserver)
|
||||||
|
|
||||||
elif not self.isSubdomain(nameserver) and (ip is not None and ip != []):
|
elif not cls.isSubdomain(name, nameserver) and (ip is not None and ip != []):
|
||||||
raise NameserverError(
|
raise NameserverError(
|
||||||
code=nsErrorCodes.GLUE_RECORD_NOT_ALLOWED, nameserver=nameserver, ip=ip
|
code=nsErrorCodes.GLUE_RECORD_NOT_ALLOWED, nameserver=nameserver, ip=ip
|
||||||
)
|
)
|
||||||
elif ip is not None and ip != []:
|
elif ip is not None and ip != []:
|
||||||
for addr in ip:
|
for addr in ip:
|
||||||
if not self._valid_ip_addr(addr):
|
if not cls._valid_ip_addr(addr):
|
||||||
raise NameserverError(
|
raise NameserverError(
|
||||||
code=nsErrorCodes.INVALID_IP, nameserver=nameserver, ip=ip
|
code=nsErrorCodes.INVALID_IP, nameserver=nameserver, ip=ip
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _valid_ip_addr(self, ipToTest: str):
|
@classmethod
|
||||||
|
def _valid_ip_addr(cls, ipToTest: str):
|
||||||
"""returns boolean if valid ip address string
|
"""returns boolean if valid ip address string
|
||||||
We currently only accept v4 or v6 ips
|
We currently only accept v4 or v6 ips
|
||||||
returns:
|
returns:
|
||||||
|
@ -380,7 +388,9 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
if newHostDict[prevHost] is not None and set(
|
if newHostDict[prevHost] is not None and set(
|
||||||
newHostDict[prevHost]
|
newHostDict[prevHost]
|
||||||
) != set(addrs):
|
) != set(addrs):
|
||||||
self.checkHostIPCombo(nameserver=prevHost, ip=newHostDict[prevHost])
|
self.__class__.checkHostIPCombo(
|
||||||
|
name=self.name, nameserver=prevHost, ip=newHostDict[prevHost]
|
||||||
|
)
|
||||||
updated_values.append((prevHost, newHostDict[prevHost]))
|
updated_values.append((prevHost, newHostDict[prevHost]))
|
||||||
|
|
||||||
new_values = {
|
new_values = {
|
||||||
|
@ -390,7 +400,9 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
}
|
}
|
||||||
|
|
||||||
for nameserver, ip in new_values.items():
|
for nameserver, ip in new_values.items():
|
||||||
self.checkHostIPCombo(nameserver=nameserver, ip=ip)
|
self.__class__.checkHostIPCombo(
|
||||||
|
name=self.name, nameserver=nameserver, ip=ip
|
||||||
|
)
|
||||||
|
|
||||||
return (deleted_values, updated_values, new_values, previousHostDict)
|
return (deleted_values, updated_values, new_values, previousHostDict)
|
||||||
|
|
||||||
|
@ -565,7 +577,11 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
if len(hosts) > 13:
|
if len(hosts) > 13:
|
||||||
raise NameserverError(code=nsErrorCodes.TOO_MANY_HOSTS)
|
raise NameserverError(code=nsErrorCodes.TOO_MANY_HOSTS)
|
||||||
|
|
||||||
if self.state not in [self.State.DNS_NEEDED, self.State.READY]:
|
if self.state not in [
|
||||||
|
self.State.DNS_NEEDED,
|
||||||
|
self.State.READY,
|
||||||
|
self.State.UNKNOWN,
|
||||||
|
]:
|
||||||
raise ActionNotAllowed("Nameservers can not be " "set in the current state")
|
raise ActionNotAllowed("Nameservers can not be " "set in the current state")
|
||||||
|
|
||||||
logger.info("Setting nameservers")
|
logger.info("Setting nameservers")
|
||||||
|
@ -943,6 +959,13 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
help_text="Very basic info about the lifecycle of this domain object",
|
help_text="Very basic info about the lifecycle of this domain object",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
expiration_date = DateField(
|
||||||
|
null=True,
|
||||||
|
help_text=(
|
||||||
|
"Duplication of registry's expiration" "date saved for ease of reporting"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
def isActive(self):
|
def isActive(self):
|
||||||
return self.state == Domain.State.CREATED
|
return self.state == Domain.State.CREATED
|
||||||
|
|
||||||
|
@ -1342,7 +1365,7 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
|
|
||||||
@transition(
|
@transition(
|
||||||
field="state",
|
field="state",
|
||||||
source=[State.DNS_NEEDED],
|
source=[State.DNS_NEEDED, State.READY],
|
||||||
target=State.READY,
|
target=State.READY,
|
||||||
# conditions=[dns_not_needed]
|
# conditions=[dns_not_needed]
|
||||||
)
|
)
|
||||||
|
@ -1505,7 +1528,7 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
data = registry.send(req, cleaned=True).res_data[0]
|
data = registry.send(req, cleaned=True).res_data[0]
|
||||||
host = {
|
host = {
|
||||||
"name": name,
|
"name": name,
|
||||||
"addrs": getattr(data, "addrs", ...),
|
"addrs": [item.addr for item in getattr(data, "addrs", [])],
|
||||||
"cr_date": getattr(data, "cr_date", ...),
|
"cr_date": getattr(data, "cr_date", ...),
|
||||||
"statuses": getattr(data, "statuses", ...),
|
"statuses": getattr(data, "statuses", ...),
|
||||||
"tr_date": getattr(data, "tr_date", ...),
|
"tr_date": getattr(data, "tr_date", ...),
|
||||||
|
@ -1530,10 +1553,9 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
return []
|
return []
|
||||||
|
|
||||||
for ip_addr in ip_list:
|
for ip_addr in ip_list:
|
||||||
if self.is_ipv6(ip_addr):
|
edited_ip_list.append(
|
||||||
edited_ip_list.append(epp.Ip(addr=ip_addr, ip="v6"))
|
epp.Ip(addr=ip_addr, ip="v6" if self.is_ipv6(ip_addr) else None)
|
||||||
else: # default ip addr is v4
|
)
|
||||||
edited_ip_list.append(epp.Ip(addr=ip_addr))
|
|
||||||
|
|
||||||
return edited_ip_list
|
return edited_ip_list
|
||||||
|
|
||||||
|
@ -1571,7 +1593,7 @@ class Domain(TimeStampedModel, DomainHelper):
|
||||||
return response.code
|
return response.code
|
||||||
except RegistryError as e:
|
except RegistryError as e:
|
||||||
logger.error("Error _update_host, code was %s error was %s" % (e.code, e))
|
logger.error("Error _update_host, code was %s error was %s" % (e.code, e))
|
||||||
return e.code
|
raise e
|
||||||
|
|
||||||
def addAndRemoveHostsFromDomain(
|
def addAndRemoveHostsFromDomain(
|
||||||
self, hostsToAdd: list[str], hostsToDelete: list[str]
|
self, hostsToAdd: list[str], hostsToDelete: list[str]
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from api.views import in_domains
|
from api.views import check_domain_available
|
||||||
from registrar.utility import errors
|
from registrar.utility import errors
|
||||||
|
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@ class DomainHelper:
|
||||||
raise errors.ExtraDotsError()
|
raise errors.ExtraDotsError()
|
||||||
if not DomainHelper.string_could_be_domain(domain + ".gov"):
|
if not DomainHelper.string_could_be_domain(domain + ".gov"):
|
||||||
raise ValueError()
|
raise ValueError()
|
||||||
if in_domains(domain):
|
if not check_domain_available(domain):
|
||||||
raise errors.DomainUnavailableError()
|
raise errors.DomainUnavailableError()
|
||||||
return domain
|
return domain
|
||||||
|
|
||||||
|
|
|
@ -29,7 +29,7 @@
|
||||||
|
|
||||||
{% url 'domain-dns-nameservers' pk=domain.id as url %}
|
{% url 'domain-dns-nameservers' pk=domain.id as url %}
|
||||||
{% if domain.nameservers|length > 0 %}
|
{% if domain.nameservers|length > 0 %}
|
||||||
{% include "includes/summary_item.html" with title='DNS name servers' value=domain.nameservers list='true' edit_link=url %}
|
{% include "includes/summary_item.html" with title='DNS name servers' domains='true' value=domain.nameservers list='true' edit_link=url %}
|
||||||
{% else %}
|
{% else %}
|
||||||
<h2 class="margin-top-neg-1"> DNS name servers </h2>
|
<h2 class="margin-top-neg-1"> DNS name servers </h2>
|
||||||
<p> No DNS name servers have been added yet. Before your domain can be used we’ll need information about your domain name servers.</p>
|
<p> No DNS name servers have been added yet. Before your domain can be used we’ll need information about your domain name servers.</p>
|
||||||
|
|
|
@ -7,7 +7,7 @@
|
||||||
|
|
||||||
<h1>DNSSEC</h1>
|
<h1>DNSSEC</h1>
|
||||||
|
|
||||||
<p>DNSSEC, or DNS Security Extensions, is additional security layer to protect your website. Enabling DNSSEC ensures that when someone visits your website, they can be certain that it’s connecting to the correct server, preventing potential hijacking or tampering with your domain's records.</p>
|
<p>DNSSEC, or DNS Security Extensions, is an additional security layer to protect your website. Enabling DNSSEC ensures that when someone visits your domain, they can be certain that it’s connecting to the correct server, preventing potential hijacking or tampering with your domain's records.</p>
|
||||||
|
|
||||||
<form class="usa-form usa-form--text-width" method="post">
|
<form class="usa-form usa-form--text-width" method="post">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
|
|
|
@ -29,7 +29,7 @@
|
||||||
{{ formset.management_form }}
|
{{ formset.management_form }}
|
||||||
|
|
||||||
{% for form in formset %}
|
{% for form in formset %}
|
||||||
<fieldset class="ds-record">
|
<fieldset class="repeatable-form">
|
||||||
|
|
||||||
<legend class="sr-only">DS Data record {{forloop.counter}}</legend>
|
<legend class="sr-only">DS Data record {{forloop.counter}}</legend>
|
||||||
|
|
||||||
|
@ -74,7 +74,7 @@
|
||||||
</fieldset>
|
</fieldset>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|
||||||
<button type="button" class="usa-button usa-button--unstyled display-block margin-bottom-2" id="add-ds-form">
|
<button type="button" class="usa-button usa-button--unstyled display-block margin-bottom-2" id="add-form">
|
||||||
<svg class="usa-icon" aria-hidden="true" focusable="false" role="img" width="24" height="24">
|
<svg class="usa-icon" aria-hidden="true" focusable="false" role="img" width="24" height="24">
|
||||||
<use xlink:href="{%static 'img/sprite.svg'%}#add_circle"></use>
|
<use xlink:href="{%static 'img/sprite.svg'%}#add_circle"></use>
|
||||||
</svg><span class="margin-left-05">Add new record</span>
|
</svg><span class="margin-left-05">Add new record</span>
|
||||||
|
|
|
@ -11,20 +11,31 @@
|
||||||
|
|
||||||
<h1>DNS name servers</h1>
|
<h1>DNS name servers</h1>
|
||||||
|
|
||||||
<p>Before your domain can be used we'll need information about your domain
|
<p>Before your domain can be used we’ll need information about your domain name servers. Name server records indicate which DNS server is authoritative for your domain.</p>
|
||||||
name servers.</p>
|
|
||||||
|
<p>Add a name server record by entering the address (e.g., ns1.nameserver.com) in the name server fields below. You must add at least two name servers (13 max).</p>
|
||||||
|
|
||||||
|
<div class="usa-alert usa-alert--slim usa-alert--info">
|
||||||
|
<div class="usa-alert__body">
|
||||||
|
<p class="margin-top-0">Add an IP address only when your name server's address includes your domain name (e.g., if your domain name is "example.gov" and your name server is "ns1.example.gov,” then an IP address is required.) To add multiple IP addresses, separate them with commas.</p>
|
||||||
|
<p class="margin-bottom-0">This step is uncommon unless you self-host your DNS or use custom addresses for your nameserver.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{% include "includes/required_fields.html" %}
|
{% include "includes/required_fields.html" %}
|
||||||
|
|
||||||
<form class="usa-form usa-form--large" method="post" novalidate id="form-container">
|
<form class="usa-form usa-form--extra-large" method="post" novalidate id="form-container">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{{ formset.management_form }}
|
{{ formset.management_form }}
|
||||||
|
|
||||||
{% for form in formset %}
|
{% for form in formset %}
|
||||||
<div class="server-form">
|
<div class="repeatable-form">
|
||||||
|
<div class="grid-row grid-gap-2 flex-end">
|
||||||
|
<div class="tablet:grid-col-5">
|
||||||
|
{{ form.domain }}
|
||||||
{% with sublabel_text="Example: ns"|concat:forloop.counter|concat:".example.com" %}
|
{% with sublabel_text="Example: ns"|concat:forloop.counter|concat:".example.com" %}
|
||||||
{% if forloop.counter <= 2 %}
|
{% if forloop.counter <= 2 %}
|
||||||
{% with attr_required=True %}
|
{% with attr_required=True add_group_class="usa-form-group--unstyled-error" %}
|
||||||
{% input_with_errors form.server %}
|
{% input_with_errors form.server %}
|
||||||
{% endwith %}
|
{% endwith %}
|
||||||
{% else %}
|
{% else %}
|
||||||
|
@ -32,19 +43,47 @@
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endwith %}
|
{% endwith %}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="tablet:grid-col-5">
|
||||||
|
{% with sublabel_text="Example: 86.124.49.54 or 2001:db8::1234:5678" add_group_class="usa-form-group--unstyled-error" %}
|
||||||
|
{% input_with_errors form.ip %}
|
||||||
|
{% endwith %}
|
||||||
|
</div>
|
||||||
|
<div class="tablet:grid-col-2">
|
||||||
|
{% comment %} TODO: remove this if for 1192 {% endcomment %}
|
||||||
|
{% if forloop.counter > 2 %}
|
||||||
|
<button type="button" class="usa-button usa-button--unstyled display-block delete-record margin-bottom-075">
|
||||||
|
<svg class="usa-icon" aria-hidden="true" focusable="false" role="img" width="24" height="24">
|
||||||
|
<use xlink:href="{%static 'img/sprite.svg'%}#delete"></use>
|
||||||
|
</svg><span class="margin-left-05">Delete</span>
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|
||||||
<button type="button" class="usa-button usa-button--unstyled display-block" id="add-nameserver-form">
|
<button type="button" class="usa-button usa-button--unstyled display-block" id="add-form">
|
||||||
<svg class="usa-icon" aria-hidden="true" focusable="false" role="img" width="24" height="24">
|
<svg class="usa-icon" aria-hidden="true" focusable="false" role="img" width="24" height="24">
|
||||||
<use xlink:href="{%static 'img/sprite.svg'%}#add_circle"></use>
|
<use xlink:href="{%static 'img/sprite.svg'%}#add_circle"></use>
|
||||||
</svg><span class="margin-left-05">Add another name server</span>
|
</svg><span class="margin-left-05">Add another name server</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{% comment %} Work around USWDS' button margins to add some spacing between the submit and the 'add more'
|
||||||
|
This solution still works when we remove the 'add more' at 13 forms {% endcomment %}
|
||||||
|
<div class="margin-top-2">
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
class="usa-button"
|
class="usa-button"
|
||||||
>Save
|
>Save
|
||||||
</button>
|
</button>
|
||||||
</form>
|
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="usa-button usa-button--outline"
|
||||||
|
name="btn-cancel-click"
|
||||||
|
aria-label="Reset the data in the Name Server form to the registry state (undo changes)"
|
||||||
|
>Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
{% endblock %} {# domain_content #}
|
{% endblock %} {# domain_content #}
|
||||||
|
|
|
@ -12,11 +12,13 @@
|
||||||
email, and DNS name servers.
|
email, and DNS name servers.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<ul>
|
<ul class="usa-list">
|
||||||
<li>There is no limit to the number of domain managers you can add.</li>
|
<li>There is no limit to the number of domain managers you can add.</li>
|
||||||
<li>After adding a domain manager, an email invitation will be sent to that user with
|
<li>After adding a domain manager, an email invitation will be sent to that user with
|
||||||
instructions on how to set up an account.</li>
|
instructions on how to set up an account.</li>
|
||||||
<li>To remove a domain manager, <a href="{% public_site_url 'contact/' %}" class="usa-link">contact us</a> for assistance.
|
<li>To remove a domain manager, <a href="{% public_site_url 'contact/' %}"
|
||||||
|
target="_blank" rel="noopener noreferrer" class="usa-link">contact us</a> for
|
||||||
|
assistance.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
{% if domain.permissions %}
|
{% if domain.permissions %}
|
||||||
|
|
|
@ -43,7 +43,6 @@
|
||||||
{% else %}
|
{% else %}
|
||||||
{% include "includes/contact.html" with contact=value %}
|
{% include "includes/contact.html" with contact=value %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<!-- TODO #687 add here another elif for nameservers to show item Ips -->
|
|
||||||
{% elif list %}
|
{% elif list %}
|
||||||
{% if value|length == 1 %}
|
{% if value|length == 1 %}
|
||||||
{% if users %}
|
{% if users %}
|
||||||
|
@ -56,6 +55,17 @@
|
||||||
{% for item in value %}
|
{% for item in value %}
|
||||||
{% if users %}
|
{% if users %}
|
||||||
<li>{{ item.user.email }}</li>
|
<li>{{ item.user.email }}</li>
|
||||||
|
{% elif domains %}
|
||||||
|
<li>
|
||||||
|
{{ item.0 }}
|
||||||
|
{% if item.1 %}
|
||||||
|
({% spaceless %}
|
||||||
|
{% for addr in item.1 %}
|
||||||
|
{{addr}}{% if not forloop.last %}, {% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% endspaceless %})
|
||||||
|
{% endif %}
|
||||||
|
</li>
|
||||||
{% else %}
|
{% else %}
|
||||||
<li>{{ item }}</li>
|
<li>{{ item }}</li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
|
@ -738,6 +738,7 @@ class MockEppLib(TestCase):
|
||||||
"ns1.cats-are-superior3.com",
|
"ns1.cats-are-superior3.com",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
infoDomainNoHost = fakedEppObject(
|
infoDomainNoHost = fakedEppObject(
|
||||||
"my-nameserver.gov",
|
"my-nameserver.gov",
|
||||||
cr_date=datetime.datetime(2023, 5, 25, 19, 45, 35),
|
cr_date=datetime.datetime(2023, 5, 25, 19, 45, 35),
|
||||||
|
@ -755,7 +756,7 @@ class MockEppLib(TestCase):
|
||||||
mockDataInfoHosts = fakedEppObject(
|
mockDataInfoHosts = fakedEppObject(
|
||||||
"lastPw",
|
"lastPw",
|
||||||
cr_date=datetime.datetime(2023, 8, 25, 19, 45, 35),
|
cr_date=datetime.datetime(2023, 8, 25, 19, 45, 35),
|
||||||
addrs=["1.2.3.4", "2.3.4.5"],
|
addrs=[common.Ip(addr="1.2.3.4"), common.Ip(addr="2.3.4.5")],
|
||||||
)
|
)
|
||||||
|
|
||||||
mockDataHostChange = fakedEppObject(
|
mockDataHostChange = fakedEppObject(
|
||||||
|
@ -793,13 +794,49 @@ class MockEppLib(TestCase):
|
||||||
infoDomainHasIP = fakedEppObject(
|
infoDomainHasIP = fakedEppObject(
|
||||||
"nameserverwithip.gov",
|
"nameserverwithip.gov",
|
||||||
cr_date=datetime.datetime(2023, 5, 25, 19, 45, 35),
|
cr_date=datetime.datetime(2023, 5, 25, 19, 45, 35),
|
||||||
contacts=[],
|
contacts=[
|
||||||
|
common.DomainContact(
|
||||||
|
contact="securityContact",
|
||||||
|
type=PublicContact.ContactTypeChoices.SECURITY,
|
||||||
|
),
|
||||||
|
common.DomainContact(
|
||||||
|
contact="technicalContact",
|
||||||
|
type=PublicContact.ContactTypeChoices.TECHNICAL,
|
||||||
|
),
|
||||||
|
common.DomainContact(
|
||||||
|
contact="adminContact",
|
||||||
|
type=PublicContact.ContactTypeChoices.ADMINISTRATIVE,
|
||||||
|
),
|
||||||
|
],
|
||||||
hosts=[
|
hosts=[
|
||||||
"ns1.nameserverwithip.gov",
|
"ns1.nameserverwithip.gov",
|
||||||
"ns2.nameserverwithip.gov",
|
"ns2.nameserverwithip.gov",
|
||||||
"ns3.nameserverwithip.gov",
|
"ns3.nameserverwithip.gov",
|
||||||
],
|
],
|
||||||
addrs=["1.2.3.4", "2.3.4.5"],
|
addrs=[common.Ip(addr="1.2.3.4"), common.Ip(addr="2.3.4.5")],
|
||||||
|
)
|
||||||
|
|
||||||
|
justNameserver = fakedEppObject(
|
||||||
|
"justnameserver.com",
|
||||||
|
cr_date=datetime.datetime(2023, 5, 25, 19, 45, 35),
|
||||||
|
contacts=[
|
||||||
|
common.DomainContact(
|
||||||
|
contact="securityContact",
|
||||||
|
type=PublicContact.ContactTypeChoices.SECURITY,
|
||||||
|
),
|
||||||
|
common.DomainContact(
|
||||||
|
contact="technicalContact",
|
||||||
|
type=PublicContact.ContactTypeChoices.TECHNICAL,
|
||||||
|
),
|
||||||
|
common.DomainContact(
|
||||||
|
contact="adminContact",
|
||||||
|
type=PublicContact.ContactTypeChoices.ADMINISTRATIVE,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
hosts=[
|
||||||
|
"ns1.justnameserver.com",
|
||||||
|
"ns2.justnameserver.com",
|
||||||
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
infoDomainCheckHostIPCombo = fakedEppObject(
|
infoDomainCheckHostIPCombo = fakedEppObject(
|
||||||
|
@ -823,11 +860,17 @@ class MockEppLib(TestCase):
|
||||||
|
|
||||||
def mockCheckDomainCommand(self, _request, cleaned):
|
def mockCheckDomainCommand(self, _request, cleaned):
|
||||||
if "gsa.gov" in getattr(_request, "names", None):
|
if "gsa.gov" in getattr(_request, "names", None):
|
||||||
return self._mockDomainName("gsa.gov", True)
|
return self._mockDomainName("gsa.gov", False)
|
||||||
elif "GSA.gov" in getattr(_request, "names", None):
|
elif "GSA.gov" in getattr(_request, "names", None):
|
||||||
return self._mockDomainName("GSA.gov", True)
|
return self._mockDomainName("GSA.gov", False)
|
||||||
elif "igorvilleremixed.gov" in getattr(_request, "names", None):
|
elif "igorville.gov" in getattr(_request, "names", None):
|
||||||
return self._mockDomainName("igorvilleremixed.gov", False)
|
return self._mockDomainName("igorvilleremixed.gov", True)
|
||||||
|
elif "top-level-agency.gov" in getattr(_request, "names", None):
|
||||||
|
return self._mockDomainName("top-level-agency.gov", True)
|
||||||
|
elif "city.gov" in getattr(_request, "names", None):
|
||||||
|
return self._mockDomainName("city.gov", True)
|
||||||
|
elif "city1.gov" in getattr(_request, "names", None):
|
||||||
|
return self._mockDomainName("city1.gov", True)
|
||||||
elif "errordomain.gov" in getattr(_request, "names", None):
|
elif "errordomain.gov" in getattr(_request, "names", None):
|
||||||
raise RegistryError("Registry cannot find domain availability.")
|
raise RegistryError("Registry cannot find domain availability.")
|
||||||
else:
|
else:
|
||||||
|
@ -916,6 +959,7 @@ class MockEppLib(TestCase):
|
||||||
"threenameserversDomain.gov": (self.infoDomainThreeHosts, None),
|
"threenameserversDomain.gov": (self.infoDomainThreeHosts, None),
|
||||||
"defaultsecurity.gov": (self.InfoDomainWithDefaultSecurityContact, None),
|
"defaultsecurity.gov": (self.InfoDomainWithDefaultSecurityContact, None),
|
||||||
"defaulttechnical.gov": (self.InfoDomainWithDefaultTechnicalContact, None),
|
"defaulttechnical.gov": (self.InfoDomainWithDefaultTechnicalContact, None),
|
||||||
|
"justnameserver.com": (self.justNameserver, None),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Retrieve the corresponding values from the dictionary
|
# Retrieve the corresponding values from the dictionary
|
||||||
|
|
|
@ -56,7 +56,7 @@ class TestDomainCache(MockEppLib):
|
||||||
self.assertFalse("avail" in domain._cache.keys())
|
self.assertFalse("avail" in domain._cache.keys())
|
||||||
|
|
||||||
# using a setter should clear the cache
|
# using a setter should clear the cache
|
||||||
domain.expiration_date = datetime.date.today()
|
domain.registry_expiration_date = datetime.date.today()
|
||||||
self.assertEquals(domain._cache, {})
|
self.assertEquals(domain._cache, {})
|
||||||
|
|
||||||
# send should have been called only once
|
# send should have been called only once
|
||||||
|
@ -107,7 +107,7 @@ class TestDomainCache(MockEppLib):
|
||||||
}
|
}
|
||||||
expectedHostsDict = {
|
expectedHostsDict = {
|
||||||
"name": self.mockDataInfoDomain.hosts[0],
|
"name": self.mockDataInfoDomain.hosts[0],
|
||||||
"addrs": self.mockDataInfoHosts.addrs,
|
"addrs": [item.addr for item in self.mockDataInfoHosts.addrs],
|
||||||
"cr_date": self.mockDataInfoHosts.cr_date,
|
"cr_date": self.mockDataInfoHosts.cr_date,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -10,10 +10,7 @@ class TestNameserverError(TestCase):
|
||||||
def test_with_no_ip(self):
|
def test_with_no_ip(self):
|
||||||
"""Test NameserverError when no ip address is passed"""
|
"""Test NameserverError when no ip address is passed"""
|
||||||
nameserver = "nameserver val"
|
nameserver = "nameserver val"
|
||||||
expected = (
|
expected = "Using your domain for a name server requires an IP address"
|
||||||
f"Nameserver {nameserver} needs to have an "
|
|
||||||
"IP address because it is a subdomain"
|
|
||||||
)
|
|
||||||
|
|
||||||
nsException = NameserverError(
|
nsException = NameserverError(
|
||||||
code=nsErrorCodes.MISSING_IP, nameserver=nameserver
|
code=nsErrorCodes.MISSING_IP, nameserver=nameserver
|
||||||
|
@ -38,7 +35,7 @@ class TestNameserverError(TestCase):
|
||||||
ip = "ip val"
|
ip = "ip val"
|
||||||
nameserver = "nameserver val"
|
nameserver = "nameserver val"
|
||||||
|
|
||||||
expected = f"Nameserver {nameserver} has an invalid IP address: {ip}"
|
expected = f"{nameserver}: Enter an IP address in the required format."
|
||||||
nsException = NameserverError(
|
nsException = NameserverError(
|
||||||
code=nsErrorCodes.INVALID_IP, nameserver=nameserver, ip=ip
|
code=nsErrorCodes.INVALID_IP, nameserver=nameserver, ip=ip
|
||||||
)
|
)
|
||||||
|
|
|
@ -110,12 +110,13 @@ class TestURLAuth(TestCase):
|
||||||
# Note that the trailing slash is wobbly depending on how the URL was defined.
|
# Note that the trailing slash is wobbly depending on how the URL was defined.
|
||||||
IGNORE_URLS = [
|
IGNORE_URLS = [
|
||||||
# These are the OIDC auth endpoints that always need
|
# These are the OIDC auth endpoints that always need
|
||||||
# to be public.
|
# to be public. Use the exact URLs that will be tested.
|
||||||
"/openid/login/",
|
"/openid/login/",
|
||||||
"/openid/logout/",
|
"/openid/logout/",
|
||||||
"/openid/callback",
|
"/openid/callback",
|
||||||
"/openid/callback/login/",
|
"/openid/callback/login/",
|
||||||
"/openid/callback/logout/",
|
"/openid/callback/logout/",
|
||||||
|
"/api/v1/available/whitehouse.gov",
|
||||||
]
|
]
|
||||||
|
|
||||||
def assertURLIsProtectedByAuth(self, url):
|
def assertURLIsProtectedByAuth(self, url):
|
||||||
|
|
|
@ -10,6 +10,10 @@ from .common import MockEppLib, completed_application # type: ignore
|
||||||
from django_webtest import WebTest # type: ignore
|
from django_webtest import WebTest # type: ignore
|
||||||
import boto3_mocking # type: ignore
|
import boto3_mocking # type: ignore
|
||||||
|
|
||||||
|
from registrar.utility.errors import (
|
||||||
|
NameserverError,
|
||||||
|
NameserverErrorCodes,
|
||||||
|
)
|
||||||
|
|
||||||
from registrar.models import (
|
from registrar.models import (
|
||||||
DomainApplication,
|
DomainApplication,
|
||||||
|
@ -1095,6 +1099,13 @@ class TestWithDomainPermissions(TestWithUser):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp()
|
super().setUp()
|
||||||
self.domain, _ = Domain.objects.get_or_create(name="igorville.gov")
|
self.domain, _ = Domain.objects.get_or_create(name="igorville.gov")
|
||||||
|
self.domain_with_ip, _ = Domain.objects.get_or_create(
|
||||||
|
name="nameserverwithip.gov"
|
||||||
|
)
|
||||||
|
self.domain_just_nameserver, _ = Domain.objects.get_or_create(
|
||||||
|
name="justnameserver.com"
|
||||||
|
)
|
||||||
|
|
||||||
self.domain_dsdata, _ = Domain.objects.get_or_create(name="dnssec-dsdata.gov")
|
self.domain_dsdata, _ = Domain.objects.get_or_create(name="dnssec-dsdata.gov")
|
||||||
self.domain_multdsdata, _ = Domain.objects.get_or_create(
|
self.domain_multdsdata, _ = Domain.objects.get_or_create(
|
||||||
name="dnssec-multdsdata.gov"
|
name="dnssec-multdsdata.gov"
|
||||||
|
@ -1104,9 +1115,11 @@ class TestWithDomainPermissions(TestWithUser):
|
||||||
self.domain_dnssec_none, _ = Domain.objects.get_or_create(
|
self.domain_dnssec_none, _ = Domain.objects.get_or_create(
|
||||||
name="dnssec-none.gov"
|
name="dnssec-none.gov"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.domain_information, _ = DomainInformation.objects.get_or_create(
|
self.domain_information, _ = DomainInformation.objects.get_or_create(
|
||||||
creator=self.user, domain=self.domain
|
creator=self.user, domain=self.domain
|
||||||
)
|
)
|
||||||
|
|
||||||
DomainInformation.objects.get_or_create(
|
DomainInformation.objects.get_or_create(
|
||||||
creator=self.user, domain=self.domain_dsdata
|
creator=self.user, domain=self.domain_dsdata
|
||||||
)
|
)
|
||||||
|
@ -1116,9 +1129,17 @@ class TestWithDomainPermissions(TestWithUser):
|
||||||
DomainInformation.objects.get_or_create(
|
DomainInformation.objects.get_or_create(
|
||||||
creator=self.user, domain=self.domain_dnssec_none
|
creator=self.user, domain=self.domain_dnssec_none
|
||||||
)
|
)
|
||||||
|
DomainInformation.objects.get_or_create(
|
||||||
|
creator=self.user, domain=self.domain_with_ip
|
||||||
|
)
|
||||||
|
DomainInformation.objects.get_or_create(
|
||||||
|
creator=self.user, domain=self.domain_just_nameserver
|
||||||
|
)
|
||||||
|
|
||||||
self.role, _ = UserDomainRole.objects.get_or_create(
|
self.role, _ = UserDomainRole.objects.get_or_create(
|
||||||
user=self.user, domain=self.domain, role=UserDomainRole.Roles.MANAGER
|
user=self.user, domain=self.domain, role=UserDomainRole.Roles.MANAGER
|
||||||
)
|
)
|
||||||
|
|
||||||
UserDomainRole.objects.get_or_create(
|
UserDomainRole.objects.get_or_create(
|
||||||
user=self.user, domain=self.domain_dsdata, role=UserDomainRole.Roles.MANAGER
|
user=self.user, domain=self.domain_dsdata, role=UserDomainRole.Roles.MANAGER
|
||||||
)
|
)
|
||||||
|
@ -1132,6 +1153,16 @@ class TestWithDomainPermissions(TestWithUser):
|
||||||
domain=self.domain_dnssec_none,
|
domain=self.domain_dnssec_none,
|
||||||
role=UserDomainRole.Roles.MANAGER,
|
role=UserDomainRole.Roles.MANAGER,
|
||||||
)
|
)
|
||||||
|
UserDomainRole.objects.get_or_create(
|
||||||
|
user=self.user,
|
||||||
|
domain=self.domain_with_ip,
|
||||||
|
role=UserDomainRole.Roles.MANAGER,
|
||||||
|
)
|
||||||
|
UserDomainRole.objects.get_or_create(
|
||||||
|
user=self.user,
|
||||||
|
domain=self.domain_just_nameserver,
|
||||||
|
role=UserDomainRole.Roles.MANAGER,
|
||||||
|
)
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
try:
|
try:
|
||||||
|
@ -1215,6 +1246,37 @@ class TestDomainOverview(TestWithDomainPermissions, WebTest):
|
||||||
response = self.client.get(reverse("domain", kwargs={"pk": self.domain.id}))
|
response = self.client.get(reverse("domain", kwargs={"pk": self.domain.id}))
|
||||||
self.assertEqual(response.status_code, 403)
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|
||||||
|
def test_domain_see_just_nameserver(self):
|
||||||
|
home_page = self.app.get("/")
|
||||||
|
self.assertContains(home_page, "justnameserver.com")
|
||||||
|
|
||||||
|
# View nameserver on Domain Overview page
|
||||||
|
detail_page = self.app.get(
|
||||||
|
reverse("domain", kwargs={"pk": self.domain_just_nameserver.id})
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertContains(detail_page, "justnameserver.com")
|
||||||
|
self.assertContains(detail_page, "ns1.justnameserver.com")
|
||||||
|
self.assertContains(detail_page, "ns2.justnameserver.com")
|
||||||
|
|
||||||
|
def test_domain_see_nameserver_and_ip(self):
|
||||||
|
home_page = self.app.get("/")
|
||||||
|
self.assertContains(home_page, "nameserverwithip.gov")
|
||||||
|
|
||||||
|
# View nameserver on Domain Overview page
|
||||||
|
detail_page = self.app.get(
|
||||||
|
reverse("domain", kwargs={"pk": self.domain_with_ip.id})
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertContains(detail_page, "nameserverwithip.gov")
|
||||||
|
|
||||||
|
self.assertContains(detail_page, "ns1.nameserverwithip.gov")
|
||||||
|
self.assertContains(detail_page, "ns2.nameserverwithip.gov")
|
||||||
|
self.assertContains(detail_page, "ns3.nameserverwithip.gov")
|
||||||
|
# Splitting IP addresses bc there is odd whitespace and can't strip text
|
||||||
|
self.assertContains(detail_page, "(1.2.3.4,")
|
||||||
|
self.assertContains(detail_page, "2.3.4.5)")
|
||||||
|
|
||||||
|
|
||||||
class TestDomainManagers(TestDomainOverview):
|
class TestDomainManagers(TestDomainOverview):
|
||||||
def test_domain_managers(self):
|
def test_domain_managers(self):
|
||||||
|
@ -1384,20 +1446,165 @@ class TestDomainNameservers(TestDomainOverview):
|
||||||
)
|
)
|
||||||
self.assertContains(page, "DNS name servers")
|
self.assertContains(page, "DNS name servers")
|
||||||
|
|
||||||
@skip("Broken by adding registry connection fix in ticket 848")
|
def test_domain_nameservers_form_submit_one_nameserver(self):
|
||||||
def test_domain_nameservers_form(self):
|
"""Nameserver form submitted with one nameserver throws error.
|
||||||
"""Can change domain's nameservers.
|
|
||||||
|
|
||||||
Uses self.app WebTest because we need to interact with forms.
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
"""
|
"""
|
||||||
|
# initial nameservers page has one server with two ips
|
||||||
nameservers_page = self.app.get(
|
nameservers_page = self.app.get(
|
||||||
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
||||||
)
|
)
|
||||||
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
||||||
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
||||||
|
# attempt to submit the form with only one nameserver, should error
|
||||||
|
# regarding required fields
|
||||||
with less_console_noise(): # swallow log warning message
|
with less_console_noise(): # swallow log warning message
|
||||||
result = nameservers_page.form.submit()
|
result = nameservers_page.form.submit()
|
||||||
# form submission was a post, response should be a redirect
|
# form submission was a post with an error, response should be a 200
|
||||||
|
# error text appears twice, once at the top of the page, once around
|
||||||
|
# the required field. form requires a minimum of 2 name servers
|
||||||
|
self.assertContains(result, "This field is required.", count=2, status_code=200)
|
||||||
|
|
||||||
|
def test_domain_nameservers_form_submit_subdomain_missing_ip(self):
|
||||||
|
"""Nameserver form catches missing ip error on subdomain.
|
||||||
|
|
||||||
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
|
"""
|
||||||
|
# initial nameservers page has one server with two ips
|
||||||
|
nameservers_page = self.app.get(
|
||||||
|
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
||||||
|
)
|
||||||
|
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
||||||
|
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
||||||
|
# attempt to submit the form without two hosts, both subdomains,
|
||||||
|
# only one has ips
|
||||||
|
nameservers_page.form["form-1-server"] = "ns2.igorville.gov"
|
||||||
|
with less_console_noise(): # swallow log warning message
|
||||||
|
result = nameservers_page.form.submit()
|
||||||
|
# form submission was a post with an error, response should be a 200
|
||||||
|
# error text appears twice, once at the top of the page, once around
|
||||||
|
# the required field. subdomain missing an ip
|
||||||
|
self.assertContains(
|
||||||
|
result,
|
||||||
|
str(NameserverError(code=NameserverErrorCodes.MISSING_IP)),
|
||||||
|
count=2,
|
||||||
|
status_code=200,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_domain_nameservers_form_submit_missing_host(self):
|
||||||
|
"""Nameserver form catches error when host is missing.
|
||||||
|
|
||||||
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
|
"""
|
||||||
|
# initial nameservers page has one server with two ips
|
||||||
|
nameservers_page = self.app.get(
|
||||||
|
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
||||||
|
)
|
||||||
|
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
||||||
|
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
||||||
|
# attempt to submit the form without two hosts, both subdomains,
|
||||||
|
# only one has ips
|
||||||
|
nameservers_page.form["form-1-ip"] = "127.0.0.1"
|
||||||
|
with less_console_noise(): # swallow log warning message
|
||||||
|
result = nameservers_page.form.submit()
|
||||||
|
# form submission was a post with an error, response should be a 200
|
||||||
|
# error text appears twice, once at the top of the page, once around
|
||||||
|
# the required field. nameserver has ip but missing host
|
||||||
|
self.assertContains(
|
||||||
|
result,
|
||||||
|
str(NameserverError(code=NameserverErrorCodes.MISSING_HOST)),
|
||||||
|
count=2,
|
||||||
|
status_code=200,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_domain_nameservers_form_submit_glue_record_not_allowed(self):
|
||||||
|
"""Nameserver form catches error when IP is present
|
||||||
|
but host not subdomain.
|
||||||
|
|
||||||
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
|
"""
|
||||||
|
nameserver1 = "ns1.igorville.gov"
|
||||||
|
nameserver2 = "ns2.igorville.com"
|
||||||
|
valid_ip = "127.0.0.1"
|
||||||
|
# initial nameservers page has one server with two ips
|
||||||
|
nameservers_page = self.app.get(
|
||||||
|
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
||||||
|
)
|
||||||
|
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
||||||
|
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
||||||
|
# attempt to submit the form without two hosts, both subdomains,
|
||||||
|
# only one has ips
|
||||||
|
nameservers_page.form["form-0-server"] = nameserver1
|
||||||
|
nameservers_page.form["form-1-server"] = nameserver2
|
||||||
|
nameservers_page.form["form-1-ip"] = valid_ip
|
||||||
|
with less_console_noise(): # swallow log warning message
|
||||||
|
result = nameservers_page.form.submit()
|
||||||
|
# form submission was a post with an error, response should be a 200
|
||||||
|
# error text appears twice, once at the top of the page, once around
|
||||||
|
# the required field. nameserver has ip but missing host
|
||||||
|
self.assertContains(
|
||||||
|
result,
|
||||||
|
str(NameserverError(code=NameserverErrorCodes.GLUE_RECORD_NOT_ALLOWED)),
|
||||||
|
count=2,
|
||||||
|
status_code=200,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_domain_nameservers_form_submit_invalid_ip(self):
|
||||||
|
"""Nameserver form catches invalid IP on submission.
|
||||||
|
|
||||||
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
|
"""
|
||||||
|
nameserver = "ns2.igorville.gov"
|
||||||
|
invalid_ip = "123"
|
||||||
|
# initial nameservers page has one server with two ips
|
||||||
|
nameservers_page = self.app.get(
|
||||||
|
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
||||||
|
)
|
||||||
|
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
||||||
|
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
||||||
|
# attempt to submit the form without two hosts, both subdomains,
|
||||||
|
# only one has ips
|
||||||
|
nameservers_page.form["form-1-server"] = nameserver
|
||||||
|
nameservers_page.form["form-1-ip"] = invalid_ip
|
||||||
|
with less_console_noise(): # swallow log warning message
|
||||||
|
result = nameservers_page.form.submit()
|
||||||
|
# form submission was a post with an error, response should be a 200
|
||||||
|
# error text appears twice, once at the top of the page, once around
|
||||||
|
# the required field. nameserver has ip but missing host
|
||||||
|
self.assertContains(
|
||||||
|
result,
|
||||||
|
str(
|
||||||
|
NameserverError(
|
||||||
|
code=NameserverErrorCodes.INVALID_IP, nameserver=nameserver
|
||||||
|
)
|
||||||
|
),
|
||||||
|
count=2,
|
||||||
|
status_code=200,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_domain_nameservers_form_submits_successfully(self):
|
||||||
|
"""Nameserver form submits successfully with valid input.
|
||||||
|
|
||||||
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
|
"""
|
||||||
|
nameserver1 = "ns1.igorville.gov"
|
||||||
|
nameserver2 = "ns2.igorville.gov"
|
||||||
|
invalid_ip = "127.0.0.1"
|
||||||
|
# initial nameservers page has one server with two ips
|
||||||
|
nameservers_page = self.app.get(
|
||||||
|
reverse("domain-dns-nameservers", kwargs={"pk": self.domain.id})
|
||||||
|
)
|
||||||
|
session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
|
||||||
|
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
|
||||||
|
# attempt to submit the form without two hosts, both subdomains,
|
||||||
|
# only one has ips
|
||||||
|
nameservers_page.form["form-0-server"] = nameserver1
|
||||||
|
nameservers_page.form["form-1-server"] = nameserver2
|
||||||
|
nameservers_page.form["form-1-ip"] = invalid_ip
|
||||||
|
with less_console_noise(): # swallow log warning message
|
||||||
|
result = nameservers_page.form.submit()
|
||||||
|
# form submission was a successful post, response should be a 302
|
||||||
self.assertEqual(result.status_code, 302)
|
self.assertEqual(result.status_code, 302)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
result["Location"],
|
result["Location"],
|
||||||
|
@ -1407,9 +1614,8 @@ class TestDomainNameservers(TestDomainOverview):
|
||||||
page = result.follow()
|
page = result.follow()
|
||||||
self.assertContains(page, "The name servers for this domain have been updated")
|
self.assertContains(page, "The name servers for this domain have been updated")
|
||||||
|
|
||||||
@skip("Broken by adding registry connection fix in ticket 848")
|
|
||||||
def test_domain_nameservers_form_invalid(self):
|
def test_domain_nameservers_form_invalid(self):
|
||||||
"""Can change domain's nameservers.
|
"""Nameserver form does not submit with invalid data.
|
||||||
|
|
||||||
Uses self.app WebTest because we need to interact with forms.
|
Uses self.app WebTest because we need to interact with forms.
|
||||||
"""
|
"""
|
||||||
|
@ -1424,9 +1630,9 @@ class TestDomainNameservers(TestDomainOverview):
|
||||||
with less_console_noise(): # swallow logged warning message
|
with less_console_noise(): # swallow logged warning message
|
||||||
result = nameservers_page.form.submit()
|
result = nameservers_page.form.submit()
|
||||||
# form submission was a post with an error, response should be a 200
|
# form submission was a post with an error, response should be a 200
|
||||||
# error text appears twice, once at the top of the page, once around
|
# error text appears four times, twice at the top of the page,
|
||||||
# the field.
|
# once around each required field.
|
||||||
self.assertContains(result, "This field is required", count=2, status_code=200)
|
self.assertContains(result, "This field is required", count=4, status_code=200)
|
||||||
|
|
||||||
|
|
||||||
class TestDomainAuthorizingOfficial(TestDomainOverview):
|
class TestDomainAuthorizingOfficial(TestDomainOverview):
|
||||||
|
|
|
@ -20,6 +20,41 @@ class ActionNotAllowed(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class GenericErrorCodes(IntEnum):
|
||||||
|
"""Used across the registrar for
|
||||||
|
error mapping.
|
||||||
|
Overview of generic error codes:
|
||||||
|
- 1 GENERIC_ERROR a generic value error
|
||||||
|
- 2 CANNOT_CONTACT_REGISTRY a connection error w registry
|
||||||
|
"""
|
||||||
|
|
||||||
|
GENERIC_ERROR = 1
|
||||||
|
CANNOT_CONTACT_REGISTRY = 2
|
||||||
|
|
||||||
|
|
||||||
|
class GenericError(Exception):
|
||||||
|
"""
|
||||||
|
GenericError class used to raise exceptions across
|
||||||
|
the registrar
|
||||||
|
"""
|
||||||
|
|
||||||
|
_error_mapping = {
|
||||||
|
GenericErrorCodes.CANNOT_CONTACT_REGISTRY: (
|
||||||
|
"Update failed. Cannot contact the registry."
|
||||||
|
),
|
||||||
|
GenericErrorCodes.GENERIC_ERROR: ("Value entered was wrong."),
|
||||||
|
}
|
||||||
|
|
||||||
|
def __init__(self, *args, code=None, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.code = code
|
||||||
|
if self.code in self._error_mapping:
|
||||||
|
self.message = self._error_mapping.get(self.code)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"{self.message}"
|
||||||
|
|
||||||
|
|
||||||
class NameserverErrorCodes(IntEnum):
|
class NameserverErrorCodes(IntEnum):
|
||||||
"""Used in the NameserverError class for
|
"""Used in the NameserverError class for
|
||||||
error mapping.
|
error mapping.
|
||||||
|
@ -29,6 +64,8 @@ class NameserverErrorCodes(IntEnum):
|
||||||
value but is not a subdomain
|
value but is not a subdomain
|
||||||
- 3 INVALID_IP invalid ip address format or invalid version
|
- 3 INVALID_IP invalid ip address format or invalid version
|
||||||
- 4 TOO_MANY_HOSTS more than the max allowed host values
|
- 4 TOO_MANY_HOSTS more than the max allowed host values
|
||||||
|
- 5 UNABLE_TO_UPDATE_DOMAIN unable to update the domain
|
||||||
|
- 6 MISSING_HOST host is missing for a nameserver
|
||||||
"""
|
"""
|
||||||
|
|
||||||
MISSING_IP = 1
|
MISSING_IP = 1
|
||||||
|
@ -36,6 +73,7 @@ class NameserverErrorCodes(IntEnum):
|
||||||
INVALID_IP = 3
|
INVALID_IP = 3
|
||||||
TOO_MANY_HOSTS = 4
|
TOO_MANY_HOSTS = 4
|
||||||
UNABLE_TO_UPDATE_DOMAIN = 5
|
UNABLE_TO_UPDATE_DOMAIN = 5
|
||||||
|
MISSING_HOST = 6
|
||||||
|
|
||||||
|
|
||||||
class NameserverError(Exception):
|
class NameserverError(Exception):
|
||||||
|
@ -45,11 +83,15 @@ class NameserverError(Exception):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_error_mapping = {
|
_error_mapping = {
|
||||||
NameserverErrorCodes.MISSING_IP: "Nameserver {} needs to have an "
|
NameserverErrorCodes.MISSING_IP: (
|
||||||
"IP address because it is a subdomain",
|
"Using your domain for a name server requires an IP address"
|
||||||
NameserverErrorCodes.GLUE_RECORD_NOT_ALLOWED: "Nameserver {} cannot be linked "
|
),
|
||||||
"because it is not a subdomain",
|
NameserverErrorCodes.GLUE_RECORD_NOT_ALLOWED: (
|
||||||
NameserverErrorCodes.INVALID_IP: "Nameserver {} has an invalid IP address: {}",
|
"Name server address does not match domain name"
|
||||||
|
),
|
||||||
|
NameserverErrorCodes.INVALID_IP: (
|
||||||
|
"{}: Enter an IP address in the required format."
|
||||||
|
),
|
||||||
NameserverErrorCodes.TOO_MANY_HOSTS: (
|
NameserverErrorCodes.TOO_MANY_HOSTS: (
|
||||||
"Too many hosts provided, you may not have more than 13 nameservers."
|
"Too many hosts provided, you may not have more than 13 nameservers."
|
||||||
),
|
),
|
||||||
|
@ -57,6 +99,9 @@ class NameserverError(Exception):
|
||||||
"Unable to update domain, changes were not applied."
|
"Unable to update domain, changes were not applied."
|
||||||
"Check logs as a Registry Error is the likely cause"
|
"Check logs as a Registry Error is the likely cause"
|
||||||
),
|
),
|
||||||
|
NameserverErrorCodes.MISSING_HOST: (
|
||||||
|
"Name server must be provided to enter IP address."
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, *args, code=None, nameserver=None, ip=None, **kwargs):
|
def __init__(self, *args, code=None, nameserver=None, ip=None, **kwargs):
|
||||||
|
@ -65,7 +110,7 @@ class NameserverError(Exception):
|
||||||
if self.code in self._error_mapping:
|
if self.code in self._error_mapping:
|
||||||
self.message = self._error_mapping.get(self.code)
|
self.message = self._error_mapping.get(self.code)
|
||||||
if nameserver is not None and ip is not None:
|
if nameserver is not None and ip is not None:
|
||||||
self.message = self.message.format(str(nameserver), str(ip))
|
self.message = self.message.format(str(nameserver))
|
||||||
elif nameserver is not None:
|
elif nameserver is not None:
|
||||||
self.message = self.message.format(str(nameserver))
|
self.message = self.message.format(str(nameserver))
|
||||||
elif ip is not None:
|
elif ip is not None:
|
||||||
|
|
|
@ -23,6 +23,12 @@ from registrar.models import (
|
||||||
UserDomainRole,
|
UserDomainRole,
|
||||||
)
|
)
|
||||||
from registrar.models.public_contact import PublicContact
|
from registrar.models.public_contact import PublicContact
|
||||||
|
from registrar.utility.errors import (
|
||||||
|
GenericError,
|
||||||
|
GenericErrorCodes,
|
||||||
|
NameserverError,
|
||||||
|
NameserverErrorCodes as nsErrorCodes,
|
||||||
|
)
|
||||||
from registrar.models.utility.contact_error import ContactError
|
from registrar.models.utility.contact_error import ContactError
|
||||||
|
|
||||||
from ..forms import (
|
from ..forms import (
|
||||||
|
@ -40,8 +46,6 @@ from epplibwrapper import (
|
||||||
common,
|
common,
|
||||||
extensions,
|
extensions,
|
||||||
RegistryError,
|
RegistryError,
|
||||||
CANNOT_CONTACT_REGISTRY,
|
|
||||||
GENERIC_ERROR,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
from ..utility.email import send_templated_email, EmailSendingError
|
from ..utility.email import send_templated_email, EmailSendingError
|
||||||
|
@ -215,6 +219,7 @@ class DomainNameserversView(DomainFormBaseView):
|
||||||
|
|
||||||
template_name = "domain_nameservers.html"
|
template_name = "domain_nameservers.html"
|
||||||
form_class = NameserverFormset
|
form_class = NameserverFormset
|
||||||
|
model = Domain
|
||||||
|
|
||||||
def get_initial(self):
|
def get_initial(self):
|
||||||
"""The initial value for the form (which is a formset here)."""
|
"""The initial value for the form (which is a formset here)."""
|
||||||
|
@ -223,7 +228,9 @@ class DomainNameserversView(DomainFormBaseView):
|
||||||
|
|
||||||
if nameservers is not None:
|
if nameservers is not None:
|
||||||
# Add existing nameservers as initial data
|
# Add existing nameservers as initial data
|
||||||
initial_data.extend({"server": name} for name, *ip in nameservers)
|
initial_data.extend(
|
||||||
|
{"server": name, "ip": ",".join(ip)} for name, ip in nameservers
|
||||||
|
)
|
||||||
|
|
||||||
# Ensure at least 3 fields, filled or empty
|
# Ensure at least 3 fields, filled or empty
|
||||||
while len(initial_data) < 2:
|
while len(initial_data) < 2:
|
||||||
|
@ -252,24 +259,81 @@ class DomainNameserversView(DomainFormBaseView):
|
||||||
form.fields["server"].required = True
|
form.fields["server"].required = True
|
||||||
else:
|
else:
|
||||||
form.fields["server"].required = False
|
form.fields["server"].required = False
|
||||||
|
form.fields["domain"].initial = self.object.name
|
||||||
return formset
|
return formset
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
"""Form submission posts to this view.
|
||||||
|
|
||||||
|
This post method harmonizes using DomainBaseView and FormMixin
|
||||||
|
"""
|
||||||
|
self._get_domain(request)
|
||||||
|
formset = self.get_form()
|
||||||
|
|
||||||
|
if "btn-cancel-click" in request.POST:
|
||||||
|
url = self.get_success_url()
|
||||||
|
return HttpResponseRedirect(url)
|
||||||
|
|
||||||
|
if formset.is_valid():
|
||||||
|
return self.form_valid(formset)
|
||||||
|
else:
|
||||||
|
return self.form_invalid(formset)
|
||||||
|
|
||||||
def form_valid(self, formset):
|
def form_valid(self, formset):
|
||||||
"""The formset is valid, perform something with it."""
|
"""The formset is valid, perform something with it."""
|
||||||
|
|
||||||
|
self.request.session["nameservers_form_domain"] = self.object
|
||||||
|
|
||||||
# Set the nameservers from the formset
|
# Set the nameservers from the formset
|
||||||
nameservers = []
|
nameservers = []
|
||||||
for form in formset:
|
for form in formset:
|
||||||
try:
|
try:
|
||||||
as_tuple = (form.cleaned_data["server"],)
|
ip_string = form.cleaned_data["ip"]
|
||||||
|
# ip_string will be None or a string of IP addresses
|
||||||
|
# comma-separated
|
||||||
|
ip_list = []
|
||||||
|
if ip_string:
|
||||||
|
# Split the string into a list using a comma as the delimiter
|
||||||
|
ip_list = ip_string.split(",")
|
||||||
|
|
||||||
|
as_tuple = (
|
||||||
|
form.cleaned_data["server"],
|
||||||
|
ip_list,
|
||||||
|
)
|
||||||
nameservers.append(as_tuple)
|
nameservers.append(as_tuple)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
# no server information in this field, skip it
|
# no server information in this field, skip it
|
||||||
pass
|
pass
|
||||||
self.object.nameservers = nameservers
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.object.nameservers = nameservers
|
||||||
|
except NameserverError as Err:
|
||||||
|
# NamserverErrors *should* be caught in form; if reached here,
|
||||||
|
# there was an uncaught error in submission (through EPP)
|
||||||
|
messages.error(
|
||||||
|
self.request, NameserverError(code=nsErrorCodes.UNABLE_TO_UPDATE_DOMAIN)
|
||||||
|
)
|
||||||
|
logger.error(f"Nameservers error: {Err}")
|
||||||
|
# TODO: registry is not throwing an error when no connection
|
||||||
|
except RegistryError as Err:
|
||||||
|
if Err.is_connection_error():
|
||||||
|
messages.error(
|
||||||
|
self.request,
|
||||||
|
GenericError(code=GenericErrorCodes.CANNOT_CONTACT_REGISTRY),
|
||||||
|
)
|
||||||
|
logger.error(f"Registry connection error: {Err}")
|
||||||
|
else:
|
||||||
|
messages.error(
|
||||||
|
self.request, GenericError(code=GenericErrorCodes.GENERIC_ERROR)
|
||||||
|
)
|
||||||
|
logger.error(f"Registry error: {Err}")
|
||||||
|
else:
|
||||||
messages.success(
|
messages.success(
|
||||||
self.request, "The name servers for this domain have been updated."
|
self.request,
|
||||||
|
"The name servers for this domain have been updated. "
|
||||||
|
"Keep in mind that DNS changes may take some time to "
|
||||||
|
"propagate across the internet. It can take anywhere "
|
||||||
|
"from a few minutes to 48 hours for your changes to take place.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# superclass has the redirect
|
# superclass has the redirect
|
||||||
|
@ -431,10 +495,15 @@ class DomainDsDataView(DomainFormBaseView):
|
||||||
self.object.dnssecdata = dnssecdata
|
self.object.dnssecdata = dnssecdata
|
||||||
except RegistryError as err:
|
except RegistryError as err:
|
||||||
if err.is_connection_error():
|
if err.is_connection_error():
|
||||||
messages.error(self.request, CANNOT_CONTACT_REGISTRY)
|
messages.error(
|
||||||
|
self.request,
|
||||||
|
GenericError(code=GenericErrorCodes.CANNOT_CONTACT_REGISTRY),
|
||||||
|
)
|
||||||
logger.error(f"Registry connection error: {err}")
|
logger.error(f"Registry connection error: {err}")
|
||||||
else:
|
else:
|
||||||
messages.error(self.request, GENERIC_ERROR)
|
messages.error(
|
||||||
|
self.request, GenericError(code=GenericErrorCodes.GENERIC_ERROR)
|
||||||
|
)
|
||||||
logger.error(f"Registry error: {err}")
|
logger.error(f"Registry error: {err}")
|
||||||
return self.form_invalid(formset)
|
return self.form_invalid(formset)
|
||||||
else:
|
else:
|
||||||
|
@ -510,7 +579,10 @@ class DomainSecurityEmailView(DomainFormBaseView):
|
||||||
# If no default is created for security_contact,
|
# If no default is created for security_contact,
|
||||||
# then we cannot connect to the registry.
|
# then we cannot connect to the registry.
|
||||||
if contact is None:
|
if contact is None:
|
||||||
messages.error(self.request, CANNOT_CONTACT_REGISTRY)
|
messages.error(
|
||||||
|
self.request,
|
||||||
|
GenericError(code=GenericErrorCodes.CANNOT_CONTACT_REGISTRY),
|
||||||
|
)
|
||||||
return redirect(self.get_success_url())
|
return redirect(self.get_success_url())
|
||||||
|
|
||||||
contact.email = new_email
|
contact.email = new_email
|
||||||
|
@ -519,13 +591,20 @@ class DomainSecurityEmailView(DomainFormBaseView):
|
||||||
contact.save()
|
contact.save()
|
||||||
except RegistryError as Err:
|
except RegistryError as Err:
|
||||||
if Err.is_connection_error():
|
if Err.is_connection_error():
|
||||||
messages.error(self.request, CANNOT_CONTACT_REGISTRY)
|
messages.error(
|
||||||
|
self.request,
|
||||||
|
GenericError(code=GenericErrorCodes.CANNOT_CONTACT_REGISTRY),
|
||||||
|
)
|
||||||
logger.error(f"Registry connection error: {Err}")
|
logger.error(f"Registry connection error: {Err}")
|
||||||
else:
|
else:
|
||||||
messages.error(self.request, GENERIC_ERROR)
|
messages.error(
|
||||||
|
self.request, GenericError(code=GenericErrorCodes.GENERIC_ERROR)
|
||||||
|
)
|
||||||
logger.error(f"Registry error: {Err}")
|
logger.error(f"Registry error: {Err}")
|
||||||
except ContactError as Err:
|
except ContactError as Err:
|
||||||
messages.error(self.request, GENERIC_ERROR)
|
messages.error(
|
||||||
|
self.request, GenericError(code=GenericErrorCodes.GENERIC_ERROR)
|
||||||
|
)
|
||||||
logger.error(f"Generic registry error: {Err}")
|
logger.error(f"Generic registry error: {Err}")
|
||||||
else:
|
else:
|
||||||
messages.success(
|
messages.success(
|
||||||
|
|
|
@ -1,53 +1,61 @@
|
||||||
-i https://pypi.python.org/simple
|
-i https://pypi.python.org/simple
|
||||||
|
annotated-types==0.6.0; python_version >= '3.8'
|
||||||
asgiref==3.7.2; python_version >= '3.7'
|
asgiref==3.7.2; python_version >= '3.7'
|
||||||
boto3==1.26.145
|
boto3==1.28.66; python_version >= '3.7'
|
||||||
botocore==1.29.145 ; python_version >= '3.7'
|
botocore==1.31.66; python_version >= '3.7'
|
||||||
cachetools==5.3.1
|
cachetools==5.3.1; python_version >= '3.7'
|
||||||
certifi==2023.7.22; python_version >= '3.6'
|
certifi==2023.7.22; python_version >= '3.6'
|
||||||
cfenv==0.5.3
|
cfenv==0.5.3
|
||||||
cffi==1.15.1
|
cffi==1.16.0; python_version >= '3.8'
|
||||||
charset-normalizer==3.1.0 ; python_full_version >= '3.7.0'
|
charset-normalizer==3.3.0; python_full_version >= '3.7.0'
|
||||||
cryptography==41.0.4; python_version >= '3.7'
|
cryptography==41.0.4; python_version >= '3.7'
|
||||||
defusedxml==0.7.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
|
defusedxml==0.7.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
|
||||||
dj-database-url==2.0.0
|
dj-database-url==2.1.0
|
||||||
dj-email-url==1.0.6
|
dj-email-url==1.0.6
|
||||||
django==4.2.3
|
django==4.2.6; python_version >= '3.8'
|
||||||
django-allow-cidr==0.6.0
|
django-allow-cidr==0.7.1
|
||||||
django-auditlog==2.3.0
|
django-auditlog==2.3.0; python_version >= '3.7'
|
||||||
django-cache-url==3.4.4
|
django-cache-url==3.4.4
|
||||||
django-csp==3.7
|
django-csp==3.7
|
||||||
django-fsm==2.8.1
|
django-fsm==2.8.1
|
||||||
django-login-required-middleware==0.9.0
|
django-login-required-middleware==0.9.0
|
||||||
django-phonenumber-field[phonenumberslite]==7.1.0
|
django-phonenumber-field[phonenumberslite]==7.2.0; python_version >= '3.8'
|
||||||
django-widget-tweaks==1.4.12
|
django-widget-tweaks==1.5.0; python_version >= '3.8'
|
||||||
environs[django]==9.5.0
|
environs[django]==9.5.0; python_version >= '3.6'
|
||||||
faker==18.10.0
|
faker==19.11.0; python_version >= '3.8'
|
||||||
git+https://github.com/cisagov/epplib.git@d56d183f1664f34c40ca9716a3a9a345f0ef561c#egg=fred-epplib
|
fred-epplib@ git+https://github.com/cisagov/epplib.git@d56d183f1664f34c40ca9716a3a9a345f0ef561c
|
||||||
furl==2.1.3
|
furl==2.1.3
|
||||||
future==0.18.3; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
|
future==0.18.3; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
|
||||||
gunicorn==20.1.0
|
gevent==23.9.1; python_version >= '3.8'
|
||||||
|
geventconnpool@ git+https://github.com/rasky/geventconnpool.git@1bbb93a714a331a069adf27265fe582d9ba7ecd4
|
||||||
|
greenlet==3.0.0; python_version >= '3.7'
|
||||||
|
gunicorn==21.2.0; python_version >= '3.5'
|
||||||
idna==3.4; python_version >= '3.5'
|
idna==3.4; python_version >= '3.5'
|
||||||
jmespath==1.0.1; python_version >= '3.7'
|
jmespath==1.0.1; python_version >= '3.7'
|
||||||
lxml==4.9.2 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
|
lxml==4.9.3; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
|
||||||
mako==1.2.4; python_version >= '3.7'
|
mako==1.2.4; python_version >= '3.7'
|
||||||
markupsafe==2.1.2 ; python_version >= '3.7'
|
markupsafe==2.1.3; python_version >= '3.7'
|
||||||
marshmallow==3.19.0 ; python_version >= '3.7'
|
marshmallow==3.20.1; python_version >= '3.8'
|
||||||
oic==1.6.0
|
oic==1.6.1; python_version ~= '3.7'
|
||||||
orderedmultidict==1.0.1
|
orderedmultidict==1.0.1
|
||||||
packaging==23.1 ; python_version >= '3.7'
|
packaging==23.2; python_version >= '3.7'
|
||||||
phonenumberslite==8.13.13
|
phonenumberslite==8.13.23
|
||||||
psycopg2-binary==2.9.6
|
psycopg2-binary==2.9.9; python_version >= '3.7'
|
||||||
pycparser==2.21
|
pycparser==2.21
|
||||||
pycryptodomex==3.18.0
|
pycryptodomex==3.19.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
|
||||||
pydantic==1.10.8 ; python_version >= '3.7'
|
pydantic==2.4.2; python_version >= '3.7'
|
||||||
|
pydantic-core==2.10.1; python_version >= '3.7'
|
||||||
|
pydantic-settings==2.0.3; python_version >= '3.7'
|
||||||
pyjwkest==1.4.2
|
pyjwkest==1.4.2
|
||||||
python-dateutil==2.8.2; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
|
python-dateutil==2.8.2; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
|
||||||
python-dotenv==1.0.0; python_version >= '3.8'
|
python-dotenv==1.0.0; python_version >= '3.8'
|
||||||
requests==2.31.0
|
requests==2.31.0; python_version >= '3.7'
|
||||||
s3transfer==0.6.1 ; python_version >= '3.7'
|
s3transfer==0.7.0; python_version >= '3.7'
|
||||||
setuptools==67.8.0 ; python_version >= '3.7'
|
setuptools==68.2.2; python_version >= '3.8'
|
||||||
six==1.16.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
|
six==1.16.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
|
||||||
sqlparse==0.4.4; python_version >= '3.5'
|
sqlparse==0.4.4; python_version >= '3.5'
|
||||||
typing-extensions==4.6.3
|
typing-extensions==4.8.0; python_version >= '3.8'
|
||||||
urllib3==1.26.17 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'
|
urllib3==2.0.7; python_version >= '3.7'
|
||||||
whitenoise==6.4.0
|
whitenoise==6.6.0; python_version >= '3.8'
|
||||||
|
zope.event==5.0; python_version >= '3.7'
|
||||||
|
zope.interface==6.1; python_version >= '3.7'
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue