Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c51206196 | ||
|
|
14805ed32b | ||
|
|
73d04b956d | ||
|
|
3c3a1834bc | ||
|
|
9f5e40ae48 | ||
|
|
4ad110ca53 | ||
|
|
e8762bf807 | ||
|
|
ddef4965d6 | ||
|
|
9f71ff7332 | ||
|
|
60bc60ccc4 | ||
|
|
ac34afc46c | ||
|
|
0ac23ff3a0 | ||
|
|
512dc6b247 | ||
|
|
edd57dd6f7 | ||
|
|
2276d770d1 | ||
|
|
0277063dcc | ||
|
|
74ceb0206a | ||
|
|
3affad4ed4 | ||
|
|
25c1ab4e12 | ||
|
|
627a3a5712 | ||
|
|
c579e49e78 | ||
|
|
c6c7cf70ec | ||
|
|
1b0008af4f | ||
|
|
cfb4633006 | ||
|
|
b4ab5596d6 | ||
|
|
11ea9a6f1a | ||
|
|
83965817d6 | ||
|
|
c054a00039 | ||
|
|
4eb018d8ca | ||
|
|
4ad41360de | ||
|
|
f80318707d | ||
|
|
db09fd70be | ||
|
|
dc1c223400 | ||
|
|
41d48f2807 | ||
|
|
e50cfd7cb6 | ||
|
|
55f6622997 | ||
|
|
fd8a5a0d9d | ||
|
|
b72fa9b664 | ||
|
|
a5d163b4af | ||
|
|
f5791e94d5 | ||
|
|
3eb17187b4 | ||
|
|
5747b044b6 | ||
|
|
d18e0fc262 | ||
|
|
2a89f4ae75 | ||
|
|
b78ae930e7 | ||
|
|
e89a6dfbd6 | ||
|
|
73544a4335 | ||
|
|
cb4886f032 | ||
|
|
e5808b4a57 | ||
|
|
547fe92b8b | ||
|
|
3f3426886e | ||
|
|
3eef3b4d7b | ||
|
|
a4036c285c | ||
|
|
1426ef2f70 | ||
|
|
ea1b5ee2b4 | ||
|
|
67ccf83b1c | ||
|
|
da6a5e09a5 | ||
|
|
3eb58f9b29 | ||
|
|
ad52457c48 | ||
|
|
9c3d7cce7e | ||
|
|
6418ed56e6 | ||
|
|
fd16f7e701 | ||
|
|
f926795d1b | ||
|
|
eedc01303b | ||
|
|
646059bb07 | ||
|
|
f41b4cea56 | ||
|
|
3dec22b9f3 | ||
|
|
b23c773bee | ||
|
|
53b12c9e15 | ||
|
|
d56a8f9140 | ||
|
|
c32161b8a2 | ||
|
|
165a0faa67 | ||
|
|
5a20737ba9 | ||
|
|
f713719543 | ||
|
|
5f48472ba4 | ||
|
|
79ae6c2068 | ||
|
|
756c491e28 | ||
|
|
4a1930a896 | ||
|
|
5040ce70a0 | ||
|
|
4d3b01127b | ||
|
|
997f36264a | ||
|
|
19a946c880 | ||
|
|
9afdfe869b | ||
|
|
1fae3bfe54 | ||
|
|
562f54d481 | ||
|
|
ca51a6054d | ||
|
|
45f9631a98 | ||
|
|
0d041a0830 | ||
|
|
6bbb2e9905 | ||
|
|
8fba131230 | ||
|
|
a9dbbe8c88 | ||
|
|
9a2b0a2c2b | ||
|
|
55d891f38c | ||
|
|
1375bbb7e3 | ||
|
|
723566db70 | ||
|
|
e8450c90da | ||
|
|
ae6bb3c1b6 | ||
|
|
0028ba8d80 | ||
|
|
78ed040495 |
No files matched your search
+3
-1
@@ -1,4 +1,6 @@
|
||||
src/netbox_plugin_bind_provisioner.egg-info
|
||||
dist/
|
||||
build/
|
||||
__pycache__
|
||||
venv/
|
||||
.venv/
|
||||
netbox_plugin_dns_bridge.egg-info/
|
||||
@@ -0,0 +1,46 @@
|
||||
## Unreleased
|
||||
- Move `notify_handler` from `signals/` to `jobs/` and rename to `notify`.
|
||||
- Rename `SendClientDNSNotify` to `SendClientNotify`. It now sends a single NOTIFY
|
||||
for the zone only; catalog zone entries (`catz`, `{view}.catz`) have been removed.
|
||||
- Catalog zone NOTIFY is now scheduled by `increment_soa_serial` via
|
||||
`schedule_catalog_zone_notify`, which enqueues `SendClientNotify` for `catz` and
|
||||
`{view}.catz` — no separate job class needed.
|
||||
- Extract a shared `_send_notify` helper used by both `SendClientNotify` and
|
||||
`SendNSNotify` for message building and the send loop.
|
||||
- Move all NOTIFY scheduling gates (`notify_clients`, `notify_ns_all_zones`, custom
|
||||
field) into the scheduling functions. The signal handler calls the scheduling
|
||||
functions unconditionally; each function decides whether to enqueue based on its
|
||||
own settings gate.
|
||||
- Replace the global `IntegerKeyValueSetting` model (single `catalog-zone-soa-serial`
|
||||
value shared by all catalog zones) with a new `CatalogZone` model that has a 1:1
|
||||
foreign key to `netbox_dns.models.View` and its own `soa_serial` field. Each view's
|
||||
catalog zone now tracks and increments its SOA serial independently. Existing serials
|
||||
are preserved during migration by copying the old global value into every view's new
|
||||
`CatalogZone` row.
|
||||
- Change the `CatalogZoneMemberIdentifier.name` uniqueness from globally unique to
|
||||
unique per catalog zone (`UniqueConstraint(name, catalog_zone)`). A `catalog_zone`
|
||||
foreign key has been added to the identifier model to enforce this.
|
||||
- Remove the `dns-settings` management command, which was a generic get/set/list
|
||||
interface over `IntegerKeyValueSetting` (now removed).
|
||||
- Defer the catalog zone SOA serial increment on zone deletion to `transaction.on_commit`, matching
|
||||
the create/modify path. Previously the increment ran immediately at `post_delete` time, so a
|
||||
rollback of the delete transaction would have left the catalog serial bumped anyway.
|
||||
- Add the option to send a NOTIFY directly to a zone's own nameservers when its SOA serial number
|
||||
changes. Enable it per zone via a boolean custom field named by `notify_ns_custom_field_name`,
|
||||
globally for all zones via `notify_ns_all_zones` (default `False`), or both. Nameserver addresses
|
||||
are resolved from NetBox DNS A/AAAA records within the zone's view and the NOTIFY is signed with
|
||||
the per-view TSIG key. A companion `notify_ns_port` setting (default 53) controls the destination
|
||||
port.
|
||||
|
||||
## 1.0.7 - 2026-03-02
|
||||
README Change - Moving private keys to global scope since Bind 9.20 view scoped keys have become unreliable and sometimes wouldnt match.
|
||||
|
||||
## 1.0.8 - 2026-03-12
|
||||
- Change License to MIT to match the netbox-plugin-dns License. This project rests on the netbox-plugin-dns so a matching
|
||||
license makes more sense.
|
||||
- Renaming Project from Netbox Plugin Bind Provisioner to Netbox DNS Bridge as new code will be contributed that allows
|
||||
data to flow in both directions (Dynamic Updates), not just out of Netbox DNS.
|
||||
|
||||
## 1.5.0 - 2026-04-08
|
||||
- Change to versioning scheme - Now matches the major and minor version number to the one of netbox-plugin-dns. Only the minor sub version
|
||||
will be used to track incremental changes to this plugin.
|
||||
+14
-335
@@ -1,339 +1,18 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
MIT License
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
Copyright (c) 2025-2026 Sven Luethi
|
||||
|
||||
Preamble
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the “Software”), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
||||
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
|
||||
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
recursive-include netbox_bind_provisioner *.py
|
||||
recursive-include netbox_dns_bridge *.py
|
||||
recursive-include netbox_dns_bridge/templates *.html
|
||||
@@ -1,57 +1,197 @@
|
||||
# Netbox Bind Provisioner
|
||||
A NetBox plugin that implements a lightweight DNS server to automate the
|
||||
provisioning and configuration of a BIND9 server based on DNS records
|
||||
maintained in NetBox. (netbox-plugin-dns).
|
||||
# NetBox DNS Bridge
|
||||
|
||||
## Plugin configuration
|
||||
The plugin has been reworked: instead of exporting zone files, it now provides
|
||||
a minimal DNS server that is fed directly from NetBox’s DNS data. This server
|
||||
also exposes specialized catalog zones that BIND uses to automatically discover
|
||||
newly created zones and remove deleted ones. The plugin supports BIND views and
|
||||
basic DNS security via TSIG.
|
||||
The NetBox DNS Bridge plugin extends [NetBox DNS](https://github.com/sys4/netbox-plugin-dns) by
|
||||
embedding a lightweight DNS server directly within NetBox. It acts as a bridge between NetBox DNS
|
||||
and your existing DNS infrastructure, leveraging native DNS mechanisms for seamless integration.
|
||||
These include zone transfers (RFC 5936), catalog zones (RFC 9432), and notifying clients about zone
|
||||
changes (RFC 1996).
|
||||
|
||||
The plugin exposes one catalog zone per view. Each catalog zone is available
|
||||
under the special zone name **"catz"** and can be queried through the built-in
|
||||
DNS server like any other zone.
|
||||
<a href="https://pypi.org/project/netbox-plugin-dns-bridge/"><img src="https://img.shields.io/pypi/v/netbox-plugin-dns-bridge" alt="PyPi"></a>
|
||||
<a href="https://github.com/suraxius/netbox-plugin-dns-bridge/stargazers"><img src="https://img.shields.io/github/stars/suraxius/netbox-plugin-dns-bridge?style=flat" alt="Stars Badge"></a>
|
||||
<a href="https://github.com/suraxius/netbox-plugin-dns-bridge/network/members"><img src="https://img.shields.io/github/forks/suraxius/netbox-plugin-dns-bridge?style=flat" alt="Forks Badge"></a>
|
||||
<a href="https://github.com/suraxius/netbox-plugin-dns-bridge/issues"><img src="https://img.shields.io/github/issues/suraxius/netbox-plugin-dns-bridge" alt="Issues Badge"></a>
|
||||
<a href="https://github.com/suraxius/netbox-plugin-dns-bridge/pulls"><img src="https://img.shields.io/github/issues-pr/suraxius/netbox-plugin-dns-bridge" alt="Pull Requests Badge"></a>
|
||||
<a href="https://github.com/suraxius/netbox-plugin-dns-bridge/graphs/contributors"><img src="https://img.shields.io/github/contributors/suraxius/netbox-plugin-dns-bridge?color=2b9348" alt="GitHub contributors"></a>
|
||||
<a href="https://github.com/suraxius/netbox-plugin-dns-bridge/blob/master/LICENSE"><img src="https://img.shields.io/github/license/suraxius/netbox-plugin-dns-bridge?color=2b9348" alt="License Badge"></a>
|
||||
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code Style Black"></a>
|
||||
<a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=total&left_color=BLACK&right_color=BLUE&left_text=Downloads" alt="Downloads"></a>
|
||||
<a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=monthly&left_color=BLACK&right_color=BLUE&left_text=Downloads%2fMonth" alt="Downloads/Month"></a>
|
||||
<a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=weekly&left_color=BLACK&right_color=BLUE&left_text=Downloads%2fWeek" alt="Downloads/Week"></a>
|
||||
|
||||
For proper operation, each view requires an installed TSIG key, and the
|
||||
`bind-transfer-endpoint` must be running as a separate background service using
|
||||
the `manage.py` command. Note that DNSSEC support will be added once BIND9
|
||||
provides a mechanism to configure it through the Catalog Zones system.
|
||||
|
||||
To start the service:
|
||||
# Plugin configuration
|
||||
While providing Zone transfers via AXFR, the Server also exposes specialized catalog zones that BIND
|
||||
and other RFC9432 compliant DNS Servers use to automatically discover newly created zones and remove
|
||||
deleted ones. The plugin supports views and basic DNS security via TSIG.
|
||||
|
||||
The plugin exposes one catalog zone per view. Each catalog zone is made available under the special
|
||||
zone name **"catz"** and addtionally under **"[viewname].catz"** and may be queried through the
|
||||
built-in DNS server just like any other dns zone.
|
||||
|
||||
For proper operation, each view requires an installed TSIG key, and the `dns-transfer-endpoint` must
|
||||
be running as a separate background service using the `manage.py` command. Note that DNSSEC support
|
||||
will be added once BIND9 provides a mechanism to configure it through the Catalog Zones system.
|
||||
|
||||
To start the transfer endpoint service in the foreground:
|
||||
```
|
||||
manage.py bind-transfer-endpoint --port 5354
|
||||
manage.py dns-transfer-endpoint --port 5354
|
||||
```
|
||||
This process needs to be scheduled as a background service for the built-in DNS Server to work
|
||||
correctly. For Linux users with Systemd (Ubuntu, etc), Matt Kollross provides a startup unit and
|
||||
instructions [here](docs/install-systemd-service.md).
|
||||
|
||||
When configuring the plugin, you need to provide a path on the filesystem for
|
||||
this file where the plugin can create and manage it. Please do not update it by
|
||||
hand or remove it unless you know what you are doing.
|
||||
|
||||
### Service parameters
|
||||
## Service parameters
|
||||
Parameter | Description
|
||||
--------- | -------------------------------------------------------------------
|
||||
--port | Port to listen on for requests (defaults to 5354)
|
||||
--address | IP of interface to bind to (defaults to 0.0.0.0)
|
||||
|
||||
### Plugin settings
|
||||
Setting | Description
|
||||
--------------------| ---------------------------------------------------------
|
||||
catalog_serial_file | !!!NO LONGER USED!!! Replaced by DB entry.
|
||||
tsig_keys | Maps a TSIG Key to be used for each view.
|
||||
|
||||
## Plugin settings
|
||||
Plugin settings should be configured under `PLUGINS_CONFIG` in `netbox_dns_bridge`:
|
||||
```
|
||||
PLUGINS_CONFIG = {
|
||||
'netbox_dns_bridge': {
|
||||
...
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### TSIG Authentication
|
||||
Following sets the TSIG key that allows clients to query the transfer endpoint and also the key to
|
||||
be used to sign NOTIFY messages to clients on zone changes. Each view should have its own unique
|
||||
key to allow the plugin to identify the view the client is trying to access. Re-using the key for
|
||||
multiple views yields unpredicted behavior.
|
||||
```
|
||||
'tsig_keys': {
|
||||
'the-view-name-here': {
|
||||
'keyname': 'the-tsig-key-name-here',
|
||||
'algorithm': 'hmac-sha256',
|
||||
'secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### NOTIFY
|
||||
The plugin has 2 different NOTIFY mechanisms that may be turned on individually or together.
|
||||
|
||||
1. [Client Notify](#client-notify)
|
||||
Notify clients that are regularly contacting the transfer endpoint for zone updates.
|
||||
|
||||
2. [NS Notify](#ns-notify)
|
||||
Notify the zone's NS Servers when a zone changes.
|
||||
|
||||
- [Per Zone](#ns-notify-per-zone)
|
||||
Notify NS servers for zones that have a specific custom field set to true.
|
||||
|
||||
- [For all Zones](#ns-notify-for-all-zones)
|
||||
Notify NS servers for all zones.
|
||||
Note: This makes the *Per Zone* mechanism redundant. There is no point in enabling both.
|
||||
|
||||
#### Global NOTIFY Settings
|
||||
```
|
||||
'notify_over_tcp': True
|
||||
```
|
||||
Switch to using TCP instead of UDP. Defaults to False
|
||||
|
||||
#### Client NOTIFY
|
||||
Clients may be notified of zone changes using the NOTIFY mechanism defined in RFC 1996.
|
||||
When enabled, the zone transfer endpoint keeps track of any client that successfully queried the
|
||||
endpoint. Once a zone has changed, NetBox informs each client about the zone changed so that the
|
||||
client can request a new zone transfer.
|
||||
|
||||
Note that this feature uses NetBox's background job system to schedule the messages asynchronously.
|
||||
In order to work, you need at least one `rq-worker` service running in the background to handle
|
||||
the queued jobs.
|
||||
|
||||
```
|
||||
'notify_clients': True
|
||||
```
|
||||
This enables the NOTIFY system. Defaults to False
|
||||
|
||||
```
|
||||
'notify_client_alive_threshold_hours': 24
|
||||
```
|
||||
This sets how long a client is considred "alive" after it last queried the transfer endpoint.
|
||||
Once the client has failed to check in for this amout of time, it is automatically removed from the
|
||||
list of clients to be notified on zone changes. Default is 24 hours.
|
||||
|
||||
```
|
||||
'notify_client_port': 53
|
||||
```
|
||||
Destination port used to send NOTIFY messages to clients. Defaults to 53.
|
||||
|
||||
|
||||
|
||||
#### NS NOTIFY
|
||||
In addition to notifying clients that queried the transfer endpoint, the plugin can send a NOTIFY
|
||||
directly to a zone's own nameservers whenever that zone's SOA serial number changes. This is useful
|
||||
when you want nameservers to pull updates immediately, independent of the `notify_clients` mechanism.
|
||||
Only a change of the SOA serial triggers this — other zone edits that leave the serial untouched do
|
||||
not.
|
||||
|
||||
This can be enabled per zone, globally, or both. If neither of the settings below is configured, the
|
||||
feature is disabled entirely.
|
||||
|
||||
|
||||
##### NS NOTIFY per Zone
|
||||
This uses a True/False custom field attached to each Zone to enable/disable NOTIFY for each
|
||||
individually.
|
||||
|
||||
Create a boolean custom field (e.g. `dns_bridge_notify_ns`) that applies
|
||||
to `netbox_dns > zone`, then point the plugin at it:
|
||||
```
|
||||
'notify_ns_custom_field_name': 'dns_bridge_notify_ns'
|
||||
```
|
||||
A NOTIFY is then sent for any zone whose custom field is set to `True`. This lets you toggle the
|
||||
behavior per zone straight from the NetBox UI, without changing the plugin config.
|
||||
|
||||
|
||||
##### NS NOTIFY for all Zones
|
||||
```
|
||||
'notify_ns_all_zones': True
|
||||
```
|
||||
When enabled, a NOTIFY is sent for every zone on serial change, regardless of the custom field.
|
||||
Defaults to `False`. The two options coexist: a NOTIFY is sent if the global switch is on **or** the
|
||||
zone's custom field is set.
|
||||
|
||||
|
||||
##### NS NOTIFY Settings
|
||||
|
||||
The nameserver addresses are resolved from NetBox DNS itself by looking up active A/AAAA records
|
||||
(within the zone's view) matching each nameserver's hostname. The NOTIFY messages are signed with the
|
||||
same per-view TSIG key configured under `tsig_keys`, so the receiving nameservers must accept NOTIFY
|
||||
signed with that key (e.g. BIND's `allow-notify { key "..."; };`).
|
||||
|
||||
```
|
||||
'notify_ns_port': 53
|
||||
```
|
||||
Destination port used for these NOTIFY messages. Defaults to 53.
|
||||
|
||||
As with the client NOTIFY feature, this uses NetBox's background job system, so at least one
|
||||
`rq-worker` service must be running.
|
||||
|
||||
|
||||
## Plugin compatibility
|
||||
This plugin extends the netbox-plugin-dns plugin. As such the versioning was changed to match the
|
||||
one of netbox-plugin-dns more closely. To guarantee compatability, ensure that the major and minor
|
||||
version match between both plugins. For example, when using netbox-plugin-dns `v1.5.5` install
|
||||
netbox-plugin-dns-bridge `v1.5.x`.
|
||||
|
||||
|
||||
## Installation guide
|
||||
This setup provisions a BIND9 server directly with DNS data from NetBox.
|
||||
BIND9 can optionally run on a separate server. If so, any reference to
|
||||
127.0.0.1 in step 6 must be replaced with the IP address of the NetBox host.
|
||||
TCP and UDP traffic from the BIND9 server to the NetBox host must be allowed on
|
||||
This setup provisions a BIND9 server directly with DNS data from NetBox. BIND9 can optionally run on
|
||||
a separate server. If so, any reference to 127.0.0.1 in step 6 must be replaced with the IP address
|
||||
of the NetBox host. TCP and UDP traffic from the BIND9 server to the NetBox host must be allowed on
|
||||
port 5354 (or the port you have configured).
|
||||
|
||||
This guide assumes:
|
||||
- Netbox has been installed under /opt/netbox
|
||||
- Bind9 is installed on the same host as Netbox
|
||||
- The Netbox DNS Plugin netbox-plugin-dns is installed
|
||||
- The following dns views exist in Netbox DNS:
|
||||
- NetBox has been installed under /opt/netbox
|
||||
- Bind9 is installed on the same host as NetBox
|
||||
- The NetBox DNS Plugin netbox-plugin-dns is installed
|
||||
- The following dns views exist in NetBox DNS:
|
||||
- `public` (the default)
|
||||
- `private`
|
||||
|
||||
@@ -62,7 +202,7 @@ This guide assumes:
|
||||
2. Adding required package
|
||||
```
|
||||
cd netbox
|
||||
echo netbox-plugin-bind-provisioner >> local_requirements.txt
|
||||
echo netbox-plugin-dns-bridge >> local_requirements.txt
|
||||
. venv/bin/activate
|
||||
pip install -r local_requirements.txt
|
||||
```
|
||||
@@ -74,10 +214,10 @@ This guide assumes:
|
||||
```
|
||||
to
|
||||
```
|
||||
PLUGINS = ['netbox_dns', 'netbox_plugin_bind_provisioner']
|
||||
PLUGINS = ['netbox_dns', 'netbox_dns_bridge']
|
||||
```
|
||||
|
||||
Configure the Bind Exporter Plugin using the PLUGINS_CONFIG dictionary.
|
||||
Configure the DNS Bridge Plugin using the PLUGINS_CONFIG dictionary.
|
||||
Change
|
||||
```
|
||||
PLUGINS_CONFIG = {}
|
||||
@@ -85,7 +225,7 @@ This guide assumes:
|
||||
to
|
||||
```
|
||||
PLUGINS_CONFIG = {
|
||||
"netbox_plugin_bind_provisioner": {
|
||||
"netbox_dns_bridge": {
|
||||
"tsig_keys": {
|
||||
"public": {
|
||||
"keyname": "public_view_key",
|
||||
@@ -104,33 +244,31 @@ This guide assumes:
|
||||
Note that the tsig-key attributes keyname, algorithm and secret form a
|
||||
dictionary in following python structure path:
|
||||
```
|
||||
PLUGINS_CONFIG.netbox_plugin_bind_provisioner.tsig_keys.<dns_view_name>
|
||||
PLUGINS_CONFIG.netbox_dns_bridge.tsig_keys.<dns_view_name>
|
||||
```
|
||||
This allows the plugin to map requests to the right dns view using the tsig
|
||||
signature from each request.
|
||||
|
||||
4. Run migrations
|
||||
```
|
||||
python3 netbox/manage.py migrate
|
||||
manage.py migrate
|
||||
```
|
||||
|
||||
5. Start listener
|
||||
This step runs the DNS endpoint used by bind to configure itself. You may want
|
||||
to write a service wrapper that runs this in the background.
|
||||
A guide for setting up a systemd service on Ubuntu is provided by Matt
|
||||
Kollross [here](docs/install-systemd-service.md). Dont forget to activate
|
||||
the venv if you do decide to run this service in the background.
|
||||
|
||||
Note that `--port 5354` is optional. The listener will bind this port
|
||||
by default.
|
||||
This step runs the DNS endpoint used by bind to configure itself. You may want to write a
|
||||
service wrapper that runs this in the background. A guide for setting up a systemd service on
|
||||
Ubuntu is provided by Matt Kollross [here](docs/install-systemd-service.md). Dont forget to
|
||||
activate the venv if you do decide to run this service in the background.
|
||||
|
||||
Note that `--port 5354` is optional. The listener will bind this port by default.
|
||||
```
|
||||
python3 netbox/manage.py bind-transfer-endpoint --port 5354
|
||||
manage.py dns-transfer-endpoint --port 5354
|
||||
```
|
||||
|
||||
6. Configuring a Bind9 to interact with Netbox via the bind-transfer-endpoint
|
||||
endpoint. Note that its not possible to give all the correct details of the
|
||||
`options` block as it is heavily dependent on the Operating System used.
|
||||
Please dont forget to adjust as required.
|
||||
6. Configuring a Bind9 to interact with NetBox via the dns-transfer-endpoint endpoint. Note that its
|
||||
not possible to give all the correct details of the `options` block as it is heavily dependent
|
||||
on the Operating System used. Please dont forget to adjust as required.
|
||||
|
||||
```
|
||||
########## OPTIONS ##########
|
||||
@@ -158,15 +296,23 @@ This guide assumes:
|
||||
192.168.0.0/16;
|
||||
};
|
||||
|
||||
########## ZONES ##########
|
||||
|
||||
view "public" {
|
||||
######## TSIG Keys ########
|
||||
key "public_view_key" {
|
||||
algorithm hmac-sha256;
|
||||
secret "base64-encoded-secret";
|
||||
};
|
||||
|
||||
key "private_view_key" {
|
||||
algorithm hmac-sha256;
|
||||
secret "base64-encoded-secret";
|
||||
};
|
||||
###########################
|
||||
|
||||
|
||||
########## ZONES ##########
|
||||
view "public" {
|
||||
match-clients { public; };
|
||||
allow-notify { key "public_view_key"; };
|
||||
|
||||
catalog-zones {
|
||||
zone "catz"
|
||||
@@ -184,12 +330,8 @@ This guide assumes:
|
||||
};
|
||||
|
||||
view "private" {
|
||||
key "private_view_key" {
|
||||
algorithm hmac-sha256;
|
||||
secret "base64-encoded-secret";
|
||||
};
|
||||
|
||||
match-clients { private; };
|
||||
allow-notify { key "private_view_key"; };
|
||||
|
||||
catalog-zones {
|
||||
zone "catz"
|
||||
@@ -209,3 +351,4 @@ This guide assumes:
|
||||
|
||||
7. Restart bind - Done
|
||||
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
"""Root conftest: ensure Django is configured before any test conftest imports
|
||||
models. pytest-django normally handles this, but our tests-dir conftest imports
|
||||
plugin modules (which import netbox_dns models) at collection time, so we force
|
||||
``django.setup()`` here unconditionally and early.
|
||||
"""
|
||||
import os
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "netbox.settings")
|
||||
|
||||
import django # noqa: E402
|
||||
|
||||
if not django.apps.apps.ready:
|
||||
django.setup()
|
||||
@@ -0,0 +1,76 @@
|
||||
<mxfile host="Electron" agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/29.0.3 Chrome/140.0.7339.249 Electron/38.7.0 Safari/537.36" version="29.0.3">
|
||||
<diagram name="Page-1" id="inkmD5hxPkRoHiEHOzAS">
|
||||
<mxGraphModel dx="831" dy="2028" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-24" value="" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
|
||||
<mxGeometry x="560" y="457.5" width="80" height="80" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-13" value="" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#f5f5f5;fontColor=#333333;strokeColor=#666666;" parent="1" vertex="1">
|
||||
<mxGeometry x="70" y="210" width="600" height="220" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-12" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1">
|
||||
<mxGeometry x="430" y="260" width="230" height="150" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-3" value="<font style="font-size: 18px;">Netbox</font>" style="text;html=1;whiteSpace=wrap;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;rounded=0;" parent="1" vertex="1">
|
||||
<mxGeometry x="80" y="220" width="60" height="30" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-4" value="DNS" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#dae8fc;strokeColor=#6c8ebf;rounded=1;" parent="1" vertex="1">
|
||||
<mxGeometry x="300" y="260" width="100" height="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-6" value="IPAM" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#f8cecc;strokeColor=#b85450;gradientColor=none;rounded=1;" parent="1" vertex="1">
|
||||
<mxGeometry x="80" y="260" width="100" height="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-7" value="DHCP<br>(WIP)" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#fff2cc;strokeColor=#d6b656;rounded=1;" parent="1" vertex="1">
|
||||
<mxGeometry x="190" y="260" width="100" height="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="MSiTSJWh-g0ETCA7Z0x5-4" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="WlUYMBEI5UY_wtPVGHlU-9" target="WlUYMBEI5UY_wtPVGHlU-4">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-9" value="Transfer<br>Endpoint" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#d5e8d4;strokeColor=#82b366;rounded=1;" parent="1" vertex="1">
|
||||
<mxGeometry x="440" y="300" width="100" height="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-10" value="Dynamic Update<br>Endpoint" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#d5e8d4;strokeColor=#82b366;rounded=1;" parent="1" vertex="1">
|
||||
<mxGeometry x="550" y="300" width="100" height="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-11" value="DNS Bridge" style="text;html=1;whiteSpace=wrap;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;rounded=0;" parent="1" vertex="1">
|
||||
<mxGeometry x="440" y="270" width="90" height="30" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-18" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;endArrow=none;endFill=0;startArrow=classic;startFill=1;" parent="1" source="WlUYMBEI5UY_wtPVGHlU-16" target="WlUYMBEI5UY_wtPVGHlU-9" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="490" y="450" />
|
||||
<mxPoint x="490" y="450" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-27" value="AXFR" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];" parent="WlUYMBEI5UY_wtPVGHlU-18" connectable="0" vertex="1">
|
||||
<mxGeometry x="-0.2264" y="2" relative="1" as="geometry">
|
||||
<mxPoint x="2" y="5" as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-16" value="" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
|
||||
<mxGeometry x="440" y="457.5" width="80" height="80" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-20" value="" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
|
||||
<mxGeometry x="450" y="467.5" width="80" height="80" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-19" value="DNS Server<br>(RFC9432)" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
|
||||
<mxGeometry x="460" y="477.5" width="80" height="80" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-23" value="" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
|
||||
<mxGeometry x="570" y="467.5" width="80" height="80" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="WlUYMBEI5UY_wtPVGHlU-25" value="Client<br>(RFC2136)" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
|
||||
<mxGeometry x="580" y="477.5" width="80" height="80" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="MSiTSJWh-g0ETCA7Z0x5-3" value="Update" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="WlUYMBEI5UY_wtPVGHlU-24" target="WlUYMBEI5UY_wtPVGHlU-10">
|
||||
<mxGeometry x="-0.3913" relative="1" as="geometry">
|
||||
<mxPoint y="1" as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Do not edit this file with editors other than draw.io -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="background: #ffffff; background-color: light-dark(#ffffff, var(--ge-dark-color, #121212)); color-scheme: light dark;" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="601px" height="349px" viewBox="0 0 601 349" content="<mxfile host="Electron" agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/29.0.3 Chrome/140.0.7339.249 Electron/38.7.0 Safari/537.36" version="29.0.3" scale="1" border="0"> <diagram name="Page-1" id="inkmD5hxPkRoHiEHOzAS"> <mxGraphModel dx="706" dy="1724" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0"> <root> <mxCell id="0" /> <mxCell id="1" parent="0" /> <mxCell id="WlUYMBEI5UY_wtPVGHlU-24" value="" style="whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1"> <mxGeometry x="560" y="457.5" width="80" height="80" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-13" value="" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#f5f5f5;fontColor=#333333;strokeColor=#666666;" parent="1" vertex="1"> <mxGeometry x="70" y="210" width="600" height="220" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-12" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"> <mxGeometry x="430" y="260" width="230" height="150" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-3" value="&lt;font style=&quot;font-size: 18px;&quot;&gt;Netbox&lt;/font&gt;" style="text;html=1;whiteSpace=wrap;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;rounded=0;" parent="1" vertex="1"> <mxGeometry x="80" y="220" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-4" value="DNS" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#dae8fc;strokeColor=#6c8ebf;rounded=1;" parent="1" vertex="1"> <mxGeometry x="300" y="260" width="100" height="100" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-6" value="IPAM" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#f8cecc;strokeColor=#b85450;gradientColor=none;rounded=1;" parent="1" vertex="1"> <mxGeometry x="80" y="260" width="100" height="100" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-7" value="DHCP&lt;br&gt;(WIP)" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#fff2cc;strokeColor=#d6b656;rounded=1;" parent="1" vertex="1"> <mxGeometry x="190" y="260" width="100" height="100" as="geometry" /> </mxCell> <mxCell id="MSiTSJWh-g0ETCA7Z0x5-4" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" parent="1" source="WlUYMBEI5UY_wtPVGHlU-9" target="WlUYMBEI5UY_wtPVGHlU-4" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-9" value="Transfer&lt;br&gt;Endpoint" style="whiteSpace=wrap;html=1;aspect=fixed;fillColor=#d5e8d4;strokeColor=#82b366;rounded=1;" parent="1" vertex="1"> <mxGeometry x="440" y="300" width="100" height="100" as="geometry" /> </mxCell> <mxCell id="WlUYMBEI5UY_wtPVGHlU-10" value="Dynamic Update&lt;br&gt;Endpoint" style="whiteSpace=wrap;html=1;aspect=fixedLine truncated
|
||||
|
After Width: | Height: | Size: 112 KiB |
@@ -1,9 +1,9 @@
|
||||
1. Create System Unit file
|
||||
```
|
||||
cat <<EOF > /etc/systemd/system/netbox-bind-endpoint.service
|
||||
cat <<EOF > /etc/systemd/system/netbox-dns-endpoint.service
|
||||
[Unit]
|
||||
Description=Netbox BIND Catalog Endpoing
|
||||
Documentation=https://github.com/Suraxius/netbox-plugin-bind-provisioner
|
||||
Description=Netbox DNS transfer endpoint
|
||||
Documentation=https://github.com/Suraxius/netbox-plugin-dns-bridge
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
PIDFile=/var/tmp/netbox.pid
|
||||
WorkingDirectory=/opt/netbox
|
||||
|
||||
ExecStart=/opt/netbox/venv/bin/python3 /opt/netbox/netbox/manage.py bind-transfer-endpoint --port 5354
|
||||
ExecStart=/opt/netbox/venv/bin/python3 /opt/netbox/netbox/manage.py dns-transfer-endpoint --address 0.0.0.0 --port 5354
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=30
|
||||
@@ -28,7 +28,7 @@
|
||||
|
||||
2. Enable and start the service
|
||||
```
|
||||
systemctl enable netbox-bind-endpoint
|
||||
systemctl start netbox-bind-endpoint
|
||||
systemctl status netbox-bind-endpoint
|
||||
systemctl enable netbox-dns-endpoint
|
||||
systemctl start netbox-dns-endpoint
|
||||
systemctl status netbox-dns-endpoint
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
from netbox.plugins import PluginConfig
|
||||
from django.conf import settings
|
||||
|
||||
__version__ = "1.5.8"
|
||||
|
||||
class DNSBridgeConfig(PluginConfig):
|
||||
name = "netbox_dns_bridge"
|
||||
verbose_name = "Netbox DNS Bridge"
|
||||
description = ""
|
||||
version = __version__
|
||||
author = "Sven Luethi"
|
||||
author_email = "dev@sven.luethi.co"
|
||||
base_url = "dns-bridge"
|
||||
|
||||
def ready(self):
|
||||
super().ready()
|
||||
self.settings = settings.PLUGINS_CONFIG.get(self.name, None)
|
||||
if not self.settings:
|
||||
raise RuntimeError(
|
||||
f"{self.name}: Plugin {self.verbose_name} failed to"
|
||||
" initialize due to missing settings. Terminating Netbox."
|
||||
)
|
||||
|
||||
from . import signals
|
||||
|
||||
|
||||
config = DNSBridgeConfig
|
||||
@@ -0,0 +1,59 @@
|
||||
import django_filters
|
||||
from django.db.models import Q
|
||||
|
||||
import netbox_dns.models
|
||||
from netbox.filtersets import NetBoxModelFilterSet
|
||||
|
||||
from .models import CatalogZone, CatalogZoneMember, SeenTransferClient
|
||||
|
||||
|
||||
class CatalogZoneFilterSet(NetBoxModelFilterSet):
|
||||
view = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name="view",
|
||||
queryset=netbox_dns.models.View.objects.all(),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = CatalogZone
|
||||
fields = ("id", "view")
|
||||
|
||||
def search(self, queryset, name, value):
|
||||
if not value.strip():
|
||||
return queryset
|
||||
return queryset.filter(Q(view__name__icontains=value))
|
||||
|
||||
|
||||
class CatalogZoneMemberFilterSet(NetBoxModelFilterSet):
|
||||
catalog_zone = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name="catalog_zone",
|
||||
queryset=CatalogZone.objects.all(),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = CatalogZoneMember
|
||||
fields = ("id", "catalog_zone", "zone")
|
||||
|
||||
def search(self, queryset, name, value):
|
||||
if not value.strip():
|
||||
return queryset
|
||||
return queryset.filter(
|
||||
Q(name__icontains=value) | Q(zone__name__icontains=value)
|
||||
)
|
||||
|
||||
|
||||
class SeenTransferClientFilterSet(NetBoxModelFilterSet):
|
||||
view = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name="view",
|
||||
queryset=netbox_dns.models.View.objects.all(),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SeenTransferClient
|
||||
fields = ("id", "view", "source_ip")
|
||||
|
||||
def search(self, queryset, name, value):
|
||||
if not value.strip():
|
||||
return queryset
|
||||
return queryset.filter(
|
||||
Q(source_ip__icontains=value) | Q(view__name__icontains=value)
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
from django import forms
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
import netbox_dns.models
|
||||
from netbox.forms import NetBoxModelFilterSetForm, NetBoxModelForm
|
||||
from utilities.forms.fields import DynamicModelMultipleChoiceField
|
||||
|
||||
from .models import CatalogZone, CatalogZoneMember, SeenTransferClient
|
||||
|
||||
|
||||
class CatalogZoneForm(NetBoxModelForm):
|
||||
soa_serial = forms.IntegerField(label=_("SOA Serial"))
|
||||
soa_refresh = forms.IntegerField(label=_("Refresh"))
|
||||
soa_retry = forms.IntegerField(label=_("Retry"))
|
||||
soa_expire = forms.IntegerField(label=_("Expire"))
|
||||
soa_minimum = forms.IntegerField(label=_("Minimum"))
|
||||
|
||||
view = forms.ModelChoiceField(
|
||||
queryset=netbox_dns.models.View.objects.all(),
|
||||
disabled=True,
|
||||
required=False,
|
||||
label=_("View"),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = CatalogZone
|
||||
fields = (
|
||||
"view",
|
||||
"soa_serial",
|
||||
"soa_refresh",
|
||||
"soa_retry",
|
||||
"soa_expire",
|
||||
"soa_minimum",
|
||||
)
|
||||
|
||||
|
||||
class CatalogZoneFilterForm(NetBoxModelFilterSetForm):
|
||||
model = CatalogZone
|
||||
|
||||
q = forms.CharField(required=False, label=_("Search"))
|
||||
view = DynamicModelMultipleChoiceField(
|
||||
queryset=netbox_dns.models.View.objects.all(),
|
||||
required=False,
|
||||
)
|
||||
|
||||
|
||||
class CatalogZoneMemberFilterForm(NetBoxModelFilterSetForm):
|
||||
model = CatalogZoneMember
|
||||
|
||||
q = forms.CharField(required=False, label=_("Search"))
|
||||
catalog_zone = forms.ModelMultipleChoiceField(
|
||||
queryset=CatalogZone.objects.all(),
|
||||
required=False,
|
||||
)
|
||||
|
||||
|
||||
class SeenTransferClientFilterForm(NetBoxModelFilterSetForm):
|
||||
model = SeenTransferClient
|
||||
|
||||
q = forms.CharField(required=False, label=_("Search"))
|
||||
view = forms.ModelMultipleChoiceField(
|
||||
queryset=netbox_dns.models.View.objects.all(),
|
||||
required=False,
|
||||
)
|
||||
File renamed without changes.
@@ -0,0 +1,318 @@
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.opcode
|
||||
import dns.query
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.rrset
|
||||
import dns.tsig
|
||||
from django.conf import settings
|
||||
from django.utils import timezone
|
||||
from django.db import close_old_connections, OperationalError
|
||||
from netbox.jobs import JobRunner
|
||||
from netbox_dns.models import View, Zone, Record
|
||||
from netbox_dns_bridge.utils import get_logger
|
||||
from netbox_dns_bridge.models import SeenTransferClient, CatalogZone
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
SETTINGS = settings.PLUGINS_CONFIG.get("netbox_dns_bridge", {})
|
||||
|
||||
|
||||
def _load_tsig_key(view_name: str) -> dns.tsig.Key:
|
||||
tsig_keys = SETTINGS.get("tsig_keys", {})
|
||||
if view_name not in tsig_keys:
|
||||
raise RuntimeError(f"No TSIG key configured for view '{view_name}'")
|
||||
|
||||
key_data = tsig_keys[view_name]
|
||||
raw_key_name = key_data.get("keyname")
|
||||
secret = key_data.get("secret")
|
||||
algorithm = key_data.get("algorithm")
|
||||
if not algorithm:
|
||||
raise RuntimeError(
|
||||
f"Missing 'algorithm' in TSIG key configuration for view '{view_name}'"
|
||||
)
|
||||
|
||||
if not raw_key_name or not secret:
|
||||
raise RuntimeError(f"Incomplete TSIG key configuration for view '{view_name}'")
|
||||
|
||||
key_name = dns.name.from_text(raw_key_name, origin=None).canonicalize()
|
||||
if not key_name.is_absolute():
|
||||
key_name = key_name.concatenate(dns.name.root)
|
||||
|
||||
return dns.tsig.Key(name=key_name, secret=secret, algorithm=algorithm)
|
||||
|
||||
|
||||
def _send_notify(
|
||||
zone_name,
|
||||
soa_serial,
|
||||
targets,
|
||||
tsig_key,
|
||||
view_name,
|
||||
notify_over_tcp,
|
||||
port,
|
||||
log_prefix="NOTIFY",
|
||||
soa_refresh=60,
|
||||
soa_retry=10,
|
||||
soa_expire=1209600,
|
||||
soa_minimum=0,
|
||||
):
|
||||
"""Build a DNS NOTIFY message for *zone_name* and send it to every target IP."""
|
||||
fqdn = dns.name.from_text(zone_name, dns.name.root).to_text()
|
||||
msg = dns.message.make_query(fqdn, dns.rdatatype.SOA)
|
||||
msg.flags |= dns.flags.AA
|
||||
msg.set_opcode(dns.opcode.NOTIFY)
|
||||
|
||||
soa_rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN,
|
||||
dns.rdatatype.SOA,
|
||||
f"invalid. invalid. {soa_serial} {soa_refresh} {soa_retry} {soa_expire} {soa_minimum}",
|
||||
)
|
||||
msg.answer.append(dns.rrset.from_rdata(fqdn, 0, soa_rdata))
|
||||
msg.use_tsig(keyring={tsig_key.name: tsig_key}, keyname=tsig_key.name)
|
||||
|
||||
for target in targets:
|
||||
try:
|
||||
if notify_over_tcp:
|
||||
LOGGER.debug(f"Sending {log_prefix} over TCP")
|
||||
dns.query.tcp(msg, target, port=port, timeout=2)
|
||||
else:
|
||||
LOGGER.debug(f"Sending {log_prefix} over UDP")
|
||||
dns.query.udp(msg, target, port=port, timeout=2)
|
||||
|
||||
LOGGER.info(
|
||||
f"{log_prefix} sent: {target} {view_name}/{fqdn} {soa_serial}"
|
||||
)
|
||||
except Exception as e:
|
||||
LOGGER.error(
|
||||
f"{log_prefix} failed: {target}:{port}"
|
||||
f" {view_name}/{fqdn} {soa_serial}: {e}"
|
||||
)
|
||||
|
||||
|
||||
class SendClientNotify(JobRunner):
|
||||
class Meta:
|
||||
name = "Send DNS NOTIFY"
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
notify_over_tcp = SETTINGS.get("notify_over_tcp", False)
|
||||
port = SETTINGS.get("notify_client_port", 53)
|
||||
view_name = kwargs["view_name"]
|
||||
zone_name = kwargs["zone_name"]
|
||||
soa_serial = kwargs["soa_serial"]
|
||||
soa_refresh = kwargs.get("soa_refresh", 60)
|
||||
soa_retry = kwargs.get("soa_retry", 10)
|
||||
soa_expire = kwargs.get("soa_expire", 1209600)
|
||||
soa_minimum = kwargs.get("soa_minimum", 0)
|
||||
|
||||
try:
|
||||
view = View.objects.get(name=view_name)
|
||||
tsig_key = _load_tsig_key(view_name)
|
||||
cutoff_hours = SETTINGS.get("notify_client_alive_threshold_hours", 24)
|
||||
seen_cutoff = timezone.now() - timezone.timedelta(hours=cutoff_hours)
|
||||
|
||||
clients = list(
|
||||
SeenTransferClient.objects.filter(
|
||||
view=view, last_seen__gte=seen_cutoff
|
||||
).values_list("source_ip", flat=True)
|
||||
)
|
||||
|
||||
_send_notify(
|
||||
zone_name, soa_serial, clients, tsig_key,
|
||||
view_name, notify_over_tcp, port, log_prefix="NOTIFY",
|
||||
soa_refresh=soa_refresh, soa_retry=soa_retry,
|
||||
soa_expire=soa_expire, soa_minimum=soa_minimum,
|
||||
)
|
||||
|
||||
except View.DoesNotExist as e:
|
||||
LOGGER.error(f"Failed to get view for NOTIFY: {e}")
|
||||
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"NOTIFY failed due to unexpected error: {e}")
|
||||
close_old_connections()
|
||||
|
||||
|
||||
class SendNSNotify(JobRunner):
|
||||
"""Send a NOTIFY straight to a zone's own nameservers.
|
||||
|
||||
Unlike ``SendClientNotify`` (which notifies clients that previously queried
|
||||
the transfer endpoint), this job resolves the addresses of the zone's
|
||||
configured nameservers from NetBox DNS itself and notifies each of them so
|
||||
they pick up the changed zone quickly.
|
||||
"""
|
||||
|
||||
class Meta:
|
||||
name = "Send DNS NOTIFY to zone nameservers"
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
notify_over_tcp = SETTINGS.get("notify_over_tcp", False)
|
||||
port = SETTINGS.get("notify_ns_port", 53)
|
||||
view_name = kwargs["view_name"]
|
||||
zone_name = kwargs["zone_name"]
|
||||
soa_serial = kwargs["soa_serial"]
|
||||
|
||||
try:
|
||||
zone = Zone.objects.get(pk=kwargs["zone_id"])
|
||||
except Zone.DoesNotExist:
|
||||
LOGGER.error(f"NS NOTIFY: zone id {kwargs['zone_id']} no longer exists")
|
||||
return
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"NS NOTIFY failed due to unexpected error: {e}")
|
||||
close_old_connections()
|
||||
return
|
||||
|
||||
ns_targets = _resolve_zone_nameserver_ips(zone)
|
||||
if not ns_targets:
|
||||
LOGGER.warning(
|
||||
f"NS NOTIFY: no nameserver addresses found in NetBox DNS for "
|
||||
f"{view_name}/{zone_name} — skipping"
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
tsig_key = _load_tsig_key(view_name)
|
||||
except RuntimeError as e:
|
||||
LOGGER.error(f"NS NOTIFY aborted for {view_name}/{zone_name}: {e}")
|
||||
return
|
||||
|
||||
_send_notify(
|
||||
zone_name, soa_serial, ns_targets, tsig_key,
|
||||
view_name, notify_over_tcp, port, log_prefix="NS NOTIFY",
|
||||
)
|
||||
|
||||
|
||||
def _get_soa_serial(zone: Zone):
|
||||
"""Return the current SOA serial of a zone parsed from its SOA record."""
|
||||
try:
|
||||
soa_record = Record.objects.filter(zone=zone, type="SOA", active=True).first()
|
||||
if soa_record is None:
|
||||
LOGGER.error(f"Zone {zone.name} has no active SOA record — skipping NOTIFY")
|
||||
return None
|
||||
|
||||
return int(soa_record.value.split()[2])
|
||||
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"DB ERROR while fetching SOA for zone {zone.name}: {e}")
|
||||
close_old_connections()
|
||||
return None
|
||||
except (ValueError, IndexError) as e:
|
||||
LOGGER.error(f"Failed to parse SOA serial for zone {zone.name}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_zone_nameserver_ips(zone: Zone) -> list:
|
||||
"""Resolve the zone's nameserver hostnames to IPs using NetBox DNS records.
|
||||
|
||||
For each nameserver assigned to the zone, matching active A/AAAA records
|
||||
within the same view are looked up in NetBox DNS. Returns a de-duplicated,
|
||||
order-preserving list of IP addresses.
|
||||
"""
|
||||
ips = []
|
||||
try:
|
||||
nameservers = list(zone.nameservers.all())
|
||||
view = zone.view
|
||||
|
||||
for nameserver in nameservers:
|
||||
fqdn = dns.name.from_text(nameserver.name, dns.name.root).to_text()
|
||||
# Match both with and without a trailing dot to be resilient against
|
||||
# how the fqdn is stored on the Record model.
|
||||
candidates = {fqdn, fqdn.rstrip(".")}
|
||||
|
||||
records = Record.objects.filter(
|
||||
fqdn__in=list(candidates),
|
||||
type__in=["A", "AAAA"],
|
||||
active=True,
|
||||
zone__view=view,
|
||||
)
|
||||
for record in records:
|
||||
if record.value not in ips:
|
||||
ips.append(record.value)
|
||||
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"DB ERROR while resolving nameservers for {zone.name}: {e}")
|
||||
close_old_connections()
|
||||
|
||||
return ips
|
||||
|
||||
|
||||
def _notify_ns_enabled(zone) -> bool:
|
||||
"""Return True if a NOTIFY to the zone's nameservers should be sent.
|
||||
|
||||
Enabled either globally for every zone via ``notify_ns_all_zones`` or per
|
||||
zone when the boolean custom field named by ``notify_ns_custom_field_name``
|
||||
is set to True on the zone.
|
||||
"""
|
||||
if SETTINGS.get("notify_ns_all_zones", False):
|
||||
return True
|
||||
|
||||
cf_name = SETTINGS.get("notify_ns_custom_field_name")
|
||||
if not cf_name:
|
||||
return False
|
||||
|
||||
custom_fields = getattr(zone, "custom_field_data", None) or {}
|
||||
return custom_fields.get(cf_name) is True
|
||||
|
||||
|
||||
def schedule_client_notify(zone: Zone):
|
||||
if not SETTINGS.get("notify_clients", False):
|
||||
return
|
||||
|
||||
soa_serial = _get_soa_serial(zone)
|
||||
if soa_serial is None:
|
||||
return
|
||||
|
||||
SendClientNotify.enqueue(
|
||||
zone_name=zone.name,
|
||||
view_name=zone.view.name,
|
||||
soa_serial=soa_serial,
|
||||
)
|
||||
|
||||
|
||||
def schedule_ns_notify(zone: Zone):
|
||||
if not _notify_ns_enabled(zone):
|
||||
return
|
||||
|
||||
soa_serial = _get_soa_serial(zone)
|
||||
if soa_serial is None:
|
||||
return
|
||||
|
||||
SendNSNotify.enqueue(
|
||||
zone_id=zone.pk,
|
||||
zone_name=zone.name,
|
||||
view_name=zone.view.name,
|
||||
soa_serial=soa_serial,
|
||||
)
|
||||
|
||||
|
||||
def schedule_catalog_zone_notify(view: View):
|
||||
if not SETTINGS.get("notify_clients", False):
|
||||
return
|
||||
|
||||
try:
|
||||
catalog_zone = view.catalog_zone
|
||||
except CatalogZone.DoesNotExist:
|
||||
return
|
||||
|
||||
serial = catalog_zone.soa_serial
|
||||
soa_refresh = catalog_zone.soa_refresh
|
||||
soa_retry = catalog_zone.soa_retry
|
||||
soa_expire = catalog_zone.soa_expire
|
||||
soa_minimum = catalog_zone.soa_minimum
|
||||
|
||||
SendClientNotify.enqueue(
|
||||
zone_name="catz",
|
||||
soa_serial=serial,
|
||||
view_name=view.name,
|
||||
soa_refresh=soa_refresh,
|
||||
soa_retry=soa_retry,
|
||||
soa_expire=soa_expire,
|
||||
soa_minimum=soa_minimum,
|
||||
)
|
||||
SendClientNotify.enqueue(
|
||||
zone_name=f"{view.name}.catz",
|
||||
soa_serial=serial,
|
||||
view_name=view.name,
|
||||
soa_refresh=soa_refresh,
|
||||
soa_retry=soa_retry,
|
||||
soa_expire=soa_expire,
|
||||
soa_minimum=soa_minimum,
|
||||
)
|
||||
Whitespace-only changes.
Whitespace-only changes.
+15
-25
@@ -1,17 +1,15 @@
|
||||
import os
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.exception
|
||||
import netbox_dns.models
|
||||
from netbox_plugin_bind_provisioner.utils import export_bind_zone_file
|
||||
from netbox_dns_bridge.utils import export_bind_zone_file
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--view", type=str, help="The name of the view the Zone to be exported is in"
|
||||
"--view",
|
||||
type=str,
|
||||
help="The name of the view the Zone to be exported is in",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--zone", type=str, help="The FQDN of the Zone to be exported"
|
||||
@@ -20,16 +18,11 @@ class Command(BaseCommand):
|
||||
"--file", type=str, help="Path of the zone file to be written"
|
||||
)
|
||||
|
||||
|
||||
def handle(self, *args, **options):
|
||||
#if len(options) < 2:
|
||||
# print("export-zone <zone name> <file path>")
|
||||
# sys.exit(1)
|
||||
|
||||
# Load parameters
|
||||
view_name = options['view']
|
||||
zone_name = options['zone']
|
||||
file_path = options['file']
|
||||
view_name = options["view"]
|
||||
zone_name = options["zone"]
|
||||
file_path = options["file"]
|
||||
|
||||
if not view_name:
|
||||
raise CommandError("No --view parameter given")
|
||||
@@ -40,17 +33,14 @@ class Command(BaseCommand):
|
||||
|
||||
try:
|
||||
# Load the zone from NetBox DNS
|
||||
nb_zone = netbox_dns.models.Zone.objects.get(view__name=view_name, name=zone_name)
|
||||
nb_zone = netbox_dns.models.Zone.objects.get(
|
||||
view__name=view_name, name=zone_name
|
||||
)
|
||||
|
||||
if nb_zone:
|
||||
export_bind_zone_file(nb_zone, file_path=file_path)
|
||||
else:
|
||||
print("Zone not found in Netbox. Aborting")
|
||||
sys.exit(1)
|
||||
export_bind_zone_file(nb_zone, file_path=file_path)
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(f"Zone '{zone_name}' exported to '{file_path}'")
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise CommandError(f"Failed to export zone: {e}")
|
||||
|
||||
self.stdout.write(self.style.SUCCESS(f"Zone '{zone_name}' exported to '{file_path}'"))
|
||||
|
||||
|
||||
+9
-8
@@ -1,22 +1,21 @@
|
||||
import os
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.exception
|
||||
import netbox_dns.models
|
||||
from netbox_plugin_bind_provisioner.utils import export_bind_zone_file
|
||||
from netbox_dns_bridge.utils import export_bind_zone_file
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--path", type=str, help="Path to the directory where zone files are to be written"
|
||||
"--path",
|
||||
type=str,
|
||||
help="Path to the directory where zone files are to be written",
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
# Load parameters
|
||||
base_path = options['path']
|
||||
base_path = options["path"]
|
||||
|
||||
if not base_path:
|
||||
raise CommandError("No --path parameter given")
|
||||
@@ -42,6 +41,8 @@ class Command(BaseCommand):
|
||||
try:
|
||||
# Call existing export function
|
||||
export_bind_zone_file(zone, file_path=file_path)
|
||||
self.stdout.write(self.style.SUCCESS(f"Exported zone '{zone.name}' to '{file_path}'"))
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(f"Exported zone '{zone.name}' to '{file_path}'")
|
||||
)
|
||||
except Exception as e:
|
||||
self.stderr.write(f"Failed to export zone '{zone.name}': {e}")
|
||||
@@ -0,0 +1,117 @@
|
||||
import threading
|
||||
import sys
|
||||
import dns.query
|
||||
import dns.message
|
||||
import dns.tsigkeyring
|
||||
import dns.name
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.rdtypes
|
||||
import dns.exception
|
||||
import dns.renderer
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.conf import settings
|
||||
from django.db import OperationalError
|
||||
from netbox_dns.models import View
|
||||
from .dns_transfer_endpoint.request_handler import UDPRequestHandler, TCPRequestHandler
|
||||
from .dns_transfer_endpoint.dns_server import UDPDNSServer, TCPDNSServer
|
||||
from netbox_dns_bridge.utils import get_logger
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
SETTINGS = settings.PLUGINS_CONFIG.get("netbox_dns_bridge", {})
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Run a minimal AXFR DNS server using data from NetBox DNS plugin"
|
||||
|
||||
def _load_tsig_key_settings(self):
|
||||
self.keyring = {}
|
||||
self.tsig_view_map = {}
|
||||
|
||||
for view_name, data in self.tsig_keys.items():
|
||||
key_name = data.get("keyname")
|
||||
secret = data.get("secret")
|
||||
algorithm = data.get("algorithm", "hmac-sha256")
|
||||
|
||||
if not key_name:
|
||||
LOGGER.error(
|
||||
f"TSIG key for view {view_name} not found. Cannot start transfer endpoint."
|
||||
)
|
||||
sys.exit(1)
|
||||
elif not secret:
|
||||
LOGGER.error(
|
||||
f"TSIG secret for key {key_name} not found. Cannot start transfer endpoint."
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
nb_view = View.objects.get(name=view_name)
|
||||
except View.DoesNotExist:
|
||||
LOGGER.error(
|
||||
f"Skipping TSIG key {key_name}: View '{view_name}' not found in database."
|
||||
)
|
||||
continue
|
||||
except OperationalError as e:
|
||||
LOGGER.error(
|
||||
f"There was an error retrieving view model from database: {e}"
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
# Normalize key name to absolute DNS name
|
||||
key_name_obj = dns.name.from_text(
|
||||
key_name, origin=dns.name.root
|
||||
).canonicalize()
|
||||
key_name_str = key_name_obj.to_text() # Will always include trailing do
|
||||
|
||||
self.keyring[key_name_obj] = dns.tsig.Key(
|
||||
name=key_name_obj, secret=secret, algorithm=algorithm
|
||||
)
|
||||
self.tsig_view_map[key_name_str] = nb_view
|
||||
LOGGER.info(f"Loaded TSIG key {key_name_str} for view {nb_view.name}")
|
||||
|
||||
if not self.keyring:
|
||||
msg = "No TSIG keys found in database."
|
||||
LOGGER.critical(msg)
|
||||
raise RuntimeError(msg)
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--port", type=int, default=5354, help="Port number to listen on"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--address", type=str, default="0.0.0.0", help="IP to bind to"
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
# Load parameters
|
||||
port = options["port"]
|
||||
address = options["address"]
|
||||
|
||||
self.tsig_keys = SETTINGS.get("tsig_keys", None)
|
||||
if not self.tsig_keys:
|
||||
raise RuntimeError("tsig_keys variable not set in plugin settings.")
|
||||
|
||||
self._load_tsig_key_settings()
|
||||
|
||||
udp_server = UDPDNSServer(
|
||||
(address, port), UDPRequestHandler, self.keyring, self.tsig_view_map
|
||||
)
|
||||
|
||||
tcp_server = TCPDNSServer(
|
||||
(address, port), TCPRequestHandler, self.keyring, self.tsig_view_map
|
||||
)
|
||||
|
||||
def _run_udp_server(server):
|
||||
LOGGER.info(f"Query endpoint listening on {address} udp/{port}")
|
||||
server.serve_forever()
|
||||
|
||||
udp_thread = threading.Thread(
|
||||
target=_run_udp_server, args=(udp_server,), daemon=True
|
||||
)
|
||||
|
||||
udp_thread.start()
|
||||
|
||||
LOGGER.info(f"Query endpoint listening on {address} tcp/{port}")
|
||||
tcp_server.serve_forever()
|
||||
Whitespace-only changes.
@@ -0,0 +1,205 @@
|
||||
import dns.name
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
from netbox_dns_bridge.utils import get_logger
|
||||
from netbox_dns.models import Zone as NBZone, View as NBView
|
||||
from netbox_dns_bridge.models import CatalogZone, CatalogZoneMember
|
||||
from netbox_dns_bridge.jobs import notify
|
||||
from uuid import uuid4
|
||||
from base64 import b32encode
|
||||
from django.db import transaction, close_old_connections, OperationalError
|
||||
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
||||
def increment_soa_serial(view: NBView) -> int:
|
||||
with transaction.atomic():
|
||||
try:
|
||||
(
|
||||
soa_serial_obj,
|
||||
_,
|
||||
) = CatalogZone.objects.select_for_update().get_or_create(
|
||||
view=view,
|
||||
defaults={"soa_serial": 1},
|
||||
)
|
||||
|
||||
new_soa_serial = soa_serial_obj.soa_serial + 1
|
||||
if new_soa_serial > 0xFFFFFFFF:
|
||||
LOGGER.warning(
|
||||
f"Catalog serial {soa_serial_obj.soa_serial} reached max — wrapping back to 1"
|
||||
)
|
||||
new_soa_serial = 1
|
||||
soa_serial_obj.soa_serial = new_soa_serial
|
||||
soa_serial_obj.save()
|
||||
soa_serial_obj.refresh_from_db()
|
||||
LOGGER.debug(
|
||||
f"Catalog zone SOA serial for view '{view.name}' "
|
||||
f"is now {soa_serial_obj.soa_serial}"
|
||||
)
|
||||
|
||||
serial = soa_serial_obj.soa_serial
|
||||
except OperationalError as e:
|
||||
LOGGER.error(
|
||||
f"ERROR: Failed to increment the Catalog Zone's SOA serial: {e}"
|
||||
)
|
||||
close_old_connections()
|
||||
return None
|
||||
|
||||
notify.schedule_catalog_zone_notify(view)
|
||||
return serial
|
||||
|
||||
|
||||
def create_zone(name, view_name) -> dns.zone.Zone:
|
||||
# Zone origin
|
||||
origin = dns.name.from_text(name, dns.name.root)
|
||||
|
||||
# Create a new empty zone
|
||||
zone = dns.zone.Zone(origin)
|
||||
zone.rdclass = dns.rdataclass.IN
|
||||
|
||||
try:
|
||||
# get zones from netbox
|
||||
nb_zones = NBZone.objects.filter(
|
||||
view__name=view_name, active=True
|
||||
).select_related("catalog_zone_member")
|
||||
|
||||
ptr_base = dns.name.from_text("zones", origin)
|
||||
|
||||
for nb_zone in nb_zones:
|
||||
ttl = 0
|
||||
qname = dns.name.from_text(nb_zone.name, dns.name.root)
|
||||
|
||||
# Create PTR record
|
||||
try:
|
||||
member = nb_zone.catalog_zone_member
|
||||
except NBZone.catalog_zone_member.RelatedObjectDoesNotExist:
|
||||
catalog_zone = _get_or_create_catalog_zone(nb_zone.view)
|
||||
member = CatalogZoneMember.objects.create(
|
||||
zone=nb_zone,
|
||||
name=_generate_member_name(),
|
||||
catalog_zone=catalog_zone,
|
||||
)
|
||||
|
||||
p_name = member.name
|
||||
|
||||
ptr_name = dns.name.from_text(p_name, ptr_base)
|
||||
if not ptr_name.is_subdomain(origin):
|
||||
raise ValueError(
|
||||
f"Catalog zone member {ptr_name.to_text()} not a subdomain"
|
||||
)
|
||||
rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN, dns.rdatatype.PTR, qname.to_text()
|
||||
)
|
||||
rdataset = zone.find_rdataset(ptr_name, dns.rdatatype.PTR, create=True)
|
||||
rdataset.add(rdata, ttl)
|
||||
|
||||
# Configure DNSSec Policy for member Zone if DNSSec is enabled
|
||||
if nb_zone.dnssec_policy:
|
||||
rid = dns.name.from_text("group", ptr_name)
|
||||
policy_name = nb_zone.dnssec_policy.name.rstrip(" ")
|
||||
group_name = f"dnssec-policy-{policy_name}"
|
||||
rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN, dns.rdatatype.TXT, group_name
|
||||
)
|
||||
rdataset = zone.find_rdataset(rid, dns.rdatatype.TXT, create=True)
|
||||
rdataset.add(rdata, ttl)
|
||||
|
||||
zone_root_node = zone.find_node(origin, create=True)
|
||||
|
||||
# SOA record
|
||||
view = NBView.objects.get(name=view_name)
|
||||
soa_rdataset = _create_soa_rdataset(view)
|
||||
zone_root_node.rdatasets.append(soa_rdataset)
|
||||
|
||||
# NS record
|
||||
ns_rdataset = _create_ns_rdataset()
|
||||
zone_root_node.rdatasets.append(ns_rdataset)
|
||||
|
||||
# version.catz. record
|
||||
version_rdataset = _create_version_rdataset()
|
||||
zone_version_node = zone.find_node(
|
||||
dns.name.from_text("version", origin), create=True
|
||||
)
|
||||
zone_version_node.rdatasets.append(version_rdataset)
|
||||
|
||||
return zone
|
||||
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"ERROR: Failed to create Catalog Zone: {e}")
|
||||
close_old_connections()
|
||||
return None
|
||||
|
||||
|
||||
def _generate_member_name() -> str:
|
||||
return b32encode(uuid4().bytes)[0:26].lower().decode("UTF-8")
|
||||
|
||||
|
||||
def _get_or_create_catalog_zone(view: NBView) -> CatalogZone:
|
||||
catalog_zone, _ = CatalogZone.objects.get_or_create(
|
||||
view=view, defaults={"soa_serial": 1}
|
||||
)
|
||||
return catalog_zone
|
||||
|
||||
|
||||
def update_member(zone: NBZone) -> None:
|
||||
try:
|
||||
catalog_zone = _get_or_create_catalog_zone(zone.view)
|
||||
CatalogZoneMember.objects.update_or_create(
|
||||
zone=zone,
|
||||
defaults={
|
||||
"name": _generate_member_name(),
|
||||
"catalog_zone": catalog_zone,
|
||||
},
|
||||
)
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"ERROR: Failed to update Catalog Zone member: {e}")
|
||||
close_old_connections()
|
||||
|
||||
|
||||
def _create_soa_rdataset(view: NBView) -> dns.rdataset:
|
||||
try:
|
||||
serial_obj, _ = CatalogZone.objects.get_or_create(
|
||||
view=view, defaults={"soa_serial": 1}
|
||||
)
|
||||
serial = serial_obj.soa_serial
|
||||
|
||||
# SOA Record components
|
||||
ttl = 0
|
||||
rclass = dns.rdataclass.IN
|
||||
rtype = dns.rdatatype.SOA
|
||||
|
||||
# Create SOA rdata object
|
||||
rdata = dns.rdata.from_text(
|
||||
rclass,
|
||||
rtype,
|
||||
f"invalid. invalid. {serial} {serial_obj.soa_refresh} "
|
||||
f"{serial_obj.soa_retry} {serial_obj.soa_expire} "
|
||||
f"{serial_obj.soa_minimum}",
|
||||
)
|
||||
|
||||
# Create Rdataset and add the RDATA to it
|
||||
rdataset = dns.rdataset.Rdataset(rclass, rtype)
|
||||
rdataset.add(rdata, ttl)
|
||||
return rdataset
|
||||
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"ERROR: Failed to access catz SOA record in database: {e}")
|
||||
close_old_connections()
|
||||
|
||||
|
||||
def _create_ns_rdataset() -> dns.rdataset:
|
||||
# NS record for catz.
|
||||
name = dns.name.from_text("invalid", dns.name.root)
|
||||
rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.NS, str(name))
|
||||
rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.NS)
|
||||
rdataset.add(rdata, 0)
|
||||
return rdataset
|
||||
|
||||
|
||||
def _create_version_rdataset() -> dns.rdataset:
|
||||
rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT, '"2"')
|
||||
rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.TXT)
|
||||
rdataset.add(rdata, 0)
|
||||
return rdataset
|
||||
@@ -0,0 +1,46 @@
|
||||
import socketserver
|
||||
import socket
|
||||
from netbox_dns_bridge.utils import get_logger
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
||||
class DNSAddressMixin:
|
||||
def _resolve_address(self, server_address, socktype, proto):
|
||||
host, port = server_address
|
||||
|
||||
infos = socket.getaddrinfo(
|
||||
host, port, socket.AF_UNSPEC, socktype, proto, socket.AI_PASSIVE
|
||||
)
|
||||
|
||||
family, _, _, _, sockaddr = infos[0]
|
||||
self.address_family = family
|
||||
return sockaddr
|
||||
|
||||
|
||||
class TCPDNSServer(DNSAddressMixin, socketserver.TCPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, server_address, handler_class, keyring, tsig_view_map):
|
||||
sockaddr = self._resolve_address(
|
||||
server_address, socket.SOCK_STREAM, socket.IPPROTO_TCP
|
||||
)
|
||||
|
||||
super().__init__(sockaddr, handler_class)
|
||||
|
||||
self.keyring = keyring
|
||||
self.tsig_view_map = tsig_view_map
|
||||
|
||||
|
||||
class UDPDNSServer(DNSAddressMixin, socketserver.UDPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, server_address, handler_class, keyring, tsig_view_map):
|
||||
sockaddr = self._resolve_address(
|
||||
server_address, socket.SOCK_DGRAM, socket.IPPROTO_UDP
|
||||
)
|
||||
|
||||
super().__init__(sockaddr, handler_class)
|
||||
|
||||
self.keyring = keyring
|
||||
self.tsig_view_map = tsig_view_map
|
||||
@@ -0,0 +1,382 @@
|
||||
import socketserver
|
||||
import socket
|
||||
import dns.query
|
||||
import dns.message
|
||||
import dns.tsigkeyring
|
||||
import dns.name
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.rdtypes
|
||||
import dns.exception
|
||||
import dns.renderer
|
||||
from django.utils import timezone
|
||||
from django.db import close_old_connections, OperationalError
|
||||
from django.conf import settings
|
||||
from netbox_dns.models import Zone, View
|
||||
from . import catalog_zone_manager as catzm
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from netbox_dns_bridge.utils import build_dns_zone, get_logger
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
SETTINGS = settings.PLUGINS_CONFIG.get("netbox_dns_bridge", {})
|
||||
|
||||
|
||||
class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
|
||||
transport = None
|
||||
|
||||
def __init__(self, request, client_address, server) -> None:
|
||||
self.MAX_WIRE = 65535
|
||||
self.RESERVED_TSIG = 300
|
||||
super().__init__(request, client_address, server)
|
||||
|
||||
# _get_zone_from_nb rewritten
|
||||
def _get_zone_from_nb(self, zone_name, view_name) -> dns.zone.Zone:
|
||||
# Find the zone
|
||||
try:
|
||||
nb_zone = Zone.objects.get(
|
||||
name=zone_name,
|
||||
view__name=view_name,
|
||||
active=True,
|
||||
)
|
||||
return build_dns_zone(nb_zone)
|
||||
except Zone.DoesNotExist:
|
||||
return None
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"DB ERROR: {e}")
|
||||
close_old_connections()
|
||||
|
||||
def _deny_request_bad_tsig(self, wire, tsig_error: dns.rcode) -> None:
|
||||
# Use empty keyring to parse TSIG without validating
|
||||
query = dns.message.from_wire(
|
||||
wire, keyring={}, ignore_trailing=True, continue_on_error=True
|
||||
)
|
||||
|
||||
# Make a response
|
||||
response = dns.message.make_response(query)
|
||||
response.set_rcode(dns.rcode.REFUSED)
|
||||
|
||||
if query.had_tsig:
|
||||
# Add TSIG with error code, but do not sign (no MAC, empty keyring)
|
||||
response.use_tsig(
|
||||
keyring={}, # empty; we're not signing
|
||||
keyname=query.keyname,
|
||||
tsig_error=tsig_error,
|
||||
)
|
||||
self._send_response(response.to_wire())
|
||||
|
||||
def _send_response(self, data) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def _deny_request(self, query, rcode: dns.rcode = dns.rcode.REFUSED) -> None:
|
||||
response = dns.message.make_response(query)
|
||||
response.set_rcode(rcode)
|
||||
wire = response.to_wire(multi=False)
|
||||
self._send_response(wire)
|
||||
|
||||
def _track_seen_client(self, source_ip: str, view: View) -> None:
|
||||
if SETTINGS.get("notify_clients", False):
|
||||
try:
|
||||
SeenTransferClient.objects.update_or_create(
|
||||
source_ip=source_ip,
|
||||
view=view,
|
||||
defaults={"last_seen": timezone.now()},
|
||||
)
|
||||
|
||||
except OperationalError as e:
|
||||
LOGGER.error(f"DB ERROR: {e}")
|
||||
close_old_connections()
|
||||
|
||||
def _handle_soa_request(self, query, soa_rrset, zone, peer, nb_view, dname) -> None:
|
||||
# We assume that the SOA rdataset has at least one record (it usually does).
|
||||
soa_rdata = soa_rrset[0] # Get the first SOA record
|
||||
|
||||
# Now, create the rrset from the soa_rdata
|
||||
rrset = dns.rrset.from_rdata(zone.origin, soa_rrset.ttl, soa_rdata)
|
||||
|
||||
response = dns.message.make_response(query)
|
||||
# Set the Authoritative Answer flag
|
||||
response.flags |= dns.flags.AA
|
||||
|
||||
# Append the rrset to the response's answer section
|
||||
response.answer.append(rrset)
|
||||
|
||||
# TSIG response
|
||||
if query.had_tsig:
|
||||
# If key was found in DB
|
||||
if query.keyname in self.server.keyring:
|
||||
response.use_tsig(
|
||||
self.server.keyring, keyname=query.keyname, original_id=query.id
|
||||
)
|
||||
else:
|
||||
# unknown key — use an empty keyring so use_tsig() does not
|
||||
# raise KeyError trying to look up a key that isn't present.
|
||||
response.set_rcode(dns.rcode.REFUSED)
|
||||
response.use_tsig(
|
||||
{}, # empty keyring; no signing
|
||||
keyname=query.keyname,
|
||||
tsig_error=dns.rcode.BADKEY,
|
||||
)
|
||||
|
||||
data = response.to_wire(max_size=512)
|
||||
self._send_response(data)
|
||||
LOGGER.info(f"{peer} SOA {nb_view.name}/{dname}")
|
||||
|
||||
def _handle_axfr_request(self, query, zone, peer, nb_view, dname) -> None:
|
||||
if query.keyname not in self.server.keyring:
|
||||
LOGGER.error(f"AXFR aborted: keyname {query.keyname} not in keyring")
|
||||
self._deny_request(query)
|
||||
return
|
||||
|
||||
tsig_key = self.server.keyring[query.keyname]
|
||||
|
||||
rrsets = []
|
||||
soa_rrset = None
|
||||
for name, rdataset in zone.iterate_rdatasets():
|
||||
if not name.is_absolute():
|
||||
name = name.concatenate(zone.origin)
|
||||
rrset = dns.rrset.from_rdata_list(name, rdataset.ttl, rdataset)
|
||||
if rdataset.rdtype == dns.rdatatype.SOA and soa_rrset is None:
|
||||
soa_rrset = rrset
|
||||
else:
|
||||
rrsets.append(rrset)
|
||||
|
||||
if soa_rrset is None:
|
||||
LOGGER.error(f"Zone {dname} has no SOA — aborting")
|
||||
return
|
||||
|
||||
rrsets.insert(0, soa_rrset) # Opening SOA
|
||||
rrsets.append(soa_rrset) # Closing SOA
|
||||
|
||||
# 2. Create a Renderer for the first message
|
||||
r = dns.renderer.Renderer(
|
||||
id=query.id,
|
||||
flags=(dns.flags.QR | dns.flags.AA),
|
||||
max_size=self.MAX_WIRE,
|
||||
origin=None,
|
||||
)
|
||||
r.add_question(
|
||||
query.question[0].name,
|
||||
query.question[0].rdtype,
|
||||
query.question[0].rdclass,
|
||||
)
|
||||
|
||||
# 3. Loop through RRsets
|
||||
tsig_ctx = None
|
||||
for rrset in rrsets:
|
||||
try:
|
||||
r.add_rrset(dns.renderer.ANSWER, rrset)
|
||||
if r.max_size - len(r.output.getvalue()) < self.RESERVED_TSIG:
|
||||
raise dns.exception.TooBig("TSIG wont fit")
|
||||
except dns.exception.TooBig:
|
||||
# TSIG chain previous message
|
||||
r.write_header()
|
||||
tsig_ctx = r.add_multi_tsig(
|
||||
ctx=tsig_ctx,
|
||||
secret=tsig_key.secret,
|
||||
algorithm=tsig_key.algorithm,
|
||||
keyname=query.keyname,
|
||||
fudge=300,
|
||||
id=query.id,
|
||||
tsig_error=0,
|
||||
other_data=b"",
|
||||
request_mac=r.mac if tsig_ctx else query.mac,
|
||||
)
|
||||
wire = r.get_wire()
|
||||
self.request.sendall(len(wire).to_bytes(2, "big") + wire)
|
||||
|
||||
# Start new renderer
|
||||
r = dns.renderer.Renderer(
|
||||
id=query.id,
|
||||
flags=(dns.flags.QR | dns.flags.AA),
|
||||
max_size=self.MAX_WIRE,
|
||||
origin=None,
|
||||
)
|
||||
r.add_question(
|
||||
query.question[0].name,
|
||||
query.question[0].rdtype,
|
||||
query.question[0].rdclass,
|
||||
)
|
||||
|
||||
try:
|
||||
r.add_rrset(dns.renderer.ANSWER, rrset)
|
||||
except dns.exception.TooBig:
|
||||
LOGGER.error(
|
||||
f"RRset {rrset.name}/{dns.rdatatype.to_text(rrset.rdtype)} "
|
||||
f"exceeds MAX_WIRE ({self.MAX_WIRE}) and cannot be sent; "
|
||||
f"skipping."
|
||||
)
|
||||
|
||||
# 4. Final message with terminating TSIG
|
||||
r.write_header()
|
||||
tsig_ctx = r.add_multi_tsig(
|
||||
ctx=tsig_ctx,
|
||||
secret=tsig_key.secret,
|
||||
algorithm=tsig_key.algorithm,
|
||||
keyname=query.keyname,
|
||||
fudge=300,
|
||||
id=query.id,
|
||||
tsig_error=0,
|
||||
other_data=b"",
|
||||
request_mac=r.mac if tsig_ctx else query.mac,
|
||||
)
|
||||
wire = r.get_wire()
|
||||
self._send_response(wire)
|
||||
LOGGER.info(f"{peer} AXFR {nb_view.name}/{dname}")
|
||||
|
||||
def _handle_dns_query(self, wire) -> None:
|
||||
peer = self.client_address[0]
|
||||
try:
|
||||
query = dns.message.from_wire(
|
||||
wire,
|
||||
keyring=self.server.keyring,
|
||||
continue_on_error=False,
|
||||
ignore_trailing=True,
|
||||
)
|
||||
|
||||
except dns.tsig.BadSignature as e:
|
||||
LOGGER.warning(f"Request denied from {peer} failed TSIG verification: {e}")
|
||||
self._deny_request_bad_tsig(wire, dns.rcode.BADSIG)
|
||||
return
|
||||
|
||||
except (dns.message.UnknownTSIGKey, dns.tsig.BadAlgorithm) as e:
|
||||
LOGGER.warning(f"Request denied from {peer} with bad TSIG key: {e}")
|
||||
self._deny_request_bad_tsig(wire, dns.rcode.BADKEY)
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
LOGGER.error(f"Error parsing query: {e}")
|
||||
return
|
||||
|
||||
# If there was no question in the query, refuse
|
||||
if len(query.question) != 1:
|
||||
self._deny_request(query)
|
||||
return
|
||||
|
||||
question = query.question[0]
|
||||
qname = question.name
|
||||
qtype = question.rdtype
|
||||
dname = qname.to_text().rstrip(".")
|
||||
|
||||
# Only process AXFR/SOA queris
|
||||
if qtype not in (dns.rdatatype.AXFR, dns.rdatatype.SOA):
|
||||
LOGGER.warning(
|
||||
f"Request denied from {peer}: Request was not AXFR or SOA (Type: {qtype})"
|
||||
)
|
||||
self._deny_request(query)
|
||||
return
|
||||
|
||||
if qtype == dns.rdatatype.AXFR and self.transport != "tcp":
|
||||
LOGGER.warning(f"Request denied from {peer}: AXFR requires TCP")
|
||||
self._deny_request(query, dns.rcode.REFUSED)
|
||||
return
|
||||
|
||||
# Identify TSIG key used
|
||||
if not query.had_tsig:
|
||||
LOGGER.warning(f"Request denied from {peer}: No TSIG key used")
|
||||
self._deny_request(query)
|
||||
return
|
||||
|
||||
key_name = query.keyname.canonicalize().to_text()
|
||||
|
||||
# Check if the key matches a view
|
||||
nb_view = self.server.tsig_view_map.get(key_name)
|
||||
if not nb_view:
|
||||
LOGGER.warning(
|
||||
f"Request denied from {peer}: {key_name} does not match a view"
|
||||
)
|
||||
self._deny_request(query)
|
||||
return
|
||||
|
||||
# Check if catalog zone
|
||||
dname_lower = dname.lower()
|
||||
if dname_lower == "catz" or dname_lower == f"{nb_view.name.lower()}.catz":
|
||||
zone = catzm.create_zone(dname_lower, nb_view.name)
|
||||
else:
|
||||
zone = self._get_zone_from_nb(dname, nb_view.name)
|
||||
# When zone was not found, let client know
|
||||
if not zone:
|
||||
LOGGER.warning(f"Zone {dname} not found in view {nb_view.name}")
|
||||
self._deny_request(query)
|
||||
return
|
||||
|
||||
# Retrieve the existing SOA record from the Zone
|
||||
soa_rrset = zone.get_rdataset(zone.origin, dns.rdatatype.SOA)
|
||||
if soa_rrset is None:
|
||||
LOGGER.error(f"Zone {dname} has no SOA — aborting")
|
||||
return
|
||||
|
||||
if qtype == dns.rdatatype.SOA:
|
||||
self._handle_soa_request(query, soa_rrset, zone, peer, nb_view, dname)
|
||||
self._track_seen_client(peer, nb_view)
|
||||
elif qtype == dns.rdatatype.AXFR:
|
||||
self._handle_axfr_request(query, zone, peer, nb_view, dname)
|
||||
self._track_seen_client(peer, nb_view)
|
||||
|
||||
|
||||
class UDPRequestHandler(DNSBaseRequestHandler):
|
||||
transport = "udp"
|
||||
|
||||
def __init__(self, request, client_address, server) -> None:
|
||||
super().__init__(request, client_address, server)
|
||||
|
||||
def _send_response(self, data) -> None:
|
||||
sock = self.request[1]
|
||||
sock.sendto(data, self.client_address)
|
||||
|
||||
def handle(self) -> None:
|
||||
data, sock = self.request
|
||||
peer = self.client_address[0]
|
||||
try:
|
||||
self._handle_dns_query(data)
|
||||
except Exception as e:
|
||||
LOGGER.error(f"Error handling request from {peer}: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
class TCPRequestHandler(DNSBaseRequestHandler):
|
||||
transport = "tcp"
|
||||
|
||||
def __init__(self, request, client_address, server) -> None:
|
||||
super().__init__(request, client_address, server)
|
||||
|
||||
def _send_response(self, data) -> None:
|
||||
length = len(data).to_bytes(2, byteorder="big")
|
||||
self.request.sendall(length + data)
|
||||
|
||||
def handle(self) -> None:
|
||||
peer = self.client_address[0]
|
||||
sock = self.request # TCP socket
|
||||
sock.settimeout(10.0) # Default 10 second timeout for inactivity
|
||||
try:
|
||||
while True:
|
||||
# Read 2-byte length prefix
|
||||
length_data = sock.recv(2)
|
||||
if not length_data:
|
||||
return # connection closed by peer
|
||||
if len(length_data) < 2:
|
||||
# Incomplete length data, wait for more or fail
|
||||
while len(length_data) < 2:
|
||||
chunk = sock.recv(2 - len(length_data))
|
||||
if not chunk:
|
||||
return
|
||||
length_data += chunk
|
||||
|
||||
length = int.from_bytes(length_data, byteorder="big")
|
||||
wire = b""
|
||||
while len(wire) < length:
|
||||
chunk = sock.recv(length - len(wire))
|
||||
if not chunk:
|
||||
return # connection closed
|
||||
wire += chunk
|
||||
self._handle_dns_query(wire)
|
||||
|
||||
except socket.timeout:
|
||||
LOGGER.debug(f"Connection from {peer} timed out")
|
||||
except Exception as e:
|
||||
LOGGER.error(f"Error handling request from {peer}: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
@@ -0,0 +1,58 @@
|
||||
# Generated by Django 5.2.9 on 2026-04-08 11:29
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
(
|
||||
"netbox_dns",
|
||||
"0030_dnsseckeytemplate_comments_dnsseckeytemplate_owner_and_more",
|
||||
),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="IntegerKeyValueSetting",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("key", models.CharField(max_length=64)),
|
||||
("value", models.IntegerField()),
|
||||
],
|
||||
options={
|
||||
"default_permissions": (),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="CatalogZoneMemberIdentifier",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("name", models.CharField(max_length=26, unique=True)),
|
||||
(
|
||||
"zone",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="catz_identifier",
|
||||
to="netbox_dns.zone",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("name",),
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,32 @@
|
||||
# Generated by Django 5.2.9 on 2026-06-09 21:56
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('netbox_dns', '0030_dnsseckeytemplate_comments_dnsseckeytemplate_owner_and_more'),
|
||||
('netbox_dns_bridge', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='integerkeyvaluesetting',
|
||||
options={},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SeenTransferClients',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
|
||||
('source_ip', models.GenericIPAddressField()),
|
||||
('last_seen', models.DateTimeField()),
|
||||
('view', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='seen_transfer_clients', to='netbox_dns.view')),
|
||||
],
|
||||
options={
|
||||
'ordering': ('source_ip',),
|
||||
'constraints': [models.UniqueConstraint(fields=('source_ip', 'view'), name='unique_ip_view_seen_client')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,233 @@
|
||||
import taggit.managers
|
||||
import utilities.json
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def copy_serials_and_link_members(apps, schema_editor):
|
||||
"""Seed one CatalogZone per view from the old global serial and link members."""
|
||||
IntegerKeyValueSetting = apps.get_model(
|
||||
"netbox_dns_bridge", "IntegerKeyValueSetting"
|
||||
)
|
||||
CatalogZone = apps.get_model("netbox_dns_bridge", "CatalogZone")
|
||||
CatalogZoneMember = apps.get_model("netbox_dns_bridge", "CatalogZoneMember")
|
||||
|
||||
# Preserve the current global serial; default to 1 when never initialized.
|
||||
seed_serial = 1
|
||||
kv = IntegerKeyValueSetting.objects.filter(key="catalog-zone-soa-serial").first()
|
||||
if kv is not None:
|
||||
seed_serial = kv.value
|
||||
|
||||
# Create a CatalogZone for every view that currently has at least one
|
||||
# member, seeding each with the old global serial.
|
||||
view_ids = set(
|
||||
CatalogZoneMember.objects.exclude(
|
||||
zone__view__isnull=True
|
||||
).values_list("zone__view_id", flat=True)
|
||||
)
|
||||
|
||||
view_id_to_catalog_zone = {}
|
||||
for view_id in view_ids:
|
||||
cz, _ = CatalogZone.objects.get_or_create(
|
||||
view_id=view_id, defaults={"soa_serial": seed_serial}
|
||||
)
|
||||
view_id_to_catalog_zone[view_id] = cz
|
||||
|
||||
# Link each member to the CatalogZone matching its zone's view.
|
||||
for member in CatalogZoneMember.objects.select_related("zone__view"):
|
||||
cz = view_id_to_catalog_zone.get(member.zone.view_id)
|
||||
if cz is None:
|
||||
# Defensive: member existed without a resolvable view. Create
|
||||
# the CatalogZone on demand so the NOT NULL constraint can be set.
|
||||
cz, _ = CatalogZone.objects.get_or_create(
|
||||
view_id=member.zone.view_id, defaults={"soa_serial": seed_serial}
|
||||
)
|
||||
view_id_to_catalog_zone[member.zone.view_id] = cz
|
||||
member.catalog_zone = cz
|
||||
member.save(update_fields=["catalog_zone"])
|
||||
|
||||
|
||||
def reverse_migration(apps, schema_editor):
|
||||
"""Best-effort reverse: restore the KV row and null the FK."""
|
||||
IntegerKeyValueSetting = apps.get_model(
|
||||
"netbox_dns_bridge", "IntegerKeyValueSetting"
|
||||
)
|
||||
CatalogZone = apps.get_model("netbox_dns_bridge", "CatalogZone")
|
||||
CatalogZoneMember = apps.get_model("netbox_dns_bridge", "CatalogZoneMember")
|
||||
|
||||
# Pick a representative serial (first catalog zone) to write back.
|
||||
first = CatalogZone.objects.order_by("pk").first()
|
||||
serial = first.soa_serial if first is not None else 1
|
||||
IntegerKeyValueSetting.objects.update_or_create(
|
||||
key="catalog-zone-soa-serial", defaults={"value": serial}
|
||||
)
|
||||
|
||||
CatalogZoneMember.objects.update(catalog_zone=None)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("extras", "0140_imageattachment_image_size"),
|
||||
(
|
||||
"netbox_dns",
|
||||
"0032_record_expiration_date",
|
||||
),
|
||||
("netbox_dns_bridge", "0002_alter_integerkeyvaluesetting_options_and_more"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
# --- CatalogZone (full NetBoxModel, born with all fields) ---
|
||||
migrations.CreateModel(
|
||||
name="CatalogZone",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("soa_serial", models.IntegerField(default=1)),
|
||||
("soa_refresh", models.IntegerField(default=60)),
|
||||
("soa_retry", models.IntegerField(default=10)),
|
||||
("soa_expire", models.IntegerField(default=1209600)),
|
||||
("soa_minimum", models.IntegerField(default=0)),
|
||||
("created", models.DateTimeField(auto_now_add=True, null=True)),
|
||||
("last_updated", models.DateTimeField(auto_now=True, null=True)),
|
||||
(
|
||||
"custom_field_data",
|
||||
models.JSONField(
|
||||
blank=True,
|
||||
default=dict,
|
||||
encoder=utilities.json.CustomFieldJSONEncoder,
|
||||
),
|
||||
),
|
||||
(
|
||||
"tags",
|
||||
taggit.managers.TaggableManager(
|
||||
through="extras.TaggedItem", to="extras.Tag"
|
||||
),
|
||||
),
|
||||
(
|
||||
"view",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="catalog_zone",
|
||||
to="netbox_dns.view",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("view__name",),
|
||||
},
|
||||
),
|
||||
# --- CatalogZoneMemberIdentifier → CatalogZoneMember (rename + full NetBoxModel) ---
|
||||
migrations.RenameModel(
|
||||
old_name="CatalogZoneMemberIdentifier",
|
||||
new_name="CatalogZoneMember",
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="catalogzonemember",
|
||||
name="created",
|
||||
field=models.DateTimeField(auto_now_add=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="catalogzonemember",
|
||||
name="last_updated",
|
||||
field=models.DateTimeField(auto_now=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="catalogzonemember",
|
||||
name="custom_field_data",
|
||||
field=models.JSONField(
|
||||
blank=True,
|
||||
default=dict,
|
||||
encoder=utilities.json.CustomFieldJSONEncoder,
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="catalogzonemember",
|
||||
name="tags",
|
||||
field=taggit.managers.TaggableManager(
|
||||
through="extras.TaggedItem", to="extras.Tag"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="catalogzonemember",
|
||||
name="name",
|
||||
field=models.CharField(max_length=26),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="catalogzonemember",
|
||||
name="zone",
|
||||
field=models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="catalog_zone_member",
|
||||
to="netbox_dns.zone",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="catalogzonemember",
|
||||
name="catalog_zone",
|
||||
field=models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="members",
|
||||
to="netbox_dns_bridge.catalogzone",
|
||||
),
|
||||
),
|
||||
migrations.RunPython(
|
||||
copy_serials_and_link_members,
|
||||
reverse_code=reverse_migration,
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="catalogzonemember",
|
||||
name="catalog_zone",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="members",
|
||||
to="netbox_dns_bridge.catalogzone",
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="catalogzonemember",
|
||||
constraint=models.UniqueConstraint(
|
||||
fields=("name", "catalog_zone"),
|
||||
name="unique_name_per_catalog_zone",
|
||||
),
|
||||
),
|
||||
migrations.DeleteModel(
|
||||
name="IntegerKeyValueSetting",
|
||||
),
|
||||
# --- SeenTransferClients → SeenTransferClient (rename + full NetBoxModel) ---
|
||||
migrations.RenameModel(
|
||||
old_name="SeenTransferClients",
|
||||
new_name="SeenTransferClient",
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="seentransferclient",
|
||||
name="created",
|
||||
field=models.DateTimeField(auto_now_add=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="seentransferclient",
|
||||
name="last_updated",
|
||||
field=models.DateTimeField(auto_now=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="seentransferclient",
|
||||
name="custom_field_data",
|
||||
field=models.JSONField(
|
||||
blank=True,
|
||||
default=dict,
|
||||
encoder=utilities.json.CustomFieldJSONEncoder,
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="seentransferclient",
|
||||
name="tags",
|
||||
field=taggit.managers.TaggableManager(
|
||||
through="extras.TaggedItem", to="extras.Tag"
|
||||
),
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
@@ -0,0 +1,82 @@
|
||||
from django.db import models
|
||||
|
||||
# import netbox.models
|
||||
import netbox_dns.models
|
||||
from netbox.models import NetBoxModel
|
||||
|
||||
|
||||
class CatalogZone(NetBoxModel):
|
||||
view = models.OneToOneField(
|
||||
to=netbox_dns.models.View,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="catalog_zone",
|
||||
)
|
||||
soa_serial = models.IntegerField(default=1)
|
||||
soa_refresh = models.IntegerField(default=60)
|
||||
soa_retry = models.IntegerField(default=10)
|
||||
soa_expire = models.IntegerField(default=1209600)
|
||||
soa_minimum = models.IntegerField(default=0)
|
||||
|
||||
class Meta:
|
||||
ordering = ("view__name",)
|
||||
verbose_name = "Catalog Zone"
|
||||
verbose_name_plural = "Catalog Zones"
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.view.name}: {self.soa_serial}"
|
||||
|
||||
|
||||
class CatalogZoneMember(NetBoxModel):
|
||||
name = models.CharField(
|
||||
max_length=26,
|
||||
)
|
||||
|
||||
zone = models.OneToOneField(
|
||||
to=netbox_dns.models.Zone,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="catalog_zone_member",
|
||||
)
|
||||
|
||||
catalog_zone = models.ForeignKey(
|
||||
to=CatalogZone,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="members",
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ("name",)
|
||||
verbose_name = "Catalog Zone Member"
|
||||
verbose_name_plural = "Catalog Zone Members"
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["name", "catalog_zone"],
|
||||
name="unique_name_per_catalog_zone",
|
||||
),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
class SeenTransferClient(NetBoxModel):
|
||||
source_ip = models.GenericIPAddressField()
|
||||
last_seen = models.DateTimeField()
|
||||
view = models.ForeignKey(
|
||||
to=netbox_dns.models.View,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="seen_transfer_clients",
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.source_ip} ({self.view.name})"
|
||||
|
||||
class Meta:
|
||||
ordering = ("source_ip",)
|
||||
verbose_name = "Seen Transfer Client"
|
||||
verbose_name_plural = "Seen Transfer Clients"
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["source_ip", "view"],
|
||||
name="unique_ip_view_seen_client",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from netbox.plugins import PluginMenu, PluginMenuItem
|
||||
|
||||
catalog_zones_menu_item = PluginMenuItem(
|
||||
link="plugins:netbox_dns_bridge:catalogzone_list",
|
||||
link_text=_("Catalog Zones"),
|
||||
permissions=["netbox_dns_bridge.view_catalogzone"],
|
||||
)
|
||||
|
||||
catalog_zone_members_menu_item = PluginMenuItem(
|
||||
link="plugins:netbox_dns_bridge:catalogzonemember_list",
|
||||
link_text=_("Catalog Zone Members"),
|
||||
permissions=["netbox_dns_bridge.view_catalogzonemember"],
|
||||
)
|
||||
|
||||
seen_transfer_clients_menu_item = PluginMenuItem(
|
||||
link="plugins:netbox_dns_bridge:seentransferclient_list",
|
||||
link_text=_("Clients"),
|
||||
permissions=["netbox_dns_bridge.view_seentransferclient"],
|
||||
)
|
||||
|
||||
menu = PluginMenu(
|
||||
label=_("DNS Bridge"),
|
||||
groups=(
|
||||
(
|
||||
_("Catalog Zone"),
|
||||
(catalog_zones_menu_item, catalog_zone_members_menu_item),
|
||||
),
|
||||
(
|
||||
_("Notify"),
|
||||
(seen_transfer_clients_menu_item,),
|
||||
),
|
||||
),
|
||||
icon_class="mdi mdi-bridge",
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
from . import netbox_dns_zones
|
||||
@@ -0,0 +1,96 @@
|
||||
from django.db.models.signals import pre_save, post_save, post_delete
|
||||
from django.dispatch import receiver
|
||||
from django.db import transaction
|
||||
from netbox.context import current_request
|
||||
from netbox_dns.models import Zone, View
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint import catalog_zone_manager as catzm
|
||||
from netbox_dns_bridge.jobs import notify
|
||||
|
||||
|
||||
@receiver(pre_save, sender=Zone)
|
||||
def zone_pre_save(sender, instance, **kwargs):
|
||||
zone = instance
|
||||
if zone.pk:
|
||||
try:
|
||||
old = sender.objects.only("name", "soa_serial", "view_id").get(pk=zone.pk)
|
||||
zone._old_name = old.name
|
||||
zone._old_soa_serial = old.soa_serial
|
||||
zone._old_view_id = old.view_id
|
||||
except sender.DoesNotExist:
|
||||
zone._old_name = None
|
||||
zone._old_soa_serial = None
|
||||
zone._old_view_id = None
|
||||
else:
|
||||
zone._old_name = None
|
||||
zone._old_soa_serial = None
|
||||
zone._old_view_id = None
|
||||
|
||||
|
||||
@receiver(post_save, sender=Zone)
|
||||
def zone_post_save(sender, instance, created, **kwargs):
|
||||
zone = instance
|
||||
|
||||
# Quit if this is not the first signal in this session for this zone.
|
||||
try:
|
||||
request = current_request.get()
|
||||
if request is None:
|
||||
raise LookupError
|
||||
handled_zones = getattr(request, "_handled_zones", set())
|
||||
if zone.pk in handled_zones:
|
||||
return
|
||||
handled_zones.add(zone.pk)
|
||||
request._handled_zones = handled_zones
|
||||
except LookupError:
|
||||
pass
|
||||
|
||||
# Determine whether the zone's SOA serial number changed with this save.
|
||||
# A newly created zone is always considered to have a "changed" serial.
|
||||
old_soa_serial = getattr(zone, "_old_soa_serial", None)
|
||||
new_soa_serial = getattr(zone, "soa_serial", None)
|
||||
soa_serial_changed = created or (old_soa_serial != new_soa_serial)
|
||||
|
||||
# Detect whether the zone moved between views. When it does, the old
|
||||
# view's catalog zone loses a member and the new view's gains one, so
|
||||
# both serials must be incremented.
|
||||
old_view_id = getattr(zone, "_old_view_id", None)
|
||||
view_changed = (
|
||||
not created
|
||||
and old_view_id is not None
|
||||
and old_view_id != zone.view_id
|
||||
)
|
||||
|
||||
# On commit, increment soa serial and schedule notify jobs. All settings
|
||||
# gating happens inside the scheduling functions.
|
||||
def _on_commit():
|
||||
if view_changed:
|
||||
try:
|
||||
old_view = View.objects.get(pk=old_view_id)
|
||||
catzm.increment_soa_serial(old_view)
|
||||
except View.DoesNotExist:
|
||||
pass
|
||||
catzm.increment_soa_serial(zone.view)
|
||||
|
||||
if soa_serial_changed:
|
||||
notify.schedule_client_notify(zone)
|
||||
notify.schedule_ns_notify(zone)
|
||||
|
||||
transaction.on_commit(_on_commit)
|
||||
|
||||
if created:
|
||||
# If zone was created, create the catalog zone member record for this zone.
|
||||
catzm.update_member(zone)
|
||||
else:
|
||||
# Re-create the catalog zone member when the zone name or its view
|
||||
# changed. A view move leaves the member pointing at the wrong
|
||||
# catalog zone, so it must be refreshed.
|
||||
old_name = getattr(zone, "_old_name", None)
|
||||
if (old_name and zone.name != old_name) or view_changed:
|
||||
catzm.update_member(zone)
|
||||
|
||||
|
||||
@receiver(post_delete, sender=Zone)
|
||||
def zone_post_delete(sender, instance, **kwargs):
|
||||
def _on_commit():
|
||||
catzm.increment_soa_serial(instance.view)
|
||||
|
||||
transaction.on_commit(_on_commit)
|
||||
@@ -0,0 +1,78 @@
|
||||
import django_tables2 as tables
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from netbox.tables import NetBoxTable
|
||||
from netbox.tables.columns import ActionsColumn
|
||||
|
||||
from .models import CatalogZone, CatalogZoneMember, SeenTransferClient
|
||||
|
||||
|
||||
class CatalogZoneMemberTable(NetBoxTable):
|
||||
name = tables.Column(linkify=True)
|
||||
zone = tables.Column(
|
||||
accessor="zone__name",
|
||||
verbose_name=_("Zone"),
|
||||
linkify=True,
|
||||
)
|
||||
view = tables.Column(
|
||||
accessor="catalog_zone__view__name",
|
||||
verbose_name=_("View"),
|
||||
)
|
||||
|
||||
actions = ActionsColumn(actions=())
|
||||
|
||||
class Meta(NetBoxTable.Meta):
|
||||
model = CatalogZoneMember
|
||||
fields = ("name", "zone", "view")
|
||||
default_columns = ("name", "zone", "view")
|
||||
|
||||
|
||||
class CatalogZoneTable(NetBoxTable):
|
||||
view = tables.Column(
|
||||
accessor="view__name",
|
||||
verbose_name=_("View"),
|
||||
linkify=True,
|
||||
)
|
||||
soa_serial = tables.Column(verbose_name=_("SOA Serial"))
|
||||
soa_refresh = tables.Column(verbose_name=_("Refresh"))
|
||||
soa_retry = tables.Column(verbose_name=_("Retry"))
|
||||
soa_expire = tables.Column(verbose_name=_("Expire"))
|
||||
soa_minimum = tables.Column(verbose_name=_("Minimum"))
|
||||
|
||||
actions = ActionsColumn(actions=("edit", "changelog"))
|
||||
|
||||
class Meta(NetBoxTable.Meta):
|
||||
model = CatalogZone
|
||||
fields = (
|
||||
"view",
|
||||
"soa_serial",
|
||||
"soa_refresh",
|
||||
"soa_retry",
|
||||
"soa_expire",
|
||||
"soa_minimum",
|
||||
)
|
||||
default_columns = (
|
||||
"view",
|
||||
"soa_serial",
|
||||
"soa_refresh",
|
||||
"soa_retry",
|
||||
"soa_expire",
|
||||
"soa_minimum",
|
||||
)
|
||||
|
||||
|
||||
class SeenTransferClientTable(NetBoxTable):
|
||||
source_ip = tables.Column(linkify=True)
|
||||
view = tables.Column(
|
||||
accessor="view__name",
|
||||
verbose_name=_("View"),
|
||||
linkify=True,
|
||||
)
|
||||
last_seen = tables.DateTimeColumn(verbose_name=_("Last Seen"))
|
||||
|
||||
actions = ActionsColumn(actions=())
|
||||
|
||||
class Meta(NetBoxTable.Meta):
|
||||
model = SeenTransferClient
|
||||
fields = ("source_ip", "view", "last_seen")
|
||||
default_columns = ("source_ip", "view", "last_seen")
|
||||
@@ -0,0 +1,4 @@
|
||||
{% extends 'generic/object_edit.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% trans "Edit Catalog Zone" %}{% endblock %}
|
||||
@@ -0,0 +1,4 @@
|
||||
{% extends 'generic/object_list.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% trans "Catalog Zones" %}{% endblock %}
|
||||
@@ -0,0 +1,50 @@
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load plugins %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row">
|
||||
<div class="col col-md-6">
|
||||
<div class="card">
|
||||
<h5 class="card-header">{% trans "Catalog Zone SOA" %}</h5>
|
||||
<table class="table table-hover attr-table">
|
||||
<tr>
|
||||
<th scope="row">{% trans "View" %}</th>
|
||||
<td>{{ object.view|linkify }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "SOA Serial" %}</th>
|
||||
<td>{{ object.soa_serial }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Refresh" %}</th>
|
||||
<td>{{ object.soa_refresh }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Retry" %}</th>
|
||||
<td>{{ object.soa_retry }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Expire" %}</th>
|
||||
<td>{{ object.soa_expire }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Minimum" %}</th>
|
||||
<td>{{ object.soa_minimum }}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
{% include 'inc/panels/custom_fields.html' %}
|
||||
{% plugin_left_page object %}
|
||||
</div>
|
||||
<div class="col col-md-6">
|
||||
{% include 'inc/panels/tags.html' %}
|
||||
{% plugin_right_page object %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col col-md-12">
|
||||
{% plugin_full_width_page object %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,42 @@
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load plugins %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row">
|
||||
<div class="col col-md-6">
|
||||
<div class="card">
|
||||
<h5 class="card-header">{% trans "Catalog Zone Member" %}</h5>
|
||||
<table class="table table-hover attr-table">
|
||||
<tr>
|
||||
<th scope="row">{% trans "Name" %}</th>
|
||||
<td>{{ object.name }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Zone" %}</th>
|
||||
<td>{{ object.zone|linkify }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Catalog Zone" %}</th>
|
||||
<td>{{ object.catalog_zone|linkify }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "View" %}</th>
|
||||
<td>{{ object.catalog_zone.view|linkify }}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
{% include 'inc/panels/custom_fields.html' %}
|
||||
{% plugin_left_page object %}
|
||||
</div>
|
||||
<div class="col col-md-6">
|
||||
{% include 'inc/panels/tags.html' %}
|
||||
{% plugin_right_page object %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col col-md-12">
|
||||
{% plugin_full_width_page object %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,38 @@
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load plugins %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row">
|
||||
<div class="col col-md-6">
|
||||
<div class="card">
|
||||
<h5 class="card-header">{% trans "Seen Transfer Client" %}</h5>
|
||||
<table class="table table-hover attr-table">
|
||||
<tr>
|
||||
<th scope="row">{% trans "Source IP" %}</th>
|
||||
<td>{{ object.source_ip }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "View" %}</th>
|
||||
<td>{{ object.view|linkify }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">{% trans "Last Seen" %}</th>
|
||||
<td>{{ object.last_seen|date:"Y-m-d H:i:s" }}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
{% include 'inc/panels/custom_fields.html' %}
|
||||
{% plugin_left_page object %}
|
||||
</div>
|
||||
<div class="col col-md-6">
|
||||
{% include 'inc/panels/tags.html' %}
|
||||
{% plugin_right_page object %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col col-md-12">
|
||||
{% plugin_full_width_page object %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
Whitespace-only changes.
@@ -0,0 +1,258 @@
|
||||
"""Shared, non-fixture helpers for the test suite.
|
||||
|
||||
Pure DNS / TSIG / handler plumbing that does not touch the database. Database
|
||||
factories live in ``conftest.py`` as pytest fixtures.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.rdatatype
|
||||
import dns.tsig
|
||||
import dns.tsigkeyring
|
||||
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint.request_handler import (
|
||||
DNSBaseRequestHandler,
|
||||
TCPRequestHandler,
|
||||
UDPRequestHandler,
|
||||
)
|
||||
|
||||
DEFAULT_TSIG_ALGORITHM = "hmac-sha256"
|
||||
DEFAULT_TSIG_SECRET = "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE="
|
||||
|
||||
|
||||
def make_tsig_key(
|
||||
key_name: str = "testkey.",
|
||||
secret: str = DEFAULT_TSIG_SECRET,
|
||||
algorithm: str = DEFAULT_TSIG_ALGORITHM,
|
||||
) -> dns.tsig.Key:
|
||||
name = dns.name.from_text(key_name, origin=dns.name.root).canonicalize()
|
||||
return dns.tsig.Key(name=name, secret=secret, algorithm=algorithm)
|
||||
|
||||
|
||||
def build_keyring(tsig_key: dns.tsig.Key) -> dict:
|
||||
return {tsig_key.name: tsig_key}
|
||||
|
||||
|
||||
def build_tsig_view_map(key_name: str, view) -> dict:
|
||||
canon = dns.name.from_text(key_name, origin=dns.name.root).canonicalize().to_text()
|
||||
return {canon: view}
|
||||
|
||||
|
||||
def make_unsigned_query(zone_name: str, rdtype) -> bytes:
|
||||
qname = dns.name.from_text(zone_name, dns.name.root)
|
||||
msg = dns.message.make_query(qname, rdtype)
|
||||
return msg.to_wire()
|
||||
|
||||
|
||||
def make_signed_query(
|
||||
zone_name: str,
|
||||
rdtype,
|
||||
tsig_key: dns.tsig.Key,
|
||||
) -> bytes:
|
||||
qname = dns.name.from_text(zone_name, dns.name.root)
|
||||
msg = dns.message.make_query(qname, rdtype)
|
||||
msg.use_tsig(keyring={tsig_key.name: tsig_key}, keyname=tsig_key.name)
|
||||
return msg.to_wire()
|
||||
|
||||
|
||||
class FakeServer:
|
||||
"""Stand-in for socketserver's ``self.server`` carrying TSIG state."""
|
||||
|
||||
def __init__(self, keyring: dict, tsig_view_map: dict):
|
||||
self.keyring = keyring
|
||||
self.tsig_view_map = tsig_view_map
|
||||
|
||||
|
||||
class _CaptureMixin:
|
||||
"""Capture every wire message a handler emits.
|
||||
|
||||
Both ``_send_response`` (used by denials, SOA and the final AXFR message)
|
||||
and the direct ``self.request.sendall`` calls (intermediate AXFR messages)
|
||||
are recorded as raw wire bytes (the 2-byte TCP length prefix is stripped).
|
||||
"""
|
||||
|
||||
transport = "tcp"
|
||||
|
||||
def _setup_capture(self, captured: list):
|
||||
self._captured = captured
|
||||
# For TCP: AXFR intermediate sends use self.request.sendall directly.
|
||||
self.request = MagicMock()
|
||||
self.request.sendall.side_effect = lambda data: self._record_tcp_sendall(data)
|
||||
|
||||
def _record_tcp_sendall(self, data: bytes):
|
||||
# Intermediate AXFR sends are ``len(wire).to_bytes(2,"big") + wire``.
|
||||
if len(data) >= 2:
|
||||
self._captured.append(data[2:])
|
||||
else:
|
||||
self._captured.append(data)
|
||||
|
||||
def _send_response(self, data: bytes):
|
||||
self._captured.append(data)
|
||||
|
||||
|
||||
class CaptureTCPHandler(_CaptureMixin, TCPRequestHandler):
|
||||
transport = "tcp"
|
||||
|
||||
def handle(self):
|
||||
# Never invoked: tests call _handle_dns_query directly.
|
||||
return
|
||||
|
||||
|
||||
class CaptureUDPHandler(_CaptureMixin, UDPRequestHandler):
|
||||
transport = "udp"
|
||||
|
||||
def handle(self):
|
||||
return
|
||||
|
||||
|
||||
def make_capture_handler(
|
||||
handler_cls,
|
||||
keyring: dict,
|
||||
tsig_view_map: dict,
|
||||
client_ip: str = "127.0.0.1",
|
||||
):
|
||||
"""Instantiate a capture handler without running ``handle()``.
|
||||
|
||||
Returns ``(handler, captured)`` where ``captured`` is the list of wire
|
||||
messages emitted by the handler.
|
||||
"""
|
||||
captured: list = []
|
||||
server = FakeServer(keyring, tsig_view_map)
|
||||
handler = handler_cls.__new__(handler_cls)
|
||||
# Replicate DNSBaseRequestHandler.__init__ without calling super().__init__
|
||||
# (which would invoke setup()/handle()).
|
||||
handler.MAX_WIRE = 65535
|
||||
handler.RESERVED_TSIG = 300
|
||||
handler._setup_capture(captured)
|
||||
handler.client_address = (client_ip, 12345)
|
||||
handler.server = server
|
||||
return handler, captured
|
||||
|
||||
|
||||
def parse_response(wire: bytes, keyring=None, one_rr_per_rrset: bool = False) -> dns.message.Message:
|
||||
# ``make_response`` in this dnspython copies the request TSIG keyname into
|
||||
# the response even for unsigned denials, so lenient parsing is required to
|
||||
# inspect rcode/flags/answer without verifying the (absent) MAC.
|
||||
# Use ``one_rr_per_rrset=True`` for AXFR framing checks so that repeated
|
||||
# identical RRsets (e.g. opening + closing SOA) are not merged on parse.
|
||||
return dns.message.from_wire(
|
||||
wire,
|
||||
keyring=keyring or {},
|
||||
continue_on_error=True,
|
||||
ignore_trailing=True,
|
||||
one_rr_per_rrset=one_rr_per_rrset,
|
||||
)
|
||||
|
||||
|
||||
def parse_response_strict(
|
||||
wire: bytes,
|
||||
keyring: dict,
|
||||
request_mac=None,
|
||||
one_rr_per_rrset: bool = False,
|
||||
) -> dns.message.Message:
|
||||
"""Parse and fully verify TSIG. Raises on bad signature / unknown key.
|
||||
|
||||
Verifying a response TSIG requires the original request's MAC; pass it via
|
||||
``request_mac`` (obtainable from the parsed query's ``.mac`` attribute).
|
||||
"""
|
||||
return dns.message.from_wire(
|
||||
wire,
|
||||
keyring=keyring,
|
||||
request_mac=request_mac,
|
||||
ignore_trailing=True,
|
||||
one_rr_per_rrset=one_rr_per_rrset,
|
||||
)
|
||||
|
||||
|
||||
def query_mac(query_wire: bytes, keyring: dict) -> bytes:
|
||||
"""Return the request MAC of a signed query wire (for response verification)."""
|
||||
q = dns.message.from_wire(query_wire, keyring=keyring, ignore_trailing=True)
|
||||
return q.mac
|
||||
|
||||
|
||||
def tcp_exchange(wire: bytes, host: str, port: int, timeout: float = 5.0) -> bytes:
|
||||
"""Send a wire message over TCP (2-byte length framing), return response wire."""
|
||||
import socket
|
||||
|
||||
with socket.create_connection((host, port), timeout=timeout) as sock:
|
||||
sock.settimeout(timeout)
|
||||
sock.sendall(len(wire).to_bytes(2, "big") + wire)
|
||||
# Read response length then body (handle partial reads).
|
||||
length = _recv_exact(sock, 2)
|
||||
resp_len = int.from_bytes(length, "big")
|
||||
return _recv_exact(sock, resp_len)
|
||||
|
||||
|
||||
def udp_exchange(wire: bytes, host: str, port: int, timeout: float = 5.0) -> bytes:
|
||||
"""Send a wire message over UDP, return response wire."""
|
||||
import socket
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
sock.sendto(wire, (host, port))
|
||||
return sock.recv(65535)
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
def _recv_exact(sock, n: int) -> bytes:
|
||||
buf = b""
|
||||
while len(buf) < n:
|
||||
chunk = sock.recv(n - len(buf))
|
||||
if not chunk:
|
||||
raise OSError("connection closed")
|
||||
buf += chunk
|
||||
return buf
|
||||
|
||||
|
||||
def xfr_rrsets(xfr_messages):
|
||||
"""Flatten AXFR/IXFR response messages into a flat list of RRsets.
|
||||
|
||||
``dns.query.xfr`` yields ``Message`` objects (one per TCP response chunk).
|
||||
Each message's ``answer`` section contains RRsets. This helper flattens
|
||||
all answer RRsets across all messages into a single list, preserving order.
|
||||
"""
|
||||
rrsets = []
|
||||
for msg in xfr_messages:
|
||||
rrsets.extend(msg.answer)
|
||||
return rrsets
|
||||
|
||||
|
||||
def make_dns_zone(name: str, soa_serial: int = 1, soa_ttl: int = 300,
|
||||
extra=None) -> "dns.zone.Zone":
|
||||
"""Build a ``dns.zone.Zone`` directly (no database) for unit tests.
|
||||
|
||||
Always includes an SOA at the apex. ``extra`` is an optional list of
|
||||
``(relative_name, rdtype, ttl, value_text)`` tuples appended as rdatasets.
|
||||
"""
|
||||
import dns.rdata
|
||||
import dns.rdataclass
|
||||
import dns.rdataset
|
||||
import dns.rdatatype
|
||||
import dns.zone
|
||||
|
||||
origin = dns.name.from_text(name, dns.name.root)
|
||||
zone = dns.zone.Zone(origin)
|
||||
zone.rdclass = dns.rdataclass.IN
|
||||
|
||||
soa_rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN,
|
||||
dns.rdatatype.SOA,
|
||||
f"ns1.{name}. hostmaster.{name}. {soa_serial} 300 100 1209600 3600",
|
||||
)
|
||||
soa_rds = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.SOA)
|
||||
soa_rds.add(soa_rdata, soa_ttl)
|
||||
zone.replace_rdataset(origin, soa_rds)
|
||||
|
||||
for rel_name, rdtype, ttl, value_text in extra or []:
|
||||
owner = dns.name.from_text(rel_name, origin)
|
||||
rdtype_int = dns.rdatatype.from_text(rdtype)
|
||||
rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype_int, value_text)
|
||||
rds = zone.find_rdataset(owner, rdtype_int, create=True)
|
||||
rds.add(rdata, ttl)
|
||||
|
||||
return zone
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Pytest configuration and shared fixtures.
|
||||
|
||||
Tests run inside the NetBox container (``DJANGO_SETTINGS_MODULE=netbox.configuration``)
|
||||
where ``netbox`` and ``netbox_dns`` are importable. The plugin's module-level
|
||||
``SETTINGS`` bindings are patched per-test via the ``patch_settings`` fixture.
|
||||
|
||||
Heavy imports are deferred into fixtures so this conftest imports cleanly before
|
||||
the Django app registry is guaranteed ready (the root conftest calls
|
||||
``django.setup()``).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def default_view(db):
|
||||
"""Ensure NetBox DNS has a default view (required before creating zones)."""
|
||||
from netbox_dns.models import View
|
||||
|
||||
view, _ = View.objects.get_or_create(
|
||||
name="default", defaults={"default_view": True}
|
||||
)
|
||||
return view
|
||||
|
||||
|
||||
def _settings_modules():
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint import (
|
||||
request_handler,
|
||||
)
|
||||
from netbox_dns_bridge.jobs import notify
|
||||
|
||||
return [notify, request_handler]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patch_settings(monkeypatch):
|
||||
"""Patch the module-level ``SETTINGS`` dict on every consumer module."""
|
||||
mods = _settings_modules()
|
||||
originals = {mod: mod.SETTINGS for mod in mods}
|
||||
|
||||
def _apply(new_settings):
|
||||
for mod in mods:
|
||||
monkeypatch.setattr(mod, "SETTINGS", new_settings)
|
||||
return new_settings
|
||||
|
||||
yield _apply
|
||||
|
||||
for mod, original in originals.items():
|
||||
mod.SETTINGS = original
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tsig_key():
|
||||
from netbox_dns_bridge.tests._helpers import make_tsig_key
|
||||
return make_tsig_key("testkey.")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def capture_handler():
|
||||
"""Factory: build a capture handler for unit tests."""
|
||||
from netbox_dns_bridge.tests import _helpers
|
||||
|
||||
def _make(handler_cls, keyring, tsig_view_map, client_ip="127.0.0.1"):
|
||||
return _helpers.make_capture_handler(
|
||||
handler_cls, keyring, tsig_view_map, client_ip
|
||||
)
|
||||
return _make
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database factories
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def make_view(db, default_view):
|
||||
from netbox_dns.models import View
|
||||
|
||||
counter = [0]
|
||||
|
||||
def _make(name=None, default_view=False):
|
||||
counter[0] += 1
|
||||
name = name or f"test-view-{counter[0]}"
|
||||
view, _ = View.objects.get_or_create(
|
||||
name=name, defaults={"default_view": default_view}
|
||||
)
|
||||
return view
|
||||
return _make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_nameserver(db):
|
||||
from netbox_dns.models import NameServer
|
||||
|
||||
counter = [0]
|
||||
|
||||
def _make(name=None):
|
||||
counter[0] += 1
|
||||
name = name or f"ns{counter[0]}.example.test"
|
||||
ns, _ = NameServer.objects.get_or_create(name=name)
|
||||
return ns
|
||||
return _make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_zone(db, make_view, make_nameserver):
|
||||
from netbox_dns.models import Zone
|
||||
|
||||
counter = [0]
|
||||
|
||||
def _make(name=None, view=None, soa_serial=2024010101, **kwargs):
|
||||
counter[0] += 1
|
||||
name = name or f"zone-{counter[0]}.example.test"
|
||||
view = view or make_view()
|
||||
ns = make_nameserver(f"ns1.{name}")
|
||||
defaults = dict(
|
||||
view=view,
|
||||
name=name,
|
||||
soa_mname=ns,
|
||||
soa_rname=f"hostmaster.{name}",
|
||||
soa_ttl=300,
|
||||
soa_serial=soa_serial,
|
||||
soa_serial_auto=False,
|
||||
soa_refresh=300,
|
||||
soa_retry=100,
|
||||
soa_expire=1209600,
|
||||
soa_minimum=3600,
|
||||
default_ttl=300,
|
||||
status="active",
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
zone = Zone.objects.create(**defaults)
|
||||
# Ensure an active SOA record exists (netbox_dns usually creates one,
|
||||
# but be deterministic so build_dns_zone / _get_soa_serial always find it).
|
||||
from netbox_dns.models import Record
|
||||
from netbox_dns.choices import RecordStatusChoices
|
||||
if not Record.objects.filter(zone=zone, type="SOA", active=True).exists():
|
||||
fqdn = zone.name
|
||||
Record.objects.create(
|
||||
zone=zone,
|
||||
name="",
|
||||
fqdn=fqdn,
|
||||
type="SOA",
|
||||
value=(
|
||||
f"ns1.{zone.name}. hostmaster.{zone.name}. {soa_serial} "
|
||||
f"300 100 1209600 3600"
|
||||
),
|
||||
ttl=zone.soa_ttl,
|
||||
status=RecordStatusChoices.STATUS_ACTIVE,
|
||||
managed=False,
|
||||
)
|
||||
return zone
|
||||
return _make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_record(db):
|
||||
from netbox_dns.models import Record
|
||||
from netbox_dns.choices import RecordStatusChoices
|
||||
|
||||
counter = [0]
|
||||
|
||||
def _make(zone, name="", type_="A", value="127.0.0.1", ttl=None,
|
||||
status=RecordStatusChoices.STATUS_ACTIVE, managed=False):
|
||||
counter[0] += 1
|
||||
fqdn = f"{name}.{zone.name}".lstrip(".") if name else zone.name
|
||||
return Record.objects.create(
|
||||
zone=zone,
|
||||
name=name,
|
||||
fqdn=fqdn,
|
||||
type=type_,
|
||||
value=value,
|
||||
ttl=ttl if ttl is not None else zone.default_ttl,
|
||||
status=status,
|
||||
managed=managed,
|
||||
)
|
||||
return _make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catz_serial(db):
|
||||
"""Initial SOA serial value (1) for freshly created catalog zones.
|
||||
|
||||
A ``CatalogZone`` is auto-created with ``soa_serial=1`` by the zone
|
||||
post_save signal (via ``update_member``) whenever a zone is
|
||||
created. Tests compare against this initial value.
|
||||
"""
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Real-socket integration server
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def dns_server(tsig_key):
|
||||
"""Start real TCP+UDP DNS servers on 127.0.0.1:0 in background threads.
|
||||
|
||||
Usage::
|
||||
|
||||
srv = dns_server.start(views={"testkey.": view_obj})
|
||||
resp = dns.query.tcp(msg, srv["host"], port=srv["port"])
|
||||
"""
|
||||
import threading
|
||||
import dns.name
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint.dns_server import (
|
||||
TCPDNSServer,
|
||||
UDPDNSServer,
|
||||
)
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint.request_handler import (
|
||||
TCPRequestHandler,
|
||||
UDPRequestHandler,
|
||||
)
|
||||
|
||||
class _Server:
|
||||
def __init__(self, key):
|
||||
self.tsig_key = key
|
||||
self._tcp = None
|
||||
self._udp = None
|
||||
|
||||
def start(self, views):
|
||||
keyring = {self.tsig_key.name: self.tsig_key}
|
||||
tsig_view_map = {}
|
||||
for key_name, view in views.items():
|
||||
canon = (
|
||||
dns.name.from_text(key_name, origin=dns.name.root)
|
||||
.canonicalize()
|
||||
.to_text()
|
||||
)
|
||||
tsig_view_map[canon] = view
|
||||
|
||||
self._tcp = TCPDNSServer(
|
||||
("127.0.0.1", 0), TCPRequestHandler, keyring, tsig_view_map
|
||||
)
|
||||
port = self._tcp.server_address[1]
|
||||
# Bind UDP to the same port number (TCP/UDP sockets may share it).
|
||||
self._udp = UDPDNSServer(
|
||||
("127.0.0.1", port), UDPRequestHandler, keyring, tsig_view_map
|
||||
)
|
||||
threading.Thread(target=self._tcp.serve_forever, daemon=True).start()
|
||||
threading.Thread(target=self._udp.serve_forever, daemon=True).start()
|
||||
return {
|
||||
"host": "127.0.0.1",
|
||||
"port": port,
|
||||
"tsig_key": self.tsig_key,
|
||||
}
|
||||
|
||||
def shutdown(self):
|
||||
for srv in (self._tcp, self._udp):
|
||||
if srv is not None:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
server = _Server(tsig_key)
|
||||
try:
|
||||
yield server
|
||||
finally:
|
||||
server.shutdown()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Tests for plugin bootstrap: PluginConfig metadata, ready(), and settings."""
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from netbox_dns_bridge import DNSBridgeConfig, __version__
|
||||
|
||||
|
||||
class TestPluginMetadata:
|
||||
def test_version(self):
|
||||
assert __version__ == "1.5.8"
|
||||
|
||||
def test_config_name(self):
|
||||
assert DNSBridgeConfig.name == "netbox_dns_bridge"
|
||||
|
||||
def test_config_base_url(self):
|
||||
assert DNSBridgeConfig.base_url == "dns-bridge"
|
||||
|
||||
def test_config_verbose_name(self):
|
||||
assert DNSBridgeConfig.verbose_name == "Netbox DNS Bridge"
|
||||
|
||||
def test_config_is_registered(self):
|
||||
from django.apps import apps
|
||||
|
||||
app = apps.get_app_config("netbox_dns_bridge")
|
||||
assert isinstance(app, DNSBridgeConfig)
|
||||
|
||||
def test_settings_loaded_from_plugins_config(self):
|
||||
from django.apps import apps
|
||||
|
||||
app = apps.get_app_config("netbox_dns_bridge")
|
||||
assert app.settings is not None
|
||||
assert "notify_clients" in app.settings
|
||||
|
||||
|
||||
class TestReadyValidation:
|
||||
def test_ready_raises_runtime_error_when_no_config(self):
|
||||
from django.apps import apps
|
||||
|
||||
app = apps.get_app_config("netbox_dns_bridge")
|
||||
original_settings = app.settings
|
||||
app.settings = None
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="missing settings"):
|
||||
# ready() already ran during startup; call the body again
|
||||
# by re-invoking the settings check directly
|
||||
if not app.settings:
|
||||
raise RuntimeError(
|
||||
f"{app.name}: Plugin {app.verbose_name} failed to"
|
||||
" initialize due to missing settings. Terminating Netbox."
|
||||
)
|
||||
finally:
|
||||
app.settings = original_settings
|
||||
|
||||
def test_ready_imports_signals_module(self):
|
||||
# Verify signals were imported during ready() by checking they're loaded
|
||||
import netbox_dns_bridge.signals.netbox_dns_zones as signals_mod
|
||||
assert hasattr(signals_mod, "zone_post_save")
|
||||
assert hasattr(signals_mod, "zone_post_delete")
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Tests for the catalog zone manager: increment_soa_serial, create_zone, identifiers."""
|
||||
import dns.name
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import pytest
|
||||
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint import (
|
||||
catalog_zone_manager as catzm,
|
||||
)
|
||||
from netbox_dns_bridge.models import (
|
||||
CatalogZone,
|
||||
CatalogZoneMember,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestIncrementSoaSerial:
|
||||
def test_creates_setting_if_not_exists(self, make_view):
|
||||
view = make_view(name="cz-create-view")
|
||||
CatalogZone.objects.filter(view=view).delete()
|
||||
result = catzm.increment_soa_serial(view)
|
||||
assert result == 2 # created with soa_serial=1, then incremented to 2
|
||||
|
||||
def test_increments_existing(self, catz_serial, make_view):
|
||||
view = make_view(name="cz-inc-view")
|
||||
result = catzm.increment_soa_serial(view)
|
||||
assert result == catz_serial + 1
|
||||
|
||||
def test_consecutive_increments(self, catz_serial, make_view):
|
||||
view = make_view(name="cz-cons-view")
|
||||
a = catzm.increment_soa_serial(view)
|
||||
b = catzm.increment_soa_serial(view)
|
||||
assert b == a + 1
|
||||
|
||||
def test_wraps_at_max(self, catz_serial):
|
||||
# IntegerField is 32-bit signed; use max signed value and mock
|
||||
# the get_or_create to return a value at 0xFFFFFFFF
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
mock_obj = MagicMock()
|
||||
mock_obj.soa_serial = 0xFFFFFFFF
|
||||
mock_qs = MagicMock()
|
||||
mock_qs.select_for_update.return_value.get_or_create.return_value = (
|
||||
mock_obj, False
|
||||
)
|
||||
with patch(
|
||||
"netbox_dns_bridge.management.commands.dns_transfer_endpoint."
|
||||
"catalog_zone_manager.CatalogZone.objects",
|
||||
mock_qs,
|
||||
):
|
||||
result = catzm.increment_soa_serial(MagicMock())
|
||||
assert result == 1
|
||||
|
||||
def test_wrap_logs_warning(self, catz_serial, caplog):
|
||||
import logging
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
mock_obj = MagicMock()
|
||||
mock_obj.soa_serial = 0xFFFFFFFF
|
||||
mock_qs = MagicMock()
|
||||
mock_qs.select_for_update.return_value.get_or_create.return_value = (
|
||||
mock_obj, False
|
||||
)
|
||||
with patch(
|
||||
"netbox_dns_bridge.management.commands.dns_transfer_endpoint."
|
||||
"catalog_zone_manager.CatalogZone.objects",
|
||||
mock_qs,
|
||||
):
|
||||
with caplog.at_level(logging.WARNING, logger="dns-bridge"):
|
||||
catzm.increment_soa_serial(MagicMock())
|
||||
assert any("reached max" in r.message for r in caplog.records)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestGenerateMemberName:
|
||||
def test_returns_26_char_string(self):
|
||||
name = catzm._generate_member_name()
|
||||
assert len(name) == 26
|
||||
|
||||
def test_is_lowercase(self):
|
||||
name = catzm._generate_member_name()
|
||||
assert name == name.lower()
|
||||
|
||||
def test_is_base32(self):
|
||||
import string
|
||||
|
||||
name = catzm._generate_member_name()
|
||||
valid_chars = set(string.ascii_lowercase + "234567")
|
||||
assert set(name).issubset(valid_chars)
|
||||
|
||||
def test_unique_on_repeated_calls(self):
|
||||
names = {catzm._generate_member_name() for _ in range(100)}
|
||||
assert len(names) == 100
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUpdateMember:
|
||||
def test_creates_identifier_for_new_zone(self, make_zone):
|
||||
zone = make_zone(name="ident-new.test")
|
||||
# Signal already creates one; delete it to test creation
|
||||
CatalogZoneMember.objects.filter(zone=zone).delete()
|
||||
assert not CatalogZoneMember.objects.filter(zone=zone).exists()
|
||||
catzm.update_member(zone)
|
||||
assert CatalogZoneMember.objects.filter(zone=zone).exists()
|
||||
|
||||
def test_updates_existing_identifier(self, make_zone):
|
||||
zone = make_zone(name="ident-update.test")
|
||||
catzm.update_member(zone)
|
||||
old = CatalogZoneMember.objects.get(zone=zone)
|
||||
catzm.update_member(zone)
|
||||
new = CatalogZoneMember.objects.get(zone=zone)
|
||||
assert old.name != new.name
|
||||
|
||||
def test_preserves_zone_relationship_on_update(self, make_zone):
|
||||
zone = make_zone(name="ident-rel.test")
|
||||
catzm.update_member(zone)
|
||||
catzm.update_member(zone)
|
||||
assert CatalogZoneMember.objects.filter(zone=zone).count() == 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCreateZone:
|
||||
def test_creates_zone_with_soa(self, make_zone, make_view):
|
||||
view = make_view(name="cz-view")
|
||||
make_zone(name="cz-member.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-view")
|
||||
assert zone is not None
|
||||
origin = dns.name.from_text("catz", dns.name.root)
|
||||
soa = zone.get_rdataset(origin, dns.rdatatype.SOA)
|
||||
assert soa is not None
|
||||
|
||||
def test_creates_zone_with_ns(self, make_zone, make_view):
|
||||
view = make_view(name="cz-ns-view")
|
||||
make_zone(name="cz-ns-member.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-ns-view")
|
||||
origin = dns.name.from_text("catz", dns.name.root)
|
||||
ns = zone.get_rdataset(origin, dns.rdatatype.NS)
|
||||
assert ns is not None
|
||||
|
||||
def test_creates_version_record(self, make_zone, make_view):
|
||||
view = make_view(name="cz-ver-view")
|
||||
make_zone(name="cz-ver-member.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-ver-view")
|
||||
origin = dns.name.from_text("catz", dns.name.root)
|
||||
version_name = dns.name.from_text("version", origin)
|
||||
txt = zone.get_rdataset(version_name, dns.rdatatype.TXT)
|
||||
assert txt is not None
|
||||
assert str(txt[0]) == '"2"'
|
||||
|
||||
def test_creates_ptr_for_each_zone(self, make_zone, make_view):
|
||||
view = make_view(name="cz-ptr-view")
|
||||
make_zone(name="zone-a.test", view=view)
|
||||
make_zone(name="zone-b.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-ptr-view")
|
||||
ptr_count = 0
|
||||
for name, rdataset in zone.iterate_rdatasets():
|
||||
if rdataset.rdtype == dns.rdatatype.PTR:
|
||||
ptr_count += 1
|
||||
assert ptr_count == 2
|
||||
|
||||
def test_ptr_target_matches_zone_name(self, make_zone, make_view):
|
||||
view = make_view(name="cz-target-view")
|
||||
make_zone(name="target.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-target-view")
|
||||
for name, rdataset in zone.iterate_rdatasets():
|
||||
if rdataset.rdtype == dns.rdatatype.PTR:
|
||||
assert str(rdataset[0].target) == "target.test."
|
||||
|
||||
def test_soa_serial_from_db(self, make_zone, make_view, catz_serial):
|
||||
view = make_view(name="cz-serial-view")
|
||||
make_zone(name="serial.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-serial-view")
|
||||
origin = dns.name.from_text("catz", dns.name.root)
|
||||
soa = zone.get_rdataset(origin, dns.rdatatype.SOA)
|
||||
assert soa[0].serial == catz_serial
|
||||
|
||||
def test_soa_parameters_from_model(self, make_zone, make_view):
|
||||
view = make_view(name="cz-soa-params-view")
|
||||
make_zone(name="soa-params.test", view=view)
|
||||
CatalogZone.objects.filter(view=view).update(
|
||||
soa_refresh=300,
|
||||
soa_retry=100,
|
||||
soa_expire=86400,
|
||||
soa_minimum=3600,
|
||||
)
|
||||
zone = catzm.create_zone("catz", "cz-soa-params-view")
|
||||
origin = dns.name.from_text("catz", dns.name.root)
|
||||
soa = zone.get_rdataset(origin, dns.rdatatype.SOA)
|
||||
assert soa[0].refresh == 300
|
||||
assert soa[0].retry == 100
|
||||
assert soa[0].expire == 86400
|
||||
assert soa[0].minimum == 3600
|
||||
|
||||
def test_creates_identifier_on_the_fly(self, make_zone, make_view):
|
||||
view = make_view(name="cz-ident-view")
|
||||
zone_obj = make_zone(name="no-ident.test", view=view)
|
||||
# Remove the auto-created identifier to test on-the-fly creation
|
||||
CatalogZoneMember.objects.filter(zone=zone_obj).delete()
|
||||
assert not CatalogZoneMember.objects.filter(zone=zone_obj).exists()
|
||||
zone = catzm.create_zone("catz", "cz-ident-view")
|
||||
assert zone is not None
|
||||
assert CatalogZoneMember.objects.filter(zone=zone_obj).exists()
|
||||
|
||||
def test_rdclass_is_in(self, make_zone, make_view):
|
||||
view = make_view(name="cz-class-view")
|
||||
make_zone(name="class.test", view=view)
|
||||
zone = catzm.create_zone("catz", "cz-class-view")
|
||||
assert zone.rdclass == dns.rdataclass.IN
|
||||
|
||||
def test_empty_view_returns_zone_with_soa_ns_version(self, make_view):
|
||||
make_view(name="cz-empty-view")
|
||||
zone = catzm.create_zone("catz", "cz-empty-view")
|
||||
assert zone is not None
|
||||
origin = dns.name.from_text("catz", dns.name.root)
|
||||
assert zone.get_rdataset(origin, dns.rdatatype.SOA) is not None
|
||||
assert zone.get_rdataset(origin, dns.rdatatype.NS) is not None
|
||||
|
||||
def test_dnssec_policy_adds_txt(self, make_zone, make_view, monkeypatch):
|
||||
view = make_view(name="cz-dnssec-view")
|
||||
zone_obj = make_zone(name="dnssec.test", view=view)
|
||||
|
||||
monkeypatch.setattr(type(zone_obj), "dnssec_policy", property(lambda self: type("P", (), {"name": "test-policy"})()))
|
||||
|
||||
zone = catzm.create_zone("catz", "cz-dnssec-view")
|
||||
found_txt = False
|
||||
for name, rdataset in zone.iterate_rdatasets():
|
||||
if rdataset.rdtype == dns.rdatatype.TXT:
|
||||
if any("dnssec-policy-test-policy" in str(r) for r in rdataset):
|
||||
found_txt = True
|
||||
break
|
||||
assert found_txt
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Tests for the DNS server classes: DNSAddressMixin, TCPDNSServer, UDPDNSServer."""
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint.dns_server import (
|
||||
DNSAddressMixin,
|
||||
TCPDNSServer,
|
||||
UDPDNSServer,
|
||||
)
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint.request_handler import (
|
||||
TCPRequestHandler,
|
||||
UDPRequestHandler,
|
||||
)
|
||||
|
||||
|
||||
class TestDNSAddressMixin:
|
||||
def test_resolve_address_ipv4(self):
|
||||
mixin = DNSAddressMixin()
|
||||
sockaddr = mixin._resolve_address(
|
||||
("127.0.0.1", 0), socket.SOCK_STREAM, socket.IPPROTO_TCP
|
||||
)
|
||||
assert sockaddr[0] == "127.0.0.1"
|
||||
assert mixin.address_family == socket.AF_INET
|
||||
|
||||
def test_resolve_address_udp(self):
|
||||
mixin = DNSAddressMixin()
|
||||
sockaddr = mixin._resolve_address(
|
||||
("127.0.0.1", 0), socket.SOCK_DGRAM, socket.IPPROTO_UDP
|
||||
)
|
||||
assert sockaddr[0] == "127.0.0.1"
|
||||
|
||||
|
||||
class TestTCPDNSServer:
|
||||
def test_stores_keyring_and_view_map(self):
|
||||
keyring = {"key1": "val1"}
|
||||
view_map = {"key1.": "view1"}
|
||||
srv = TCPDNSServer(
|
||||
("127.0.0.1", 0), TCPRequestHandler, keyring, view_map
|
||||
)
|
||||
try:
|
||||
assert srv.keyring is keyring
|
||||
assert srv.tsig_view_map is view_map
|
||||
finally:
|
||||
srv.server_close()
|
||||
|
||||
def test_allow_reuse_address(self):
|
||||
assert TCPDNSServer.allow_reuse_address is True
|
||||
|
||||
def test_binds_to_ephemeral_port(self):
|
||||
srv = TCPDNSServer(
|
||||
("127.0.0.1", 0), TCPRequestHandler, {}, {}
|
||||
)
|
||||
try:
|
||||
port = srv.server_address[1]
|
||||
assert port > 0
|
||||
finally:
|
||||
srv.server_close()
|
||||
|
||||
|
||||
class TestUDPDNSServer:
|
||||
def test_stores_keyring_and_view_map(self):
|
||||
keyring = {"key2": "val2"}
|
||||
view_map = {"key2.": "view2"}
|
||||
srv = UDPDNSServer(
|
||||
("127.0.0.1", 0), UDPRequestHandler, keyring, view_map
|
||||
)
|
||||
try:
|
||||
assert srv.keyring is keyring
|
||||
assert srv.tsig_view_map is view_map
|
||||
finally:
|
||||
srv.server_close()
|
||||
|
||||
def test_allow_reuse_address(self):
|
||||
assert UDPDNSServer.allow_reuse_address is True
|
||||
|
||||
def test_binds_to_ephemeral_port(self):
|
||||
srv = UDPDNSServer(
|
||||
("127.0.0.1", 0), UDPRequestHandler, {}, {}
|
||||
)
|
||||
try:
|
||||
port = srv.server_address[1]
|
||||
assert port > 0
|
||||
finally:
|
||||
srv.server_close()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Tests for management commands: dns-export-zone, dns-export-zones,
|
||||
dns-transfer-endpoint."""
|
||||
import os
|
||||
import tempfile
|
||||
from io import StringIO
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestDnsExportZoneCommand:
|
||||
def test_exports_zone_file(self, make_zone, make_record):
|
||||
zone = make_zone(name="export-cmd.test")
|
||||
make_record(zone, name="www", type_="A", value="192.0.2.1")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = os.path.join(td, "zone.db")
|
||||
out = StringIO()
|
||||
call_command(
|
||||
"dns-export-zone",
|
||||
"--view", zone.view.name,
|
||||
"--zone", "export-cmd.test",
|
||||
"--file", path,
|
||||
stdout=out,
|
||||
)
|
||||
assert os.path.exists(path)
|
||||
with open(path) as f:
|
||||
content = f.read()
|
||||
assert "SOA" in content
|
||||
assert "192.0.2.1" in content # A record value
|
||||
|
||||
def test_missing_view_raises(self):
|
||||
with pytest.raises(CommandError, match="--view"):
|
||||
call_command("dns-export-zone", "--zone", "z.test", "--file", "/tmp/x")
|
||||
|
||||
def test_missing_zone_raises(self):
|
||||
with pytest.raises(CommandError, match="--zone"):
|
||||
call_command("dns-export-zone", "--view", "default", "--file", "/tmp/x")
|
||||
|
||||
def test_missing_file_raises(self):
|
||||
with pytest.raises(CommandError, match="--file"):
|
||||
call_command("dns-export-zone", "--view", "default", "--zone", "z.test")
|
||||
|
||||
def test_nonexistent_zone_raises(self, make_view):
|
||||
make_view(name="default")
|
||||
with pytest.raises(CommandError, match="Failed to export zone"):
|
||||
call_command(
|
||||
"dns-export-zone",
|
||||
"--view", "default",
|
||||
"--zone", "does-not-exist.test",
|
||||
"--file", "/tmp/x.zone",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestDnsExportZonesCommand:
|
||||
def test_exports_all_zones(self, make_zone, make_view):
|
||||
make_zone(name="batch1.test")
|
||||
make_zone(name="batch2.test")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = StringIO()
|
||||
call_command("dns-export-zones", "--path", td, stdout=out)
|
||||
output = out.getvalue()
|
||||
assert "batch1.test" in output
|
||||
assert "batch2.test" in output
|
||||
for zone_name in ("batch1.test", "batch2.test"):
|
||||
for root, dirs, files in os.walk(td):
|
||||
if zone_name in files:
|
||||
break
|
||||
else:
|
||||
pytest.fail(f"Zone file for {zone_name} not found")
|
||||
|
||||
def test_creates_view_subdirectories(self, make_zone, make_view):
|
||||
make_zone(name="subdir.test")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = StringIO()
|
||||
call_command("dns-export-zones", "--path", td, stdout=out)
|
||||
view_dirs = os.listdir(td)
|
||||
assert len(view_dirs) > 0
|
||||
|
||||
def test_missing_path_raises(self):
|
||||
with pytest.raises(CommandError, match="--path"):
|
||||
call_command("dns-export-zones")
|
||||
|
||||
def test_no_zones_warning(self):
|
||||
from netbox_dns.models import Zone
|
||||
|
||||
Zone.objects.all().delete()
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = StringIO()
|
||||
call_command("dns-export-zones", "--path", td, stdout=out)
|
||||
assert "No zones found" in out.getvalue()
|
||||
|
||||
def test_creates_path_if_not_exists(self, make_zone):
|
||||
make_zone(name="mkpath.test")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = os.path.join(td, "subdir1", "subdir2")
|
||||
out = StringIO()
|
||||
call_command("dns-export-zones", "--path", path, stdout=out)
|
||||
assert os.path.isdir(path)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestDnsTransferEndpointCommand:
|
||||
def _get_cmd_module(self):
|
||||
"""Load the dns-transfer-endpoint command module (hyphen in filename)."""
|
||||
import sys
|
||||
from django.core.management import load_command_class
|
||||
|
||||
cmd = load_command_class("netbox_dns_bridge", "dns-transfer-endpoint")
|
||||
return sys.modules[cmd.__module__]
|
||||
|
||||
def test_missing_tsig_keys_raises(self, monkeypatch):
|
||||
cmd_mod = self._get_cmd_module()
|
||||
monkeypatch.setattr(cmd_mod, "SETTINGS", {})
|
||||
with pytest.raises(RuntimeError, match="tsig_keys variable not set"):
|
||||
call_command("dns-transfer-endpoint")
|
||||
|
||||
def test_loads_tsig_keys_and_starts_servers(
|
||||
self, monkeypatch, make_view
|
||||
):
|
||||
cmd_mod = self._get_cmd_module()
|
||||
|
||||
view = make_view(name="ep-view")
|
||||
monkeypatch.setattr(cmd_mod, "SETTINGS", {
|
||||
"tsig_keys": {
|
||||
"ep-view": {
|
||||
"keyname": "epkey.",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
with patch.object(cmd_mod, "TCPDNSServer") as mock_tcp, \
|
||||
patch.object(cmd_mod, "UDPDNSServer") as mock_udp:
|
||||
mock_tcp.return_value.serve_forever = MagicMock()
|
||||
mock_udp.return_value.serve_forever = MagicMock()
|
||||
call_command("dns-transfer-endpoint", "--port", "0", "--address", "127.0.0.1")
|
||||
assert mock_tcp.called
|
||||
assert mock_udp.called
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Tests for plugin models: constraints, __str__, cascade behaviours."""
|
||||
import pytest
|
||||
|
||||
from netbox_dns_bridge.models import (
|
||||
CatalogZone,
|
||||
CatalogZoneMember,
|
||||
SeenTransferClient,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZone:
|
||||
def test_str_representation(self, make_view):
|
||||
view = make_view(name="cz-str-view")
|
||||
cz = CatalogZone.objects.create(view=view, soa_serial=42)
|
||||
assert str(cz) == "cz-str-view: 42"
|
||||
|
||||
def test_default_soa_serial(self, make_view):
|
||||
view = make_view(name="cz-default-view")
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
assert cz.soa_serial == 1
|
||||
|
||||
def test_default_soa_parameters(self, make_view):
|
||||
view = make_view(name="cz-soa-default-view")
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
assert cz.soa_refresh == 60
|
||||
assert cz.soa_retry == 10
|
||||
assert cz.soa_expire == 1209600
|
||||
assert cz.soa_minimum == 0
|
||||
|
||||
def test_custom_soa_parameters(self, make_view):
|
||||
view = make_view(name="cz-soa-custom-view")
|
||||
cz = CatalogZone.objects.create(
|
||||
view=view,
|
||||
soa_refresh=300,
|
||||
soa_retry=100,
|
||||
soa_expire=86400,
|
||||
soa_minimum=3600,
|
||||
)
|
||||
assert cz.soa_refresh == 300
|
||||
assert cz.soa_retry == 100
|
||||
assert cz.soa_expire == 86400
|
||||
assert cz.soa_minimum == 3600
|
||||
|
||||
def test_is_full_netbox_model(self, make_view):
|
||||
view = make_view(name="cz-netbox-model-view")
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
assert cz.created is not None
|
||||
assert cz.last_updated is not None
|
||||
assert cz.custom_field_data == {}
|
||||
assert hasattr(cz, "tags")
|
||||
assert cz.get_absolute_url() == f"/plugins/dns-bridge/catalog-zones/{cz.pk}/"
|
||||
|
||||
def test_one_to_one_relationship(self, make_view):
|
||||
view = make_view(name="cz-oto-view")
|
||||
cz = CatalogZone.objects.create(view=view, soa_serial=7)
|
||||
assert view.catalog_zone == cz
|
||||
|
||||
def test_create_and_retrieve(self, make_view):
|
||||
view = make_view(name="cz-retrieve-view")
|
||||
CatalogZone.objects.create(view=view, soa_serial=99)
|
||||
cz = CatalogZone.objects.get(view=view)
|
||||
assert cz.soa_serial == 99
|
||||
|
||||
def test_ordering_by_view_name(self, make_view):
|
||||
v1 = make_view(name="z-view")
|
||||
v2 = make_view(name="a-view")
|
||||
v3 = make_view(name="m-view")
|
||||
CatalogZone.objects.create(view=v1, soa_serial=1)
|
||||
CatalogZone.objects.create(view=v2, soa_serial=2)
|
||||
CatalogZone.objects.create(view=v3, soa_serial=3)
|
||||
names = list(
|
||||
CatalogZone.objects.values_list("view__name", flat=True)
|
||||
)
|
||||
assert names == ["a-view", "m-view", "z-view"]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZoneMember:
|
||||
def test_str_representation(self, make_zone):
|
||||
zone = make_zone(name="str.test")
|
||||
m = CatalogZoneMember.objects.get(zone=zone)
|
||||
assert str(m) == m.name
|
||||
|
||||
def test_unique_name_per_catalog_zone(self, make_zone, make_view):
|
||||
view = make_view(name="shared-view")
|
||||
zone1 = make_zone(name="uniq1.test", view=view)
|
||||
zone2 = make_zone(name="uniq2.test", view=view)
|
||||
|
||||
ident1 = CatalogZoneMember.objects.get(zone=zone1)
|
||||
ident1.name = "shared-name"
|
||||
ident1.save()
|
||||
|
||||
ident2 = CatalogZoneMember.objects.get(zone=zone2)
|
||||
from django.db import IntegrityError
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
ident2.name = "shared-name"
|
||||
ident2.save()
|
||||
|
||||
def test_same_name_allowed_in_different_catalog_zones(self, make_zone, make_view):
|
||||
view1 = make_view(name="view-a")
|
||||
view2 = make_view(name="view-b")
|
||||
zone1 = make_zone(name="diff1.test", view=view1)
|
||||
zone2 = make_zone(name="diff2.test", view=view2)
|
||||
|
||||
ident1 = CatalogZoneMember.objects.get(zone=zone1)
|
||||
ident1.name = "shared-name"
|
||||
ident1.save()
|
||||
|
||||
ident2 = CatalogZoneMember.objects.get(zone=zone2)
|
||||
ident2.name = "shared-name"
|
||||
ident2.save()
|
||||
|
||||
def test_cascade_delete_when_zone_deleted(self, make_zone):
|
||||
zone = make_zone(name="cascade.test")
|
||||
m = CatalogZoneMember.objects.get(zone=zone)
|
||||
assert CatalogZoneMember.objects.filter(pk=m.pk).exists()
|
||||
zone.delete()
|
||||
assert not CatalogZoneMember.objects.filter(pk=m.pk).exists()
|
||||
|
||||
def test_one_to_one_relationship(self, make_zone):
|
||||
zone = make_zone(name="oto.test")
|
||||
m = CatalogZoneMember.objects.get(zone=zone)
|
||||
assert zone.catalog_zone_member == m
|
||||
|
||||
def test_ordering_by_name(self, make_zone, make_view):
|
||||
view = make_view(name="ord-view")
|
||||
z1 = make_zone(name="z1.test", view=view)
|
||||
z2 = make_zone(name="z2.test", view=view)
|
||||
z3 = make_zone(name="z3.test", view=view)
|
||||
CatalogZoneMember.objects.filter(zone=z3).update(name="gamma")
|
||||
CatalogZoneMember.objects.filter(zone=z1).update(name="alpha")
|
||||
CatalogZoneMember.objects.filter(zone=z2).update(name="beta")
|
||||
names = list(
|
||||
CatalogZoneMember.objects.filter(
|
||||
zone__in=[z1, z2, z3]
|
||||
).values_list("name", flat=True)
|
||||
)
|
||||
assert names == ["alpha", "beta", "gamma"]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSeenTransferClient:
|
||||
def test_str_representation(self, make_view):
|
||||
view = make_view(name="str-view")
|
||||
client = SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1",
|
||||
view=view,
|
||||
last_seen="2026-01-01T00:00:00Z",
|
||||
)
|
||||
assert str(client) == f"192.0.2.1 ({view.name})"
|
||||
|
||||
def test_unique_ip_view_constraint(self, make_view):
|
||||
from django.db import IntegrityError
|
||||
|
||||
view = make_view(name="uniq-view")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="10.0.0.1",
|
||||
view=view,
|
||||
last_seen="2026-01-01T00:00:00Z",
|
||||
)
|
||||
with pytest.raises(IntegrityError):
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="10.0.0.1",
|
||||
view=view,
|
||||
last_seen="2026-01-02T00:00:00Z",
|
||||
)
|
||||
|
||||
def test_same_ip_different_views_allowed(self, make_view):
|
||||
v1 = make_view(name="v1")
|
||||
v2 = make_view(name="v2")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="10.0.0.5", view=v1, last_seen="2026-01-01T00:00:00Z"
|
||||
)
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="10.0.0.5", view=v2, last_seen="2026-01-01T00:00:00Z"
|
||||
)
|
||||
assert SeenTransferClient.objects.filter(source_ip="10.0.0.5").count() == 2
|
||||
|
||||
def test_protect_on_view_delete(self, make_view):
|
||||
from django.db.models import ProtectedError
|
||||
|
||||
view = make_view(name="protected-view")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="10.0.0.9",
|
||||
view=view,
|
||||
last_seen="2026-01-01T00:00:00Z",
|
||||
)
|
||||
with pytest.raises(ProtectedError):
|
||||
view.delete()
|
||||
|
||||
def test_ordering_by_source_ip(self, make_view):
|
||||
from django.utils import timezone
|
||||
|
||||
v = make_view(name="ord-view")
|
||||
now = timezone.now()
|
||||
for ip in ["10.0.0.3", "10.0.0.1", "10.0.0.2"]:
|
||||
SeenTransferClient.objects.create(source_ip=ip, view=v, last_seen=now)
|
||||
ips = list(SeenTransferClient.objects.values_list("source_ip", flat=True))
|
||||
assert ips == ["10.0.0.1", "10.0.0.2", "10.0.0.3"]
|
||||
|
||||
def test_is_full_netbox_model(self, make_view):
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="stc-netbox-model-view")
|
||||
c = SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1", view=view, last_seen=timezone.now()
|
||||
)
|
||||
assert c.created is not None
|
||||
assert c.last_updated is not None
|
||||
assert c.custom_field_data == {}
|
||||
assert hasattr(c, "tags")
|
||||
assert c.get_absolute_url() == f"/plugins/dns-bridge/seen-transfer-clients/{c.pk}/"
|
||||
@@ -0,0 +1,426 @@
|
||||
"""Tests for notify: _load_tsig_key, _get_soa_serial, _resolve_zone_nameserver_ips,
|
||||
schedule_client_notify, schedule_ns_notify, schedule_catalog_zone_notify, and job classes."""
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import dns.name
|
||||
import dns.rdatatype
|
||||
import dns.tsig
|
||||
import pytest
|
||||
|
||||
import netbox_dns_bridge.jobs.notify as nh
|
||||
|
||||
|
||||
class TestLoadTsigKey:
|
||||
def _patch_settings(self, monkeypatch, tsig_keys):
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"tsig_keys": tsig_keys})
|
||||
|
||||
def test_valid_config(self, monkeypatch):
|
||||
self._patch_settings(monkeypatch, {
|
||||
"myview": {
|
||||
"keyname": "testkey.",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
})
|
||||
key = nh._load_tsig_key("myview")
|
||||
assert isinstance(key, dns.tsig.Key)
|
||||
assert key.name == dns.name.from_text("testkey.", dns.name.root).canonicalize()
|
||||
|
||||
def test_missing_view_raises(self, monkeypatch):
|
||||
self._patch_settings(monkeypatch, {})
|
||||
with pytest.raises(RuntimeError, match="No TSIG key configured"):
|
||||
nh._load_tsig_key("nope")
|
||||
|
||||
def test_missing_algorithm_raises(self, monkeypatch):
|
||||
self._patch_settings(monkeypatch, {
|
||||
"v": {"keyname": "k.", "secret": "s"}
|
||||
})
|
||||
with pytest.raises(RuntimeError, match="Missing 'algorithm'"):
|
||||
nh._load_tsig_key("v")
|
||||
|
||||
def test_missing_keyname_raises(self, monkeypatch):
|
||||
self._patch_settings(monkeypatch, {
|
||||
"v": {"secret": "s", "algorithm": "hmac-sha256"}
|
||||
})
|
||||
with pytest.raises(RuntimeError, match="Incomplete TSIG key"):
|
||||
nh._load_tsig_key("v")
|
||||
|
||||
def test_missing_secret_raises(self, monkeypatch):
|
||||
self._patch_settings(monkeypatch, {
|
||||
"v": {"keyname": "k.", "algorithm": "hmac-sha256"}
|
||||
})
|
||||
with pytest.raises(RuntimeError, match="Incomplete TSIG key"):
|
||||
nh._load_tsig_key("v")
|
||||
|
||||
def test_relative_key_name_gets_root(self, monkeypatch):
|
||||
self._patch_settings(monkeypatch, {
|
||||
"v": {
|
||||
"keyname": "relkey",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
})
|
||||
key = nh._load_tsig_key("v")
|
||||
assert key.name.is_absolute()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestGetSoaSerial:
|
||||
def test_valid_soa(self, make_zone):
|
||||
zone = make_zone(name="soa-valid.test", soa_serial=12345)
|
||||
result = nh._get_soa_serial(zone)
|
||||
assert result == 12345
|
||||
|
||||
def test_no_soa_record_returns_none(self, make_zone):
|
||||
from netbox_dns.models import Record
|
||||
|
||||
zone = make_zone(name="soa-none.test")
|
||||
Record.objects.filter(zone=zone, type="SOA").delete()
|
||||
result = nh._get_soa_serial(zone)
|
||||
assert result is None
|
||||
|
||||
def test_inactive_soa_returns_none(self, make_zone):
|
||||
from netbox_dns.models import Record
|
||||
from netbox_dns.choices import RecordStatusChoices
|
||||
|
||||
zone = make_zone(name="soa-inactive.test")
|
||||
Record.objects.filter(zone=zone, type="SOA").update(
|
||||
status=RecordStatusChoices.STATUS_INACTIVE
|
||||
)
|
||||
result = nh._get_soa_serial(zone)
|
||||
assert result is None
|
||||
|
||||
def test_malformed_serial_returns_none(self, make_zone):
|
||||
from netbox_dns.models import Record
|
||||
|
||||
zone = make_zone(name="soa-bad.test")
|
||||
Record.objects.filter(zone=zone, type="SOA").update(
|
||||
value="ns1.test. hostmaster.test. NOTANUMBER 300 100 1209600 3600"
|
||||
)
|
||||
result = nh._get_soa_serial(zone)
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestResolveZoneNameserverIps:
|
||||
def test_resolves_a_records(self, make_zone, make_record, make_nameserver):
|
||||
zone = make_zone(name="nsresolv.test")
|
||||
ns = make_nameserver("ns1.nsresolv.test")
|
||||
zone.nameservers.add(ns)
|
||||
make_record(zone, name="ns1", type_="A", value="192.0.2.1")
|
||||
ips = nh._resolve_zone_nameserver_ips(zone)
|
||||
assert "192.0.2.1" in ips
|
||||
|
||||
def test_resolves_aaaa_records(self, make_zone, make_record, make_nameserver):
|
||||
zone = make_zone(name="nsresolv6.test")
|
||||
ns = make_nameserver("ns1.nsresolv6.test")
|
||||
zone.nameservers.add(ns)
|
||||
make_record(zone, name="ns1", type_="AAAA", value="2001:db8::1")
|
||||
ips = nh._resolve_zone_nameserver_ips(zone)
|
||||
assert "2001:db8::1" in ips
|
||||
|
||||
def test_deduplicates_ips(self, make_zone, make_record, make_nameserver):
|
||||
zone = make_zone(name="nsdedup.test")
|
||||
ns = make_nameserver("ns1.nsdedup.test")
|
||||
zone.nameservers.add(ns)
|
||||
make_record(zone, name="ns1", type_="A", value="192.0.2.1")
|
||||
make_record(zone, name="ns1", type_="A", value="192.0.2.2")
|
||||
ips = nh._resolve_zone_nameserver_ips(zone)
|
||||
assert "192.0.2.1" in ips
|
||||
assert "192.0.2.2" in ips
|
||||
assert len(ips) == 2
|
||||
|
||||
def test_no_nameservers_returns_empty(self, make_zone):
|
||||
zone = make_zone(name="nsnone.test")
|
||||
ips = nh._resolve_zone_nameserver_ips(zone)
|
||||
assert ips == []
|
||||
|
||||
def test_multiple_nameservers(self, make_zone, make_record, make_nameserver):
|
||||
zone = make_zone(name="nsmulti.test")
|
||||
ns1 = make_nameserver("ns1.nsmulti.test")
|
||||
ns2 = make_nameserver("ns2.nsmulti.test")
|
||||
zone.nameservers.add(ns1, ns2)
|
||||
make_record(zone, name="ns1", type_="A", value="192.0.2.1")
|
||||
make_record(zone, name="ns2", type_="A", value="192.0.2.2")
|
||||
ips = nh._resolve_zone_nameserver_ips(zone)
|
||||
assert set(ips) == {"192.0.2.1", "192.0.2.2"}
|
||||
|
||||
def test_trailing_dot_resilience(self, make_zone, make_record, make_nameserver):
|
||||
zone = make_zone(name="nstrail.test")
|
||||
ns = make_nameserver("ns1.nstrail.test")
|
||||
zone.nameservers.add(ns)
|
||||
make_record(zone, name="ns1", type_="A", value="192.0.2.5")
|
||||
ips = nh._resolve_zone_nameserver_ips(zone)
|
||||
assert "192.0.2.5" in ips
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestScheduleClientNotify:
|
||||
def test_enqueues_job_when_enabled(self, make_zone, monkeypatch):
|
||||
zone = make_zone(name="sched-client.test", soa_serial=77)
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_clients": True})
|
||||
with patch.object(nh.SendClientNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_client_notify(zone)
|
||||
mock_enq.assert_called_once_with(
|
||||
zone_name="sched-client.test",
|
||||
view_name=zone.view.name,
|
||||
soa_serial=77,
|
||||
)
|
||||
|
||||
def test_does_not_enqueue_when_no_soa(self, make_zone, monkeypatch):
|
||||
from netbox_dns.models import Record
|
||||
|
||||
zone = make_zone(name="sched-client-nosoa.test")
|
||||
Record.objects.filter(zone=zone, type="SOA").delete()
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_clients": True})
|
||||
with patch.object(nh.SendClientNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_client_notify(zone)
|
||||
mock_enq.assert_not_called()
|
||||
|
||||
def test_does_not_enqueue_when_notify_clients_disabled(self, make_zone, monkeypatch):
|
||||
zone = make_zone(name="sched-client-disabled.test", soa_serial=77)
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_clients": False})
|
||||
with patch.object(nh.SendClientNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_client_notify(zone)
|
||||
mock_enq.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestScheduleNsNotify:
|
||||
def test_enqueues_job_when_enabled(self, make_zone, monkeypatch):
|
||||
zone = make_zone(name="sched-ns.test", soa_serial=88)
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_ns_all_zones": True})
|
||||
with patch.object(nh.SendNSNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_ns_notify(zone)
|
||||
mock_enq.assert_called_once_with(
|
||||
zone_id=zone.pk,
|
||||
zone_name="sched-ns.test",
|
||||
view_name=zone.view.name,
|
||||
soa_serial=88,
|
||||
)
|
||||
|
||||
def test_does_not_enqueue_when_no_soa(self, make_zone, monkeypatch):
|
||||
from netbox_dns.models import Record
|
||||
|
||||
zone = make_zone(name="sched-ns-nosoa.test")
|
||||
Record.objects.filter(zone=zone, type="SOA").delete()
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_ns_all_zones": True})
|
||||
with patch.object(nh.SendNSNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_ns_notify(zone)
|
||||
mock_enq.assert_not_called()
|
||||
|
||||
def test_does_not_enqueue_when_ns_notify_disabled(self, make_zone, monkeypatch):
|
||||
zone = make_zone(name="sched-ns-disabled.test", soa_serial=88)
|
||||
monkeypatch.setattr(nh, "SETTINGS", {})
|
||||
with patch.object(nh.SendNSNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_ns_notify(zone)
|
||||
mock_enq.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestScheduleCatalogZoneNotify:
|
||||
def test_enqueues_two_jobs_when_enabled(self, make_view, monkeypatch):
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
|
||||
view = make_view(name="catz-notify-view")
|
||||
CatalogZone.objects.create(view=view, soa_serial=42)
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_clients": True})
|
||||
with patch.object(nh.SendClientNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_catalog_zone_notify(view)
|
||||
assert mock_enq.call_count == 2
|
||||
mock_enq.assert_any_call(
|
||||
zone_name="catz",
|
||||
soa_serial=42,
|
||||
view_name="catz-notify-view",
|
||||
soa_refresh=60,
|
||||
soa_retry=10,
|
||||
soa_expire=1209600,
|
||||
soa_minimum=0,
|
||||
)
|
||||
mock_enq.assert_any_call(
|
||||
zone_name="catz-notify-view.catz",
|
||||
soa_serial=42,
|
||||
view_name="catz-notify-view",
|
||||
soa_refresh=60,
|
||||
soa_retry=10,
|
||||
soa_expire=1209600,
|
||||
soa_minimum=0,
|
||||
)
|
||||
|
||||
def test_does_not_enqueue_when_notify_clients_disabled(self, make_view, monkeypatch):
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
|
||||
view = make_view(name="catz-notify-disabled")
|
||||
CatalogZone.objects.create(view=view, soa_serial=42)
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_clients": False})
|
||||
with patch.object(nh.SendClientNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_catalog_zone_notify(view)
|
||||
mock_enq.assert_not_called()
|
||||
|
||||
def test_does_not_enqueue_when_no_catalog_zone(self, make_view, monkeypatch):
|
||||
view = make_view(name="catz-notify-no-cz")
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_clients": True})
|
||||
with patch.object(nh.SendClientNotify, "enqueue") as mock_enq:
|
||||
nh.schedule_catalog_zone_notify(view)
|
||||
mock_enq.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSendClientNotifyRun:
|
||||
def test_sends_single_notify_to_seen_clients(self, make_zone, make_view, monkeypatch):
|
||||
import netbox_dns_bridge.jobs.notify as nh
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="notify-run-view")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.99", view=view, last_seen=timezone.now()
|
||||
)
|
||||
|
||||
monkeypatch.setattr(nh, "SETTINGS", {
|
||||
"tsig_keys": {
|
||||
"notify-run-view": {
|
||||
"keyname": "nk.",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
},
|
||||
"notify_over_tcp": False,
|
||||
"notify_client_port": 53,
|
||||
"notify_client_alive_threshold_hours": 24,
|
||||
})
|
||||
|
||||
job = MagicMock()
|
||||
with patch("dns.query.udp") as mock_udp:
|
||||
nh.SendClientNotify.run(job,
|
||||
zone_name="z.test", soa_serial=10, view_name="notify-run-view")
|
||||
assert mock_udp.call_count == 1
|
||||
|
||||
def test_sends_notify_without_catalog_zone(self, monkeypatch, make_view):
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="no-catz-view")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1", view=view, last_seen=timezone.now()
|
||||
)
|
||||
|
||||
monkeypatch.setattr(nh, "SETTINGS", {
|
||||
"tsig_keys": {
|
||||
"no-catz-view": {
|
||||
"keyname": "nk.",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
},
|
||||
"notify_over_tcp": False,
|
||||
"notify_client_port": 53,
|
||||
"notify_client_alive_threshold_hours": 24,
|
||||
})
|
||||
|
||||
job = MagicMock()
|
||||
with patch("dns.query.udp") as mock_udp:
|
||||
nh.SendClientNotify.run(job,
|
||||
zone_name="z.test", soa_serial=1, view_name="no-catz-view")
|
||||
assert mock_udp.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSendNSNotifyRun:
|
||||
def test_sends_notify_to_nameserver_ips(self, make_zone, make_record, make_nameserver, monkeypatch):
|
||||
import netbox_dns_bridge.jobs.notify as nh
|
||||
|
||||
zone = make_zone(name="ns-notify-run.test", soa_serial=55)
|
||||
ns = make_nameserver("ns1.ns-notify-run.test")
|
||||
zone.nameservers.add(ns)
|
||||
make_record(zone, name="ns1", type_="A", value="192.0.2.200")
|
||||
|
||||
monkeypatch.setattr(nh, "SETTINGS", {
|
||||
"tsig_keys": {
|
||||
zone.view.name: {
|
||||
"keyname": "nk.",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
},
|
||||
"notify_over_tcp": False,
|
||||
"notify_ns_port": 53,
|
||||
})
|
||||
|
||||
job = MagicMock()
|
||||
with patch("dns.query.udp") as mock_udp:
|
||||
nh.SendNSNotify.run(job,
|
||||
zone_id=zone.pk, zone_name="ns-notify-run.test",
|
||||
view_name=zone.view.name, soa_serial=55)
|
||||
mock_udp.assert_called_once()
|
||||
|
||||
def test_skips_when_zone_deleted(self, monkeypatch):
|
||||
job = MagicMock()
|
||||
with patch("dns.query.udp") as mock_udp:
|
||||
nh.SendNSNotify.run(job,
|
||||
zone_id=999999, zone_name="gone.test",
|
||||
view_name="v", soa_serial=1)
|
||||
mock_udp.assert_not_called()
|
||||
|
||||
def test_skips_when_no_nameservers(self, make_zone, monkeypatch):
|
||||
zone = make_zone(name="ns-notify-empty.test")
|
||||
|
||||
monkeypatch.setattr(nh, "SETTINGS", {
|
||||
"tsig_keys": {
|
||||
zone.view.name: {
|
||||
"keyname": "nk.",
|
||||
"secret": "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=",
|
||||
"algorithm": "hmac-sha256",
|
||||
}
|
||||
},
|
||||
"notify_over_tcp": False,
|
||||
"notify_ns_port": 53,
|
||||
})
|
||||
|
||||
job = MagicMock()
|
||||
with patch("dns.query.udp") as mock_udp:
|
||||
nh.SendNSNotify.run(job,
|
||||
zone_id=zone.pk, zone_name="ns-notify-empty.test",
|
||||
view_name=zone.view.name, soa_serial=1)
|
||||
mock_udp.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestNotifyNsEnabled:
|
||||
def test_enabled_by_all_zones_flag(self, make_zone, monkeypatch):
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_ns_all_zones": True})
|
||||
from netbox_dns_bridge.jobs.notify import _notify_ns_enabled
|
||||
|
||||
zone = make_zone(name="nsflag.test")
|
||||
assert _notify_ns_enabled(zone) is True
|
||||
|
||||
def test_disabled_by_default(self, make_zone, monkeypatch):
|
||||
monkeypatch.setattr(nh, "SETTINGS", {})
|
||||
from netbox_dns_bridge.jobs.notify import _notify_ns_enabled
|
||||
|
||||
zone = make_zone(name="nsdisabled.test")
|
||||
assert _notify_ns_enabled(zone) is False
|
||||
|
||||
def test_enabled_by_custom_field(self, make_zone, monkeypatch):
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_ns_custom_field_name": "enable_notify"})
|
||||
from netbox_dns_bridge.jobs.notify import _notify_ns_enabled
|
||||
|
||||
zone = make_zone(name="nscf.test")
|
||||
zone.custom_field_data = {"enable_notify": True}
|
||||
assert _notify_ns_enabled(zone) is True
|
||||
|
||||
def test_disabled_when_custom_field_false(self, make_zone, monkeypatch):
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_ns_custom_field_name": "enable_notify"})
|
||||
from netbox_dns_bridge.jobs.notify import _notify_ns_enabled
|
||||
|
||||
zone = make_zone(name="nscf-false.test")
|
||||
zone.custom_field_data = {"enable_notify": False}
|
||||
assert _notify_ns_enabled(zone) is False
|
||||
|
||||
def test_disabled_when_custom_field_missing(self, make_zone, monkeypatch):
|
||||
monkeypatch.setattr(nh, "SETTINGS", {"notify_ns_custom_field_name": "enable_notify"})
|
||||
from netbox_dns_bridge.jobs.notify import _notify_ns_enabled
|
||||
|
||||
zone = make_zone(name="nscf-missing.test")
|
||||
zone.custom_field_data = {}
|
||||
assert _notify_ns_enabled(zone) is False
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Real-socket integration tests for the DNS transfer endpoint.
|
||||
|
||||
Starts actual TCP+UDP servers on 127.0.0.1:0 and sends real DNS queries via
|
||||
raw sockets against NetBox DNS zones in the test database. Raw sockets are used
|
||||
so response TSIG can be verified explicitly with the request MAC.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dns.flags
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.query
|
||||
import dns.rcode
|
||||
import dns.rdatatype
|
||||
import pytest
|
||||
|
||||
from netbox_dns_bridge.tests._helpers import (
|
||||
make_signed_query,
|
||||
make_unsigned_query,
|
||||
parse_response,
|
||||
parse_response_strict,
|
||||
query_mac,
|
||||
tcp_exchange,
|
||||
udp_exchange,
|
||||
build_keyring,
|
||||
xfr_rrsets,
|
||||
)
|
||||
|
||||
|
||||
pytestmark = pytest.mark.django_db(transaction=True)
|
||||
|
||||
|
||||
def _signed_soa(zone_name, tsig_key):
|
||||
return make_signed_query(zone_name, dns.rdatatype.SOA, tsig_key)
|
||||
|
||||
|
||||
def _signed_axfr(zone_name, tsig_key):
|
||||
return make_signed_query(zone_name, dns.rdatatype.AXFR, tsig_key)
|
||||
|
||||
|
||||
class TestSOAIntegration:
|
||||
def test_soa_over_tcp(self, dns_server, make_zone, make_view, tsig_key):
|
||||
view = make_view()
|
||||
make_zone(name="int-soa.test", view=view, soa_serial=555)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
keyring = build_keyring(tsig_key)
|
||||
|
||||
wire = _signed_soa("int-soa.test", tsig_key)
|
||||
resp_wire = tcp_exchange(wire, srv["host"], srv["port"])
|
||||
resp = parse_response_strict(resp_wire, keyring, query_mac(wire, keyring))
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
assert resp.flags & dns.flags.AA
|
||||
assert resp.answer[0].rdtype == dns.rdatatype.SOA
|
||||
assert resp.answer[0][0].serial == 555
|
||||
assert resp.had_tsig
|
||||
|
||||
def test_soa_over_udp(self, dns_server, make_zone, make_view, tsig_key):
|
||||
view = make_view()
|
||||
make_zone(name="int-udp.test", view=view, soa_serial=7)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
keyring = build_keyring(tsig_key)
|
||||
|
||||
wire = _signed_soa("int-udp.test", tsig_key)
|
||||
resp_wire = udp_exchange(wire, srv["host"], srv["port"])
|
||||
resp = parse_response_strict(resp_wire, keyring, query_mac(wire, keyring))
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
assert resp.answer[0][0].serial == 7
|
||||
|
||||
def test_unsigned_query_refused(self, dns_server, make_zone, make_view, tsig_key):
|
||||
view = make_view()
|
||||
make_zone(name="int-nosig.test", view=view)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
resp_wire = tcp_exchange(
|
||||
make_unsigned_query("int-nosig.test", dns.rdatatype.SOA),
|
||||
srv["host"], srv["port"],
|
||||
)
|
||||
resp = parse_response(resp_wire)
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
|
||||
class TestAXFRIntegration:
|
||||
def test_axfr_over_tcp(self, dns_server, make_zone, make_view, make_record, tsig_key):
|
||||
view = make_view()
|
||||
zone = make_zone(name="int-axfr.test", view=view, soa_serial=123)
|
||||
make_record(zone, name="www", type_="A", value="192.0.2.10")
|
||||
make_record(zone, name="api", type_="A", value="192.0.2.11")
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
records = xfr_rrsets(
|
||||
dns.query.xfr(
|
||||
srv["host"], "int-axfr.test", port=srv["port"],
|
||||
keyring={tsig_key.name: tsig_key}, keyname=tsig_key.name,
|
||||
lifetime=5, relativize=False,
|
||||
)
|
||||
)
|
||||
names = {r.name.to_text() for r in records}
|
||||
assert "int-axfr.test." in names
|
||||
assert "www.int-axfr.test." in names
|
||||
assert "api.int-axfr.test." in names
|
||||
# AXFR must begin and end with SOA.
|
||||
assert records[0].rdtype == dns.rdatatype.SOA
|
||||
assert records[-1].rdtype == dns.rdatatype.SOA
|
||||
assert records[0][0].serial == 123
|
||||
|
||||
def test_axfr_over_udp_refused(self, dns_server, make_zone, make_view, tsig_key):
|
||||
view = make_view()
|
||||
make_zone(name="int-axfr-udp.test", view=view)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
resp_wire = udp_exchange(
|
||||
_signed_axfr("int-axfr-udp.test", tsig_key), srv["host"], srv["port"]
|
||||
)
|
||||
resp = parse_response(resp_wire)
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_axfr_unknown_zone_refused(self, dns_server, make_view, tsig_key):
|
||||
view = make_view()
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
resp_wire = tcp_exchange(
|
||||
_signed_axfr("does-not-exist.test", tsig_key), srv["host"], srv["port"]
|
||||
)
|
||||
resp = parse_response(resp_wire)
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
|
||||
class TestCatzIntegration:
|
||||
def test_catz_axfr_contains_member_ptr(self, dns_server, make_zone, make_view, tsig_key):
|
||||
view = make_view()
|
||||
make_zone(name="member-a.test", view=view)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
records = xfr_rrsets(
|
||||
dns.query.xfr(
|
||||
srv["host"], "catz", port=srv["port"],
|
||||
keyring={tsig_key.name: tsig_key}, keyname=tsig_key.name,
|
||||
lifetime=5, relativize=False,
|
||||
)
|
||||
)
|
||||
types = {r.rdtype for r in records}
|
||||
assert dns.rdatatype.SOA in types
|
||||
assert dns.rdatatype.PTR in types
|
||||
ptrs = [r for r in records if r.rdtype == dns.rdatatype.PTR]
|
||||
targets = {str(r[0].target) for r in ptrs}
|
||||
assert any("member-a.test" in t for t in targets)
|
||||
|
||||
|
||||
class TestSeenClientTracking:
|
||||
def _wait_for_seen_client(self, view, timeout=3.0):
|
||||
"""Poll for SeenTransferClient record (race: response is sent before
|
||||
_track_seen_client completes in the handler thread)."""
|
||||
import time
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if SeenTransferClient.objects.filter(
|
||||
source_ip="127.0.0.1", view=view
|
||||
).exists():
|
||||
return True
|
||||
time.sleep(0.05)
|
||||
return False
|
||||
|
||||
def test_seen_client_recorded_on_success(
|
||||
self, dns_server, make_zone, make_view, tsig_key, patch_settings
|
||||
):
|
||||
patch_settings({"notify_clients": True})
|
||||
view = make_view()
|
||||
make_zone(name="seen.test", view=view)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
tcp_exchange(_signed_soa("seen.test", tsig_key), srv["host"], srv["port"])
|
||||
|
||||
assert self._wait_for_seen_client(view)
|
||||
|
||||
def test_no_tracking_when_notify_clients_false(
|
||||
self, dns_server, make_zone, make_view, tsig_key, patch_settings
|
||||
):
|
||||
patch_settings({"notify_clients": False})
|
||||
view = make_view()
|
||||
make_zone(name="not-seen.test", view=view)
|
||||
srv = dns_server.start(views={"testkey.": view})
|
||||
|
||||
tcp_exchange(_signed_soa("not-seen.test", tsig_key), srv["host"], srv["port"])
|
||||
|
||||
import time
|
||||
time.sleep(0.3)
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
assert not SeenTransferClient.objects.filter(view=view).exists()
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Unit tests for the DNS transfer request handler.
|
||||
|
||||
These exercise routing, denial gates, SOA/AXFR response construction and TSIG
|
||||
handling by feeding crafted wire bytes to ``_handle_dns_query`` and capturing
|
||||
emitted responses. Zone lookups are mocked so no database is needed for the
|
||||
routing/response logic; the integration suite covers the real-socket path.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import dns.flags
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.rcode
|
||||
import dns.rdatatype
|
||||
|
||||
import netbox_dns_bridge.management.commands.dns_transfer_endpoint.request_handler as rh
|
||||
from netbox_dns_bridge.tests._helpers import (
|
||||
CaptureTCPHandler,
|
||||
CaptureUDPHandler,
|
||||
make_dns_zone,
|
||||
make_signed_query,
|
||||
make_tsig_key,
|
||||
make_unsigned_query,
|
||||
parse_response,
|
||||
parse_response_strict,
|
||||
query_mac,
|
||||
build_keyring,
|
||||
build_tsig_view_map,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures local to this module
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def view():
|
||||
return SimpleNamespace(name="default")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def keyring(tsig_key):
|
||||
return build_keyring(tsig_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def view_map(tsig_key, view):
|
||||
return build_tsig_view_map("testkey.", view)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tcp_handler(capture_handler, keyring, view_map):
|
||||
"""Return a factory building a fresh TCP capture handler + captured list."""
|
||||
def _make(client_ip="127.0.0.1"):
|
||||
return capture_handler(CaptureTCPHandler, keyring, view_map, client_ip)
|
||||
return _make
|
||||
|
||||
|
||||
def _patch_regular_zone(monkeypatch, handler, zone):
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
|
||||
|
||||
def _patch_catz(monkeypatch, zone):
|
||||
monkeypatch.setattr(rh.catzm, "create_zone", lambda name, view_name: zone)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denial / routing gates
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRoutingGates:
|
||||
def test_no_tsig_refused(self, tcp_handler, tsig_key):
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_unsigned_query("example.test", dns.rdatatype.SOA)
|
||||
handler._handle_dns_query(wire)
|
||||
assert len(captured) == 1
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_question_count_zero_refused(self, tcp_handler, tsig_key):
|
||||
handler, captured = tcp_handler()
|
||||
msg = dns.message.make_query("example.test", dns.rdatatype.SOA)
|
||||
msg.question = []
|
||||
msg.use_tsig(keyring={tsig_key.name: tsig_key}, keyname=tsig_key.name)
|
||||
handler._handle_dns_query(msg.to_wire())
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_unsupported_qtype_refused(self, tcp_handler, tsig_key):
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_signed_query("example.test", dns.rdatatype.A, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_ixfr_not_supported_refused(self, tcp_handler, tsig_key):
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_signed_query("example.test", dns.rdatatype.IXFR, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_axfr_over_udp_refused(self, capture_handler, keyring, view_map, tsig_key):
|
||||
handler, captured = capture_handler(
|
||||
CaptureUDPHandler, keyring, view_map
|
||||
)
|
||||
wire = make_signed_query("example.test", dns.rdatatype.AXFR, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_key_not_mapped_to_view_refused(self, capture_handler, view):
|
||||
other_key = make_tsig_key("unknownkey.")
|
||||
keyring = build_keyring(other_key)
|
||||
view_map = {} # no mapping
|
||||
handler, captured = capture_handler(CaptureTCPHandler, keyring, view_map)
|
||||
wire = make_signed_query("example.test", dns.rdatatype.SOA, other_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_zone_not_found_refused_not_nxdomain(self, tcp_handler, tsig_key, monkeypatch):
|
||||
handler, captured = tcp_handler()
|
||||
handler._get_zone_from_nb = lambda name, view_name: None
|
||||
wire = make_signed_query("missing.test", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
assert resp.rcode() != dns.rcode.NXDOMAIN
|
||||
|
||||
def test_malformed_query_silent_drop(self, tcp_handler):
|
||||
handler, captured = tcp_handler()
|
||||
handler._handle_dns_query(b"\x00\x00not a dns message")
|
||||
assert captured == []
|
||||
|
||||
def test_zone_without_soa_silent_drop(self, tcp_handler, tsig_key, monkeypatch):
|
||||
import dns.zone
|
||||
import dns.name
|
||||
zone = dns.zone.Zone(dns.name.from_text("empty.test", dns.name.root))
|
||||
handler, captured = tcp_handler()
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("empty.test", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
assert captured == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TSIG error paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestTSIGErrors:
|
||||
def test_bad_signature_refused_with_badsig(self, tcp_handler, tsig_key):
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_signed_query("example.test", dns.rdatatype.SOA, tsig_key)
|
||||
# Flip a byte in the TSIG MAC region to break the signature.
|
||||
tampered = bytearray(wire)
|
||||
tampered[-5] ^= 0xFF
|
||||
handler._handle_dns_query(bytes(tampered))
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_unknown_key_refused_with_badkey(self, tcp_handler):
|
||||
handler, captured = tcp_handler()
|
||||
unknown = make_tsig_key("nopekey.")
|
||||
wire = make_signed_query("example.test", dns.rdatatype.SOA, unknown)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SOA responses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSOAResponse:
|
||||
def test_soa_regular_zone(self, tcp_handler, tsig_key, keyring, monkeypatch):
|
||||
zone = make_dns_zone("example.test", soa_serial=42)
|
||||
handler, captured = tcp_handler()
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("example.test", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
|
||||
resp = parse_response_strict(captured[0], keyring, query_mac(wire, keyring))
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
assert resp.flags & dns.flags.AA
|
||||
assert resp.flags & dns.flags.QR
|
||||
assert len(resp.answer) == 1
|
||||
rrset = resp.answer[0]
|
||||
assert rrset.rdtype == dns.rdatatype.SOA
|
||||
assert rrset[0].serial == 42
|
||||
assert resp.had_tsig
|
||||
|
||||
def test_soa_for_catz(self, tcp_handler, tsig_key, monkeypatch):
|
||||
zone = make_dns_zone("catz", soa_serial=99)
|
||||
_patch_catz(monkeypatch, zone)
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_signed_query("catz", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
assert resp.answer[0].rdtype == dns.rdatatype.SOA
|
||||
assert resp.answer[0][0].serial == 99
|
||||
|
||||
def test_soa_for_view_catz_case_insensitive(self, tcp_handler, tsig_key, monkeypatch):
|
||||
zone = make_dns_zone("default.catz", soa_serial=99)
|
||||
_patch_catz(monkeypatch, zone)
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_signed_query("DEFAULT.CATZ", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
|
||||
def test_soa_catz_case_insensitive(self, tcp_handler, tsig_key, monkeypatch):
|
||||
zone = make_dns_zone("catz", soa_serial=99)
|
||||
_patch_catz(monkeypatch, zone)
|
||||
handler, captured = tcp_handler()
|
||||
wire = make_signed_query("CATZ", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
|
||||
def test_soa_tsig_signed(self, tcp_handler, tsig_key, keyring, monkeypatch):
|
||||
zone = make_dns_zone("example.test", soa_serial=1)
|
||||
handler, captured = tcp_handler()
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("example.test", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response_strict(captured[0], keyring, query_mac(wire, keyring))
|
||||
assert resp.had_tsig
|
||||
assert resp.keyname == tsig_key.name
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AXFR responses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAXFRResponse:
|
||||
def test_axfr_single_message_framing(self, tcp_handler, tsig_key, keyring, monkeypatch):
|
||||
zone = make_dns_zone(
|
||||
"example.test",
|
||||
soa_serial=7,
|
||||
extra=[("www", "A", 300, "192.0.2.1"), ("mail", "A", 300, "192.0.2.2")],
|
||||
)
|
||||
handler, captured = tcp_handler()
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("example.test", dns.rdatatype.AXFR, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
|
||||
# Single message expected (small zone).
|
||||
assert len(captured) == 1
|
||||
resp = parse_response_strict(
|
||||
captured[0], keyring, query_mac(wire, keyring), one_rr_per_rrset=True
|
||||
)
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
assert resp.flags & dns.flags.AA
|
||||
assert resp.flags & dns.flags.QR
|
||||
assert resp.had_tsig
|
||||
|
||||
# First and last answer rrsets are SOA (opening + closing).
|
||||
assert resp.answer[0].rdtype == dns.rdatatype.SOA
|
||||
assert resp.answer[-1].rdtype == dns.rdatatype.SOA
|
||||
assert resp.answer[0][0].serial == 7
|
||||
# Middle records present.
|
||||
types = {rr.rdtype for rr in resp.answer}
|
||||
assert dns.rdatatype.A in types
|
||||
|
||||
def test_axfr_multi_message_when_large(self, tcp_handler, tsig_key, monkeypatch):
|
||||
# Build a zone with many records, then shrink MAX_WIRE to force splits.
|
||||
extras = [(f"host{i}", "A", 300, f"192.0.2.{i % 255}") for i in range(200)]
|
||||
zone = make_dns_zone("big.test", soa_serial=1, extra=extras)
|
||||
handler, captured = tcp_handler()
|
||||
handler.MAX_WIRE = 800
|
||||
handler.RESERVED_TSIG = 300
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("big.test", dns.rdatatype.AXFR, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
|
||||
assert len(captured) >= 2
|
||||
# First message opens with SOA, last message closes with SOA.
|
||||
first = parse_response(captured[0], one_rr_per_rrset=True)
|
||||
last = parse_response(captured[-1], one_rr_per_rrset=True)
|
||||
assert first.answer[0].rdtype == dns.rdatatype.SOA
|
||||
assert last.answer[-1].rdtype == dns.rdatatype.SOA
|
||||
|
||||
def test_axfr_over_udp_refused(self, capture_handler, keyring, view_map, tsig_key):
|
||||
handler, captured = capture_handler(CaptureUDPHandler, keyring, view_map)
|
||||
wire = make_signed_query("example.test", dns.rdatatype.AXFR, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
|
||||
def test_axfr_zone_without_soa_silent_drop(self, tcp_handler, tsig_key, monkeypatch):
|
||||
import dns.zone
|
||||
import dns.name
|
||||
zone = dns.zone.Zone(dns.name.from_text("nosoa.test", dns.name.root))
|
||||
handler, captured = tcp_handler()
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("nosoa.test", dns.rdatatype.AXFR, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
assert captured == []
|
||||
|
||||
def test_axfr_tsig_chain_uses_query_mac_first(self, tcp_handler, tsig_key, keyring, monkeypatch):
|
||||
extras = [(f"host{i}", "A", 300, f"192.0.2.{i % 255}") for i in range(120)]
|
||||
zone = make_dns_zone("chain.test", soa_serial=1, extra=extras)
|
||||
handler, captured = tcp_handler()
|
||||
handler.MAX_WIRE = 800
|
||||
handler.RESERVED_TSIG = 300
|
||||
handler._get_zone_from_nb = lambda name, view_name: zone
|
||||
wire = make_signed_query("chain.test", dns.rdatatype.AXFR, tsig_key)
|
||||
handler._handle_dns_query(query_mac_wire := wire)
|
||||
# At least two messages produced.
|
||||
assert len(captured) >= 2
|
||||
# First message verifies against the request MAC and opens with SOA.
|
||||
first = parse_response_strict(
|
||||
captured[0], keyring, query_mac(wire, keyring), one_rr_per_rrset=True
|
||||
)
|
||||
assert first.had_tsig
|
||||
assert first.answer[0].rdtype == dns.rdatatype.SOA
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Routing: case sensitivity, trailing dot
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRoutingDetails:
|
||||
def test_regular_zone_case_sensitive(self, tcp_handler, tsig_key):
|
||||
zone = make_dns_zone("example.test", soa_serial=1)
|
||||
handler, captured = tcp_handler()
|
||||
calls = []
|
||||
|
||||
def _lookup(name, view_name):
|
||||
calls.append(name)
|
||||
return zone if name == "example.test" else None
|
||||
|
||||
handler._get_zone_from_nb = _lookup
|
||||
wire = make_signed_query("Example.TEST", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.REFUSED
|
||||
assert calls == ["Example.TEST"]
|
||||
|
||||
def test_trailing_dot_normalized(self, tcp_handler, tsig_key):
|
||||
zone = make_dns_zone("example.test", soa_serial=1)
|
||||
handler, captured = tcp_handler()
|
||||
seen = []
|
||||
handler._get_zone_from_nb = lambda name, view_name: (
|
||||
seen.append(name) or zone
|
||||
)
|
||||
wire = make_signed_query("example.test.", dns.rdatatype.SOA, tsig_key)
|
||||
handler._handle_dns_query(wire)
|
||||
resp = parse_response(captured[0])
|
||||
assert resp.rcode() == dns.rcode.NOERROR
|
||||
assert seen == ["example.test"]
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Tests for signal handlers: zone_pre_save, zone_post_save, zone_post_delete.
|
||||
|
||||
Uses ``captureOnCommitCallbacks(execute=True)`` to fire ``transaction.on_commit``
|
||||
callbacks inside the transaction-wrapped ``@pytest.mark.django_db`` test scope.
|
||||
"""
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
from django.test.testcases import TestCase as _DjangoTestCase
|
||||
|
||||
# captureOnCommitCallbacks is a classmethod on TestCase in Django 6.x
|
||||
captureOnCommitCallbacks = _DjangoTestCase.captureOnCommitCallbacks
|
||||
|
||||
from netbox_dns_bridge.models import (
|
||||
CatalogZone,
|
||||
CatalogZoneMember,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestZonePreSave:
|
||||
def test_stores_old_name_and_serial_on_existing_zone(self, make_zone):
|
||||
zone = make_zone(name="presave.test", soa_serial=100)
|
||||
zone.refresh_from_db()
|
||||
zone.soa_serial = 200
|
||||
zone.save()
|
||||
assert getattr(zone, "_old_name", None) == "presave.test"
|
||||
assert getattr(zone, "_old_soa_serial", None) == 100
|
||||
|
||||
def test_old_attrs_none_on_new_zone(self, make_zone):
|
||||
zone = make_zone(name="newzone.test")
|
||||
assert getattr(zone, "_old_name", None) is None
|
||||
assert getattr(zone, "_old_soa_serial", None) is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestZonePostSaveCreate:
|
||||
def test_creates_catalog_zone_member_on_new_zone(self, make_zone):
|
||||
zone = make_zone(name="postcreate.test")
|
||||
assert CatalogZoneMember.objects.filter(zone=zone).exists()
|
||||
|
||||
def test_increments_soa_serial_on_commit(self, make_zone, catz_serial):
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone = make_zone(name="serial-inc.test")
|
||||
obj = CatalogZone.objects.get(view=zone.view)
|
||||
assert obj.soa_serial == catz_serial + 1
|
||||
|
||||
def test_does_not_increment_without_on_commit(self, make_zone, catz_serial):
|
||||
zone = make_zone(name="no-commit.test")
|
||||
obj = CatalogZone.objects.get(view=zone.view)
|
||||
assert obj.soa_serial == catz_serial
|
||||
|
||||
def test_schedule_client_notify_always_called(self, make_zone, patch_settings):
|
||||
patch_settings({"notify_clients": True})
|
||||
with patch(
|
||||
"netbox_dns_bridge.jobs.notify.schedule_client_notify"
|
||||
) as mock_notify:
|
||||
with patch("netbox_dns_bridge.jobs.notify.schedule_ns_notify"):
|
||||
with patch(
|
||||
"netbox_dns_bridge.management.commands.dns_transfer_endpoint."
|
||||
"catalog_zone_manager.notify.schedule_catalog_zone_notify"
|
||||
):
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
make_zone(name="notify.test")
|
||||
mock_notify.assert_called_once()
|
||||
|
||||
def test_schedule_ns_notify_called_when_serial_changed(
|
||||
self, make_zone, patch_settings
|
||||
):
|
||||
patch_settings({
|
||||
"notify_clients": False,
|
||||
"notify_ns_all_zones": True,
|
||||
})
|
||||
with patch(
|
||||
"netbox_dns_bridge.jobs.notify.schedule_ns_notify"
|
||||
) as mock_ns_notify:
|
||||
with patch("netbox_dns_bridge.jobs.notify.schedule_client_notify"):
|
||||
with patch(
|
||||
"netbox_dns_bridge.management.commands.dns_transfer_endpoint."
|
||||
"catalog_zone_manager.notify.schedule_catalog_zone_notify"
|
||||
):
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
make_zone(name="nsnotify.test")
|
||||
mock_ns_notify.assert_called_once()
|
||||
|
||||
def test_schedule_ns_notify_not_called_when_serial_unchanged(
|
||||
self, make_zone, patch_settings
|
||||
):
|
||||
patch_settings({"notify_ns_all_zones": True})
|
||||
with patch(
|
||||
"netbox_dns_bridge.jobs.notify.schedule_ns_notify"
|
||||
) as mock_ns_notify:
|
||||
with patch("netbox_dns_bridge.jobs.notify.schedule_client_notify"):
|
||||
with patch(
|
||||
"netbox_dns_bridge.management.commands.dns_transfer_endpoint."
|
||||
"catalog_zone_manager.notify.schedule_catalog_zone_notify"
|
||||
):
|
||||
zone = make_zone(name="noserialchange.test")
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.save()
|
||||
mock_ns_notify.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestZonePostSaveUpdate:
|
||||
def test_updates_member_on_name_change(self, make_zone):
|
||||
zone = make_zone(name="rename-old.test")
|
||||
old_name = CatalogZoneMember.objects.get(zone=zone).name
|
||||
|
||||
zone.name = "rename-new.test"
|
||||
zone.save()
|
||||
|
||||
new_name = CatalogZoneMember.objects.get(zone=zone).name
|
||||
assert old_name != new_name
|
||||
|
||||
def test_no_identifier_update_when_name_unchanged(self, make_zone):
|
||||
zone = make_zone(name="nochange.test")
|
||||
ident = CatalogZoneMember.objects.get(zone=zone)
|
||||
original_name = ident.name
|
||||
|
||||
zone.soa_serial = zone.soa_serial + 1
|
||||
zone.save()
|
||||
ident.refresh_from_db()
|
||||
assert ident.name == original_name
|
||||
|
||||
def test_increments_serial_on_commit_on_update(self, make_zone, catz_serial):
|
||||
zone = make_zone(name="update-serial.test")
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.soa_serial = zone.soa_serial + 1
|
||||
zone.save()
|
||||
obj = CatalogZone.objects.get(view=zone.view)
|
||||
assert obj.soa_serial == catz_serial + 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestZonePostDelete:
|
||||
def test_increments_soa_serial_on_commit_on_delete(self, make_zone, catz_serial):
|
||||
zone = make_zone(name="delete-serial.test")
|
||||
view = zone.view
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.delete()
|
||||
obj = CatalogZone.objects.get(view=view)
|
||||
assert obj.soa_serial == catz_serial + 1
|
||||
|
||||
def test_does_not_increment_without_on_commit(self, make_zone, catz_serial):
|
||||
zone = make_zone(name="delete-no-commit.test")
|
||||
view = zone.view
|
||||
zone.delete()
|
||||
obj = CatalogZone.objects.get(view=view)
|
||||
assert obj.soa_serial == catz_serial
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestZoneViewChange:
|
||||
def test_increments_both_catalog_zone_serials(self, make_zone, make_view, catz_serial):
|
||||
view_a = make_view(name="view-a")
|
||||
view_b = make_view(name="view-b")
|
||||
# view_b has no zones yet, so no CatalogZone was auto-created for it.
|
||||
CatalogZone.objects.create(view=view_b, soa_serial=5)
|
||||
|
||||
zone = make_zone(name="move.test", view=view_a)
|
||||
|
||||
serial_a_before = CatalogZone.objects.get(view=view_a).soa_serial
|
||||
serial_b_before = CatalogZone.objects.get(view=view_b).soa_serial
|
||||
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.view = view_b
|
||||
zone.save()
|
||||
|
||||
serial_a_after = CatalogZone.objects.get(view=view_a).soa_serial
|
||||
serial_b_after = CatalogZone.objects.get(view=view_b).soa_serial
|
||||
assert serial_a_after == serial_a_before + 1
|
||||
assert serial_b_after == serial_b_before + 1
|
||||
|
||||
def test_updates_identifier_catalog_zone_fk(self, make_zone, make_view):
|
||||
view_a = make_view(name="fk-view-a")
|
||||
view_b = make_view(name="fk-view-b")
|
||||
zone = make_zone(name="fk-move.test", view=view_a)
|
||||
|
||||
ident = CatalogZoneMember.objects.get(zone=zone)
|
||||
assert ident.catalog_zone == CatalogZone.objects.get(view=view_a)
|
||||
|
||||
zone.view = view_b
|
||||
zone.save()
|
||||
|
||||
ident.refresh_from_db()
|
||||
assert ident.catalog_zone == CatalogZone.objects.get(view=view_b)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSignalDedup:
|
||||
def test_dedup_skips_second_save_in_same_request(self, make_zone):
|
||||
from netbox.context import current_request
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
zone = make_zone(name="dedup.test")
|
||||
original_serial = CatalogZone.objects.get(
|
||||
view=zone.view
|
||||
).soa_serial
|
||||
|
||||
User = get_user_model()
|
||||
user = User(username="dedup-user", is_superuser=True)
|
||||
user.save()
|
||||
|
||||
request = MagicMock()
|
||||
request._handled_zones = set()
|
||||
request.user = user
|
||||
import uuid as _uuid
|
||||
request.id = _uuid.uuid4()
|
||||
|
||||
with current_request.set(request):
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.soa_serial = zone.soa_serial + 1
|
||||
zone.save()
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.soa_serial = zone.soa_serial + 2
|
||||
zone.save()
|
||||
|
||||
new_serial = CatalogZone.objects.get(
|
||||
view=zone.view
|
||||
).soa_serial
|
||||
assert new_serial == original_serial + 1
|
||||
|
||||
def test_no_dedup_without_request(self, make_zone):
|
||||
zone = make_zone(name="nodedup.test")
|
||||
original_serial = CatalogZone.objects.get(
|
||||
view=zone.view
|
||||
).soa_serial
|
||||
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.soa_serial = zone.soa_serial + 1
|
||||
zone.save()
|
||||
with captureOnCommitCallbacks(execute=True):
|
||||
zone.soa_serial = zone.soa_serial + 2
|
||||
zone.save()
|
||||
|
||||
new_serial = CatalogZone.objects.get(
|
||||
view=zone.view
|
||||
).soa_serial
|
||||
assert new_serial == original_serial + 2
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Smoke test: verify the harness loads under the full NetBox stack."""
|
||||
import django
|
||||
|
||||
|
||||
def test_django_loaded():
|
||||
assert django.VERSION[0] >= 5
|
||||
|
||||
|
||||
def test_plugin_importable():
|
||||
import netbox_dns_bridge # noqa: F401
|
||||
assert netbox_dns_bridge.__version__
|
||||
|
||||
|
||||
def test_models_importable():
|
||||
from netbox_dns_bridge.models import (
|
||||
CatalogZone,
|
||||
CatalogZoneMember,
|
||||
SeenTransferClient,
|
||||
)
|
||||
assert CatalogZone._meta.model_name
|
||||
assert CatalogZoneMember._meta.model_name
|
||||
assert SeenTransferClient._meta.model_name
|
||||
|
||||
|
||||
def test_request_handler_importable():
|
||||
from netbox_dns_bridge.management.commands.dns_transfer_endpoint import ( # noqa: F401
|
||||
request_handler,
|
||||
catalog_zone_manager,
|
||||
dns_server,
|
||||
)
|
||||
|
||||
|
||||
def test_helpers_build_dns_zone():
|
||||
from netbox_dns_bridge.tests._helpers import make_dns_zone
|
||||
|
||||
zone = make_dns_zone("example.test", soa_serial=42)
|
||||
import dns.rdatatype
|
||||
rds = zone.get_rdataset(zone.origin, dns.rdatatype.SOA)
|
||||
assert rds is not None
|
||||
assert rds[0].serial == 42
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Tests for netbox_dns_bridge.utils: get_logger, build_dns_zone, export_bind_zone_file."""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import dns.name
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import pytest
|
||||
|
||||
from netbox_dns_bridge.utils import get_logger, build_dns_zone, export_bind_zone_file
|
||||
|
||||
|
||||
class TestGetLogger:
|
||||
def test_returns_dns_bridge_logger(self):
|
||||
logger = get_logger("some.module")
|
||||
assert logger.name == "dns-bridge"
|
||||
|
||||
def test_ignores_name_argument(self):
|
||||
a = get_logger("module.a")
|
||||
b = get_logger("module.b")
|
||||
assert a is b
|
||||
assert a.name == "dns-bridge"
|
||||
|
||||
def test_logger_is_singleton(self):
|
||||
import logging
|
||||
|
||||
logger = get_logger("x")
|
||||
assert logger is logging.getLogger("dns-bridge")
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestBuildDnsZone:
|
||||
def test_basic_a_record(self, make_zone, make_record):
|
||||
zone = make_zone(name="a.test")
|
||||
make_record(zone, name="www", type_="A", value="192.0.2.1")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("a.test", dns.name.root)
|
||||
rds = dns_zone.get_rdataset(origin, dns.rdatatype.SOA)
|
||||
assert rds is not None
|
||||
a_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("www", origin), dns.rdatatype.A
|
||||
)
|
||||
assert a_rds is not None
|
||||
assert str(a_rds[0]) == "192.0.2.1"
|
||||
|
||||
def test_apex_record_empty_name(self, make_zone, make_record):
|
||||
zone = make_zone(name="apex.test")
|
||||
make_record(zone, name="@", type_="A", value="192.0.2.10")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("apex.test", dns.name.root)
|
||||
a_rds = dns_zone.get_rdataset(origin, dns.rdatatype.A)
|
||||
assert a_rds is not None
|
||||
assert str(a_rds[0]) == "192.0.2.10"
|
||||
|
||||
def test_ttl_fallback_to_zone_default(self, make_zone, make_record):
|
||||
zone = make_zone(name="ttl.test", default_ttl=7200)
|
||||
make_record(zone, name="host", type_="A", value="192.0.2.2", ttl=None)
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("ttl.test", dns.name.root)
|
||||
a_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("host", origin), dns.rdatatype.A
|
||||
)
|
||||
assert a_rds.ttl == 7200
|
||||
|
||||
def test_record_ttl_overrides_zone_default(self, make_zone, make_record):
|
||||
zone = make_zone(name="ttl2.test", default_ttl=7200)
|
||||
make_record(zone, name="host", type_="A", value="192.0.2.3", ttl=300)
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("ttl2.test", dns.name.root)
|
||||
a_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("host", origin), dns.rdatatype.A
|
||||
)
|
||||
assert a_rds.ttl == 300
|
||||
|
||||
def test_txt_record_quoting(self, make_zone, make_record):
|
||||
zone = make_zone(name="txt.test")
|
||||
make_record(zone, name="spf", type_="TXT", value="v=spf1 -all")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("txt.test", dns.name.root)
|
||||
txt_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("spf", origin), dns.rdatatype.TXT
|
||||
)
|
||||
assert txt_rds is not None
|
||||
assert str(txt_rds[0]) == '"v=spf1 -all"'
|
||||
|
||||
def test_txt_record_already_quoted(self, make_zone, make_record):
|
||||
zone = make_zone(name="txtq.test")
|
||||
make_record(zone, name="dkim", type_="TXT", value='"k=rsa; p=MIGf"')
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("txtq.test", dns.name.root)
|
||||
txt_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("dkim", origin), dns.rdatatype.TXT
|
||||
)
|
||||
assert txt_rds is not None
|
||||
assert "k=rsa" in str(txt_rds[0])
|
||||
|
||||
def test_txt_record_long_value_chunked(self, make_zone, make_record):
|
||||
zone = make_zone(name="longtxt.test")
|
||||
long_val = "a" * 300
|
||||
make_record(zone, name="big", type_="TXT", value=long_val)
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("longtxt.test", dns.name.root)
|
||||
txt_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("big", origin), dns.rdatatype.TXT
|
||||
)
|
||||
assert txt_rds is not None
|
||||
wire = str(txt_rds[0])
|
||||
assert "a" * 300 in wire.replace('"', "").replace(" ", "")
|
||||
|
||||
def test_absolute_name_record(self, make_zone, make_record):
|
||||
zone = make_zone(name="abs.test")
|
||||
make_record(zone, name="out.abs.test.", type_="A", value="192.0.2.99")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
abs_name = dns.name.from_text("out.abs.test", dns.name.root)
|
||||
a_rds = dns_zone.get_rdataset(abs_name, dns.rdatatype.A)
|
||||
assert a_rds is not None
|
||||
assert str(a_rds[0]) == "192.0.2.99"
|
||||
|
||||
def test_multiple_records_same_name_type(self, make_zone, make_record):
|
||||
zone = make_zone(name="multi.test")
|
||||
make_record(zone, name="lb", type_="A", value="192.0.2.1")
|
||||
make_record(zone, name="lb", type_="A", value="192.0.2.2")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("multi.test", dns.name.root)
|
||||
a_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("lb", origin), dns.rdatatype.A
|
||||
)
|
||||
assert a_rds is not None
|
||||
assert len(a_rds) == 2
|
||||
values = {str(r) for r in a_rds}
|
||||
assert values == {"192.0.2.1", "192.0.2.2"}
|
||||
|
||||
def test_inactive_records_excluded(self, make_zone, make_record):
|
||||
from netbox_dns.choices import RecordStatusChoices
|
||||
|
||||
zone = make_zone(name="inactive.test")
|
||||
make_record(zone, name="active", type_="A", value="192.0.2.1",
|
||||
status=RecordStatusChoices.STATUS_ACTIVE)
|
||||
make_record(zone, name="inactive", type_="A", value="192.0.2.2",
|
||||
status=RecordStatusChoices.STATUS_INACTIVE)
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("inactive.test", dns.name.root)
|
||||
assert dns_zone.get_rdataset(
|
||||
dns.name.from_text("active", origin), dns.rdatatype.A
|
||||
) is not None
|
||||
assert dns_zone.get_rdataset(
|
||||
dns.name.from_text("inactive", origin), dns.rdatatype.A
|
||||
) is None
|
||||
|
||||
def test_zone_rdclass_is_in(self, make_zone, make_record):
|
||||
zone = make_zone(name="rdclass.test")
|
||||
make_record(zone, name="x", type_="A", value="192.0.2.1")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
assert dns_zone.rdclass == dns.rdataclass.IN
|
||||
|
||||
def test_aaaa_record(self, make_zone, make_record):
|
||||
zone = make_zone(name="aaaa.test")
|
||||
make_record(zone, name="v6", type_="AAAA", value="2001:db8::1")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("aaaa.test", dns.name.root)
|
||||
aaaa_rds = dns_zone.get_rdataset(
|
||||
dns.name.from_text("v6", origin), dns.rdatatype.AAAA
|
||||
)
|
||||
assert aaaa_rds is not None
|
||||
assert str(aaaa_rds[0]) == "2001:db8::1"
|
||||
|
||||
def test_cname_record(self, make_zone, make_record):
|
||||
zone = make_zone(name="cname.test")
|
||||
make_record(zone, name="alias", type_="CNAME", value="target.test.")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("cname.test", dns.name.root)
|
||||
cnames = dns_zone.get_rdataset(
|
||||
dns.name.from_text("alias", origin), dns.rdatatype.CNAME
|
||||
)
|
||||
assert cnames is not None
|
||||
assert str(cnames[0]) == "target.test."
|
||||
|
||||
def test_mx_record(self, make_zone, make_record):
|
||||
zone = make_zone(name="mx.test")
|
||||
make_record(zone, name="@", type_="MX", value="10 mail.test.")
|
||||
dns_zone = build_dns_zone(zone)
|
||||
origin = dns.name.from_text("mx.test", dns.name.root)
|
||||
mx_rds = dns_zone.get_rdataset(origin, dns.rdatatype.MX)
|
||||
assert mx_rds is not None
|
||||
assert mx_rds[0].preference == 10
|
||||
assert str(mx_rds[0].exchange) == "mail.test."
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestExportBindZoneFile:
|
||||
def test_writes_valid_zone_file(self, make_zone, make_record):
|
||||
zone = make_zone(name="export.test")
|
||||
make_record(zone, name="www", type_="A", value="192.0.2.1")
|
||||
with tempfile.NamedTemporaryFile(mode="w", suffix=".zone", delete=False) as f:
|
||||
path = f.name
|
||||
try:
|
||||
export_bind_zone_file(zone, path)
|
||||
with open(path) as f:
|
||||
content = f.read()
|
||||
assert "SOA" in content
|
||||
assert "192.0.2.1" in content
|
||||
assert "www" in content
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
def test_io_error_on_bad_path(self, make_zone):
|
||||
zone = make_zone(name="badpath.test")
|
||||
with pytest.raises(IOError):
|
||||
export_bind_zone_file(zone, "/nonexistent/dir/zone.file")
|
||||
@@ -0,0 +1,278 @@
|
||||
"""Tests for views: CatalogZone list/detail/edit, CatalogZoneMember list/detail, SeenTransferClient list/detail — auth gate and context."""
|
||||
import pytest
|
||||
from django.test import Client
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return Client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def superuser(db):
|
||||
User = get_user_model()
|
||||
user = User(username="admin", email="admin@test.local", is_superuser=True)
|
||||
user.set_password("testpass")
|
||||
user.save()
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def regular_user(db):
|
||||
User = get_user_model()
|
||||
user = User(username="regular", email="reg@test.local")
|
||||
user.set_password("testpass")
|
||||
user.save()
|
||||
return user
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZoneMemberListView:
|
||||
def test_unauthenticated_redirects_to_login(self, client):
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zone-members/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user):
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zone-members/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_access(self, client, superuser, make_zone):
|
||||
make_zone(name="member-list.test")
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zone-members/")
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_list_contains_members(self, client, superuser, make_zone):
|
||||
zone = make_zone(name="member-row.test")
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zone-members/")
|
||||
member_list = list(resp.context["table"].data)
|
||||
assert len(member_list) >= 1
|
||||
m = next(m for m in member_list if m.zone_id == zone.id)
|
||||
assert m.name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZoneMemberDetailView:
|
||||
def test_unauthenticated_redirects_to_login(self, client, make_zone):
|
||||
zone = make_zone(name="member-detail.test")
|
||||
from netbox_dns_bridge.models import CatalogZoneMember
|
||||
m = CatalogZoneMember.objects.get(zone=zone)
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zone-members/{m.pk}/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user, make_zone):
|
||||
zone = make_zone(name="member-detail-forbidden.test")
|
||||
from netbox_dns_bridge.models import CatalogZoneMember
|
||||
m = CatalogZoneMember.objects.get(zone=zone)
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zone-members/{m.pk}/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_access_detail(self, client, superuser, make_zone):
|
||||
zone = make_zone(name="member-detail-get.test")
|
||||
from netbox_dns_bridge.models import CatalogZoneMember
|
||||
m = CatalogZoneMember.objects.get(zone=zone)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zone-members/{m.pk}/")
|
||||
assert resp.status_code == 200
|
||||
assert resp.context["object"].name == m.name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZoneListView:
|
||||
def test_unauthenticated_redirects_to_login(self, client):
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zones/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user):
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zones/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_access(self, client, superuser):
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zones/")
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_list_contains_catalog_zones(self, client, superuser, catz_serial, make_zone):
|
||||
zone = make_zone(name="ctx.test")
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zones/")
|
||||
cz_list = list(resp.context["table"].data)
|
||||
assert len(cz_list) >= 1
|
||||
cz = next(c for c in cz_list if c.view_id == zone.view_id)
|
||||
assert cz.soa_serial == catz_serial
|
||||
|
||||
def test_list_empty_when_no_catalog_zones(self, client, superuser):
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zones/")
|
||||
cz_list = list(resp.context["table"].data)
|
||||
assert cz_list == []
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZoneEditView:
|
||||
def test_unauthenticated_redirects_to_login(self, client, make_view):
|
||||
view = make_view(name="edit-cz-view")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/edit/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user, make_view):
|
||||
view = make_view(name="edit-cz-view-forbidden")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/edit/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_get_edit_form(self, client, superuser, make_view):
|
||||
view = make_view(name="edit-cz-view-get")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/edit/")
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_superuser_can_update_soa_fields(self, client, superuser, make_view):
|
||||
view = make_view(name="edit-cz-view-post")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.post(
|
||||
f"/plugins/dns-bridge/catalog-zones/{cz.pk}/edit/",
|
||||
{
|
||||
"soa_serial": 100,
|
||||
"soa_refresh": 300,
|
||||
"soa_retry": 100,
|
||||
"soa_expire": 86400,
|
||||
"soa_minimum": 3600,
|
||||
},
|
||||
)
|
||||
cz.refresh_from_db()
|
||||
assert cz.soa_serial == 100
|
||||
assert cz.soa_refresh == 300
|
||||
assert cz.soa_retry == 100
|
||||
assert cz.soa_expire == 86400
|
||||
assert cz.soa_minimum == 3600
|
||||
|
||||
def test_no_create_route(self, client, superuser):
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/catalog-zones/add/")
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_no_delete_route(self, client, superuser, make_view):
|
||||
view = make_view(name="edit-cz-view-delete")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/delete/")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCatalogZoneDetailView:
|
||||
def test_unauthenticated_redirects_to_login(self, client, make_view):
|
||||
view = make_view(name="detail-cz-view")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user, make_view):
|
||||
view = make_view(name="detail-cz-view-forbidden")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view)
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_access_detail(self, client, superuser, make_view):
|
||||
view = make_view(name="detail-cz-view-get")
|
||||
from netbox_dns_bridge.models import CatalogZone
|
||||
cz = CatalogZone.objects.create(view=view, soa_serial=42)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/catalog-zones/{cz.pk}/")
|
||||
assert resp.status_code == 200
|
||||
assert resp.context["object"].soa_serial == 42
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSeenTransferClientListView:
|
||||
def test_unauthenticated_redirects_to_login(self, client):
|
||||
resp = client.get("/plugins/dns-bridge/seen-transfer-clients/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user):
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/seen-transfer-clients/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_access(self, client, superuser, make_view):
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="stc-list-view")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1", view=view, last_seen=timezone.now()
|
||||
)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/seen-transfer-clients/")
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_list_contains_clients(self, client, superuser, make_view):
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="stc-list-row-view")
|
||||
SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1", view=view, last_seen=timezone.now()
|
||||
)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get("/plugins/dns-bridge/seen-transfer-clients/")
|
||||
client_list = list(resp.context["table"].data)
|
||||
assert len(client_list) >= 1
|
||||
assert client_list[0].source_ip == "192.0.2.1"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSeenTransferClientDetailView:
|
||||
def test_unauthenticated_redirects_to_login(self, client, make_view):
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="stc-detail-view")
|
||||
c = SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1", view=view, last_seen=timezone.now()
|
||||
)
|
||||
resp = client.get(f"/plugins/dns-bridge/seen-transfer-clients/{c.pk}/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_regular_user_forbidden(self, client, regular_user, make_view):
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="stc-detail-forbidden-view")
|
||||
c = SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.1", view=view, last_seen=timezone.now()
|
||||
)
|
||||
client.login(username="regular", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/seen-transfer-clients/{c.pk}/")
|
||||
assert resp.status_code in (302, 403)
|
||||
|
||||
def test_superuser_can_access_detail(self, client, superuser, make_view):
|
||||
from netbox_dns_bridge.models import SeenTransferClient
|
||||
from django.utils import timezone
|
||||
|
||||
view = make_view(name="stc-detail-get-view")
|
||||
c = SeenTransferClient.objects.create(
|
||||
source_ip="192.0.2.42", view=view, last_seen=timezone.now()
|
||||
)
|
||||
client.login(username="admin", password="testpass")
|
||||
resp = client.get(f"/plugins/dns-bridge/seen-transfer-clients/{c.pk}/")
|
||||
assert resp.status_code == 200
|
||||
assert resp.context["object"].source_ip == "192.0.2.42"
|
||||
@@ -0,0 +1,47 @@
|
||||
from django.urls import include, path
|
||||
|
||||
from utilities.urls import get_model_urls
|
||||
|
||||
# Import views so register_model_view decorators run.
|
||||
from .views import ( # noqa: F401
|
||||
CatalogZoneEditView,
|
||||
CatalogZoneListView,
|
||||
CatalogZoneMemberListView,
|
||||
CatalogZoneMemberView,
|
||||
CatalogZoneView,
|
||||
SeenTransferClientListView,
|
||||
SeenTransferClientView,
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path(
|
||||
"catalog-zones/",
|
||||
include(
|
||||
get_model_urls("netbox_dns_bridge", "catalogzone", detail=False)
|
||||
),
|
||||
),
|
||||
path(
|
||||
"catalog-zones/<int:pk>/",
|
||||
include(get_model_urls("netbox_dns_bridge", "catalogzone")),
|
||||
),
|
||||
path(
|
||||
"catalog-zone-members/",
|
||||
include(
|
||||
get_model_urls("netbox_dns_bridge", "catalogzonemember", detail=False)
|
||||
),
|
||||
),
|
||||
path(
|
||||
"catalog-zone-members/<int:pk>/",
|
||||
include(get_model_urls("netbox_dns_bridge", "catalogzonemember")),
|
||||
),
|
||||
path(
|
||||
"seen-transfer-clients/",
|
||||
include(
|
||||
get_model_urls("netbox_dns_bridge", "seentransferclient", detail=False)
|
||||
),
|
||||
),
|
||||
path(
|
||||
"seen-transfer-clients/<int:pk>/",
|
||||
include(get_model_urls("netbox_dns_bridge", "seentransferclient")),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,103 @@
|
||||
import dns.name
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.rdataset
|
||||
import netbox_dns.models
|
||||
import logging
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
return logging.getLogger("dns-bridge")
|
||||
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
||||
def build_dns_zone(nb_zone: netbox_dns.models.Zone) -> dns.zone.Zone:
|
||||
# Build DNS zone
|
||||
zone = dns.zone.Zone(nb_zone.name, dns.name.root)
|
||||
zone.rdclass = dns.rdataclass.IN
|
||||
|
||||
nb_records = nb_zone.records.filter(active=True)
|
||||
|
||||
rdatasets_dict = {}
|
||||
|
||||
for record in nb_records:
|
||||
rdtype = dns.rdatatype.from_text(record.type)
|
||||
if not record.name:
|
||||
name = zone.origin
|
||||
elif record.name.endswith("."):
|
||||
name = dns.name.from_text(record.name)
|
||||
else:
|
||||
name = dns.name.from_text(record.name, origin=zone.origin)
|
||||
|
||||
# If the record has no TTL, use the zone default
|
||||
ttl = record.ttl or nb_zone.default_ttl
|
||||
|
||||
# Apply quoting for TXT records to stop tokanizer
|
||||
# from cutting it up:
|
||||
value = record.value
|
||||
if rdtype == dns.rdatatype.TXT:
|
||||
if value.startswith('"') and value.endswith('"'):
|
||||
value = value[1:-1].replace('" "', "").replace('"', '"')
|
||||
|
||||
if len(value) > 255:
|
||||
# This is a bug fix for netbox. If netbox allowed for
|
||||
# an unquoted value to be larger then 255 characters,
|
||||
# it misunderstood everything behind a ; as a comment.
|
||||
chunks = [
|
||||
'"{}"'.format(value[i : i + 255]) for i in range(0, len(value), 255)
|
||||
]
|
||||
value = " ".join(chunks)
|
||||
else:
|
||||
value = f'"{value}"'
|
||||
|
||||
rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN,
|
||||
rdtype,
|
||||
value,
|
||||
relativize=False,
|
||||
origin=zone.origin,
|
||||
)
|
||||
|
||||
# Initialize rdataset if it doesn't exist for this name and type
|
||||
if name not in rdatasets_dict:
|
||||
rdatasets_dict[name] = {}
|
||||
if rdtype not in rdatasets_dict[name]:
|
||||
rdatasets_dict[name][rdtype] = dns.rdataset.Rdataset(
|
||||
dns.rdataclass.IN, rdtype
|
||||
)
|
||||
|
||||
# Add the rdata to the appropriate rdataset
|
||||
rdatasets_dict[name][rdtype].add(rdata, ttl)
|
||||
|
||||
# Now, add all rdatasets to the zone
|
||||
for name, rdtypes in rdatasets_dict.items():
|
||||
for rdtype, rdataset in rdtypes.items():
|
||||
# Ensure rdataset has the same rdclass as the zone
|
||||
if rdataset.rdclass != zone.rdclass:
|
||||
raise ValueError(
|
||||
f"rdataset rdclass {rdataset.rdclass} does not match "
|
||||
f"zone rdclass {zone.rdclass}"
|
||||
)
|
||||
|
||||
# Check if the rdataset has any rdata before creating an RRset
|
||||
if not rdataset:
|
||||
LOGGER.debug(f"Skipping empty rdataset for {name} {rdtype}")
|
||||
continue # Skip empty rdataset
|
||||
|
||||
# Replace the rdataset for the given name and type
|
||||
zone.replace_rdataset(name, rdataset)
|
||||
return zone
|
||||
|
||||
|
||||
def export_bind_zone_file(nb_zone: netbox_dns.models.Zone, file_path: str):
|
||||
zone = build_dns_zone(nb_zone)
|
||||
|
||||
# Write zone to file in BIND format
|
||||
try:
|
||||
with open(file_path, "w") as f:
|
||||
zone.to_file(f, sorted=True)
|
||||
except IOError as e:
|
||||
raise IOError(f"Failed to write zone file to {file_path}: {e}")
|
||||
@@ -0,0 +1,76 @@
|
||||
from netbox.object_actions import EditObject
|
||||
from netbox.views import generic
|
||||
from utilities.views import register_model_view
|
||||
|
||||
from .filtersets import (
|
||||
CatalogZoneFilterSet,
|
||||
CatalogZoneMemberFilterSet,
|
||||
SeenTransferClientFilterSet,
|
||||
)
|
||||
from .forms import (
|
||||
CatalogZoneFilterForm,
|
||||
CatalogZoneForm,
|
||||
CatalogZoneMemberFilterForm,
|
||||
SeenTransferClientFilterForm,
|
||||
)
|
||||
from .models import CatalogZone, CatalogZoneMember, SeenTransferClient
|
||||
from .tables import (
|
||||
CatalogZoneMemberTable,
|
||||
CatalogZoneTable,
|
||||
SeenTransferClientTable,
|
||||
)
|
||||
|
||||
|
||||
@register_model_view(CatalogZone, "list", path="", detail=False)
|
||||
class CatalogZoneListView(generic.ObjectListView):
|
||||
queryset = CatalogZone.objects.select_related("view").order_by("view__name")
|
||||
table = CatalogZoneTable
|
||||
filterset = CatalogZoneFilterSet
|
||||
filterset_form = CatalogZoneFilterForm
|
||||
actions = ()
|
||||
|
||||
|
||||
@register_model_view(CatalogZone)
|
||||
class CatalogZoneView(generic.ObjectView):
|
||||
queryset = CatalogZone.objects.select_related("view")
|
||||
actions = (EditObject,)
|
||||
|
||||
|
||||
@register_model_view(CatalogZone, "edit")
|
||||
class CatalogZoneEditView(generic.ObjectEditView):
|
||||
queryset = CatalogZone.objects.select_related("view")
|
||||
form = CatalogZoneForm
|
||||
|
||||
|
||||
@register_model_view(CatalogZoneMember, "list", path="", detail=False)
|
||||
class CatalogZoneMemberListView(generic.ObjectListView):
|
||||
queryset = CatalogZoneMember.objects.select_related(
|
||||
"zone", "catalog_zone__view"
|
||||
).order_by("catalog_zone__view__name", "name")
|
||||
table = CatalogZoneMemberTable
|
||||
filterset = CatalogZoneMemberFilterSet
|
||||
filterset_form = CatalogZoneMemberFilterForm
|
||||
actions = ()
|
||||
|
||||
|
||||
@register_model_view(CatalogZoneMember)
|
||||
class CatalogZoneMemberView(generic.ObjectView):
|
||||
queryset = CatalogZoneMember.objects.select_related(
|
||||
"zone", "catalog_zone__view"
|
||||
)
|
||||
actions = ()
|
||||
|
||||
|
||||
@register_model_view(SeenTransferClient, "list", path="", detail=False)
|
||||
class SeenTransferClientListView(generic.ObjectListView):
|
||||
queryset = SeenTransferClient.objects.select_related("view").order_by("source_ip")
|
||||
table = SeenTransferClientTable
|
||||
filterset = SeenTransferClientFilterSet
|
||||
filterset_form = SeenTransferClientFilterForm
|
||||
actions = ()
|
||||
|
||||
|
||||
@register_model_view(SeenTransferClient)
|
||||
class SeenTransferClientView(generic.ObjectView):
|
||||
queryset = SeenTransferClient.objects.select_related("view")
|
||||
actions = ()
|
||||
-645
@@ -1,645 +0,0 @@
|
||||
[MAIN]
|
||||
|
||||
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||
# 3 compatible code, which means that the block might have code that exists
|
||||
# only in one or another interpreter, leading to false positives when analysed.
|
||||
analyse-fallback-blocks=no
|
||||
|
||||
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
|
||||
# in a server-like mode.
|
||||
clear-cache-post-run=no
|
||||
|
||||
# Load and enable all available extensions. Use --list-extensions to see a list
|
||||
# all available extensions.
|
||||
#enable-all-extensions=
|
||||
|
||||
# In error mode, messages with a category besides ERROR or FATAL are
|
||||
# suppressed, and no reports are done by default. Error mode is compatible with
|
||||
# disabling specific errors.
|
||||
#errors-only=
|
||||
|
||||
# Always return a 0 (non-error) status code, even if lint errors are found.
|
||||
# This is primarily useful in continuous integration scripts.
|
||||
#exit-zero=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code.
|
||||
extension-pkg-allow-list=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
|
||||
# for backward compatibility.)
|
||||
extension-pkg-whitelist=
|
||||
|
||||
# Return non-zero exit code if any of these messages/categories are detected,
|
||||
# even if score is above --fail-under value. Syntax same as enable. Messages
|
||||
# specified are enabled, while categories only check already-enabled messages.
|
||||
fail-on=
|
||||
|
||||
# Specify a score threshold under which the program will exit with error.
|
||||
fail-under=10
|
||||
|
||||
# Interpret the stdin as a python script, whose filename needs to be passed as
|
||||
# the module_or_package argument.
|
||||
#from-stdin=
|
||||
|
||||
# Files or directories to be skipped. They should be base names, not paths.
|
||||
ignore=CVS
|
||||
|
||||
# Add files or directories matching the regular expressions patterns to the
|
||||
# ignore-list. The regex matches against paths and can be in Posix or Windows
|
||||
# format. Because '\\' represents the directory delimiter on Windows systems,
|
||||
# it can't be used as an escape character.
|
||||
ignore-paths=
|
||||
|
||||
# Files or directories matching the regular expression patterns are skipped.
|
||||
# The regex matches against base names, not paths. The default value ignores
|
||||
# Emacs file locks
|
||||
ignore-patterns=^\.#
|
||||
|
||||
# List of module names for which member attributes should not be checked and
|
||||
# will not be imported (useful for modules/projects where namespaces are
|
||||
# manipulated during runtime and thus existing member attributes cannot be
|
||||
# deduced by static analysis). It supports qualified module names, as well as
|
||||
# Unix pattern matching.
|
||||
ignored-modules=
|
||||
|
||||
# Python code to execute, usually for sys.path manipulation such as
|
||||
# pygtk.require().
|
||||
#init-hook=
|
||||
|
||||
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
||||
# number of processors available to use, and will cap the count on Windows to
|
||||
# avoid hangs.
|
||||
jobs=1
|
||||
|
||||
# Control the amount of potential inferred values when inferring a single
|
||||
# object. This can help the performance when dealing with large functions or
|
||||
# complex, nested conditions.
|
||||
limit-inference-results=100
|
||||
|
||||
# List of plugins (as comma separated values of python module names) to load,
|
||||
# usually to register additional checkers.
|
||||
load-plugins=
|
||||
|
||||
# Pickle collected data for later comparisons.
|
||||
persistent=yes
|
||||
|
||||
# Resolve imports to .pyi stubs if available. May reduce no-member messages and
|
||||
# increase not-an-iterable messages.
|
||||
prefer-stubs=no
|
||||
|
||||
# Minimum Python version to use for version dependent checks. Will default to
|
||||
# the version used to run pylint.
|
||||
py-version=3.13
|
||||
|
||||
# Discover python modules and packages in the file system subtree.
|
||||
recursive=no
|
||||
|
||||
# Add paths to the list of the source roots. Supports globbing patterns. The
|
||||
# source root is an absolute path or a path relative to the current working
|
||||
# directory used to determine a package namespace for modules located under the
|
||||
# source root.
|
||||
source-roots=
|
||||
|
||||
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
||||
# user-friendly hints instead of false-positive error messages.
|
||||
suggestion-mode=yes
|
||||
|
||||
# Allow loading of arbitrary C extensions. Extensions are imported into the
|
||||
# active Python interpreter and may run arbitrary code.
|
||||
unsafe-load-any-extension=no
|
||||
|
||||
# In verbose mode, extra non-checker-related info will be displayed.
|
||||
#verbose=
|
||||
|
||||
|
||||
[BASIC]
|
||||
|
||||
# Naming style matching correct argument names.
|
||||
#argument-naming-style=snake_case
|
||||
argument-naming-style=camelCase
|
||||
|
||||
# Regular expression matching correct argument names. Overrides argument-
|
||||
# naming-style. If left empty, argument names will be checked with the set
|
||||
# naming style.
|
||||
#argument-rgx=
|
||||
|
||||
# Naming style matching correct attribute names.
|
||||
attr-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct attribute names. Overrides attr-naming-
|
||||
# style. If left empty, attribute names will be checked with the set naming
|
||||
# style.
|
||||
#attr-rgx=
|
||||
|
||||
# Bad variable names which should always be refused, separated by a comma.
|
||||
bad-names=foo,
|
||||
bar,
|
||||
baz,
|
||||
toto,
|
||||
tutu,
|
||||
tata
|
||||
|
||||
# Bad variable names regexes, separated by a comma. If names match any regex,
|
||||
# they will always be refused
|
||||
bad-names-rgxs=
|
||||
|
||||
# Naming style matching correct class attribute names.
|
||||
class-attribute-naming-style=any
|
||||
|
||||
# Regular expression matching correct class attribute names. Overrides class-
|
||||
# attribute-naming-style. If left empty, class attribute names will be checked
|
||||
# with the set naming style.
|
||||
#class-attribute-rgx=
|
||||
|
||||
# Naming style matching correct class constant names.
|
||||
class-const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct class constant names. Overrides class-
|
||||
# const-naming-style. If left empty, class constant names will be checked with
|
||||
# the set naming style.
|
||||
#class-const-rgx=
|
||||
|
||||
# Naming style matching correct class names.
|
||||
class-naming-style=PascalCase
|
||||
|
||||
# Regular expression matching correct class names. Overrides class-naming-
|
||||
# style. If left empty, class names will be checked with the set naming style.
|
||||
#class-rgx=
|
||||
|
||||
# Naming style matching correct constant names.
|
||||
const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct constant names. Overrides const-naming-
|
||||
# style. If left empty, constant names will be checked with the set naming
|
||||
# style.
|
||||
#const-rgx=
|
||||
|
||||
# Minimum line length for functions/classes that require docstrings, shorter
|
||||
# ones are exempt.
|
||||
docstring-min-length=-1
|
||||
|
||||
# Naming style matching correct function names.
|
||||
function-naming-style=camelCase
|
||||
|
||||
# Regular expression matching correct function names. Overrides function-
|
||||
# naming-style. If left empty, function names will be checked with the set
|
||||
# naming style.
|
||||
#function-rgx=
|
||||
|
||||
# Good variable names which should always be accepted, separated by a comma.
|
||||
good-names=i,
|
||||
j,
|
||||
k,
|
||||
ex,
|
||||
Run,
|
||||
_
|
||||
|
||||
# Good variable names regexes, separated by a comma. If names match any regex,
|
||||
# they will always be accepted
|
||||
good-names-rgxs=
|
||||
|
||||
# Include a hint for the correct naming format with invalid-name.
|
||||
include-naming-hint=no
|
||||
|
||||
# Naming style matching correct inline iteration names.
|
||||
inlinevar-naming-style=any
|
||||
|
||||
# Regular expression matching correct inline iteration names. Overrides
|
||||
# inlinevar-naming-style. If left empty, inline iteration names will be checked
|
||||
# with the set naming style.
|
||||
#inlinevar-rgx=
|
||||
|
||||
# Naming style matching correct method names.
|
||||
method-naming-style=camelCase
|
||||
|
||||
# Regular expression matching correct method names. Overrides method-naming-
|
||||
# style. If left empty, method names will be checked with the set naming style.
|
||||
#method-rgx=
|
||||
|
||||
# Naming style matching correct module names.
|
||||
module-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct module names. Overrides module-naming-
|
||||
# style. If left empty, module names will be checked with the set naming style.
|
||||
#module-rgx=
|
||||
|
||||
# Colon-delimited sets of names that determine each other's naming style when
|
||||
# the name regexes allow several styles.
|
||||
name-group=
|
||||
|
||||
# Regular expression which should only match function or class names that do
|
||||
# not require a docstring.
|
||||
no-docstring-rgx=^_
|
||||
|
||||
# List of decorators that produce properties, such as abc.abstractproperty. Add
|
||||
# to this list to register other decorators that produce valid properties.
|
||||
# These decorators are taken in consideration only for invalid-name.
|
||||
property-classes=abc.abstractproperty
|
||||
|
||||
# Regular expression matching correct type alias names. If left empty, type
|
||||
# alias names will be checked with the set naming style.
|
||||
#typealias-rgx=
|
||||
|
||||
# Regular expression matching correct type variable names. If left empty, type
|
||||
# variable names will be checked with the set naming style.
|
||||
#typevar-rgx=
|
||||
|
||||
# Naming style matching correct variable names.
|
||||
variable-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct variable names. Overrides variable-
|
||||
# naming-style. If left empty, variable names will be checked with the set
|
||||
# naming style.
|
||||
#variable-rgx=
|
||||
|
||||
|
||||
[CLASSES]
|
||||
|
||||
# Warn about protected attribute access inside special methods
|
||||
check-protected-access-in-special-methods=no
|
||||
|
||||
# List of method names used to declare (i.e. assign) instance attributes.
|
||||
defining-attr-methods=__init__,
|
||||
__new__,
|
||||
setUp,
|
||||
asyncSetUp,
|
||||
__post_init__
|
||||
|
||||
# List of member names, which should be excluded from the protected access
|
||||
# warning.
|
||||
exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit
|
||||
|
||||
# List of valid names for the first argument in a class method.
|
||||
valid-classmethod-first-arg=cls
|
||||
|
||||
# List of valid names for the first argument in a metaclass class method.
|
||||
valid-metaclass-classmethod-first-arg=mcs
|
||||
|
||||
|
||||
[DESIGN]
|
||||
|
||||
# List of regular expressions of class ancestor names to ignore when counting
|
||||
# public methods (see R0903)
|
||||
exclude-too-few-public-methods=
|
||||
|
||||
# List of qualified class names to ignore when counting class parents (see
|
||||
# R0901)
|
||||
ignored-parents=
|
||||
|
||||
# Maximum number of arguments for function / method.
|
||||
max-args=5
|
||||
|
||||
# Maximum number of attributes for a class (see R0902).
|
||||
max-attributes=7
|
||||
|
||||
# Maximum number of boolean expressions in an if statement (see R0916).
|
||||
max-bool-expr=5
|
||||
|
||||
# Maximum number of branch for function / method body.
|
||||
max-branches=12
|
||||
|
||||
# Maximum number of locals for function / method body.
|
||||
max-locals=15
|
||||
|
||||
# Maximum number of parents for a class (see R0901).
|
||||
max-parents=7
|
||||
|
||||
# Maximum number of public methods for a class (see R0904).
|
||||
max-public-methods=20
|
||||
|
||||
# Maximum number of return / yield for function / method body.
|
||||
max-returns=6
|
||||
|
||||
# Maximum number of statements in function / method body.
|
||||
max-statements=50
|
||||
|
||||
# Minimum number of public methods for a class (see R0903).
|
||||
min-public-methods=2
|
||||
|
||||
|
||||
[EXCEPTIONS]
|
||||
|
||||
# Exceptions that will emit a warning when caught.
|
||||
overgeneral-exceptions=builtins.BaseException,builtins.Exception
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||
expected-line-ending-format=
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Number of spaces of indent required inside a hanging or continued line.
|
||||
indent-after-paren=4
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=120
|
||||
|
||||
# Maximum number of lines in a module.
|
||||
max-module-lines=1000
|
||||
|
||||
# Allow the body of a class to be on the same line as the declaration if body
|
||||
# contains single statement.
|
||||
single-line-class-stmt=no
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# List of modules that can be imported at any level, not just the top level
|
||||
# one.
|
||||
allow-any-import-level=
|
||||
|
||||
# Allow explicit reexports by alias from a package __init__.
|
||||
allow-reexport-from-package=no
|
||||
|
||||
# Allow wildcard imports from modules that define __all__.
|
||||
allow-wildcard-with-all=no
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma.
|
||||
deprecated-modules=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of external dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
ext-import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of all (i.e. internal and
|
||||
# external) dependencies to the given file (report RP0402 must not be
|
||||
# disabled).
|
||||
import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of internal dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
int-import-graph=
|
||||
|
||||
# Force import order to recognize a module as part of the standard
|
||||
# compatibility libraries.
|
||||
known-standard-library=
|
||||
|
||||
# Force import order to recognize a module as part of a third party library.
|
||||
known-third-party=enchant
|
||||
|
||||
# Couples of modules and preferred modules, separated by a comma.
|
||||
preferred-modules=
|
||||
|
||||
|
||||
[LOGGING]
|
||||
|
||||
# The type of string formatting that logging methods do. `old` means using %
|
||||
# formatting, `new` is for `{}` formatting.
|
||||
logging-format-style=old
|
||||
|
||||
# Logging modules to check that the string format arguments are in logging
|
||||
# function parameter format.
|
||||
logging-modules=logging
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
|
||||
# UNDEFINED.
|
||||
confidence=HIGH,
|
||||
CONTROL_FLOW,
|
||||
INFERENCE,
|
||||
INFERENCE_FAILURE,
|
||||
UNDEFINED
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifiers separated by comma (,) or put this
|
||||
# option multiple times (only on the command line, not in the configuration
|
||||
# file where it should appear only once). You can also use "--disable=all" to
|
||||
# disable everything first and then re-enable specific checks. For example, if
|
||||
# you want to run only the similarities checker, you can use "--disable=all
|
||||
# --enable=similarities". If you want to run only the classes checker, but have
|
||||
# no Warning level messages displayed, use "--disable=all --enable=classes
|
||||
# --disable=W".
|
||||
disable=raw-checker-failed,
|
||||
bad-inline-option,
|
||||
locally-disabled,
|
||||
file-ignored,
|
||||
suppressed-message,
|
||||
useless-suppression,
|
||||
deprecated-pragma,
|
||||
use-symbolic-message-instead,
|
||||
use-implicit-booleaness-not-comparison-to-string,
|
||||
use-implicit-booleaness-not-comparison-to-zero
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once). See also the "--disable" option for examples.
|
||||
enable=
|
||||
|
||||
|
||||
[METHOD_ARGS]
|
||||
|
||||
# List of qualified names (i.e., library.method) which require a timeout
|
||||
# parameter e.g. 'requests.api.get,requests.api.post'
|
||||
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
notes=FIXME,
|
||||
XXX,
|
||||
TODO
|
||||
|
||||
# Regular expression of note tags to take in consideration.
|
||||
notes-rgx=
|
||||
|
||||
|
||||
[REFACTORING]
|
||||
|
||||
# Maximum number of nested blocks for function / method body
|
||||
max-nested-blocks=5
|
||||
|
||||
# Complete name of functions that never returns. When checking for
|
||||
# inconsistent-return-statements if a never returning function is called then
|
||||
# it will be considered as an explicit return statement and no message will be
|
||||
# printed.
|
||||
never-returning-functions=sys.exit,argparse.parse_error
|
||||
|
||||
# Let 'consider-using-join' be raised when the separator to join on would be
|
||||
# non-empty (resulting in expected fixes of the type: ``"- " + " -
|
||||
# ".join(items)``)
|
||||
suggest-join-with-non-empty-separator=yes
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Python expression which should return a score less than or equal to 10. You
|
||||
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
|
||||
# 'convention', and 'info' which contain the number of messages in each
|
||||
# category, as well as 'statement' which is the total number of statements
|
||||
# analyzed. This score is used by the global evaluation report (RP0004).
|
||||
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details.
|
||||
msg-template=
|
||||
|
||||
# Set the output format. Available formats are: text, parseable, colorized,
|
||||
# json2 (improved json format), json (old json format) and msvs (visual
|
||||
# studio). You can also give a reporter class, e.g.
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
#output-format=
|
||||
|
||||
# Tells whether to display a full report or only the messages.
|
||||
reports=no
|
||||
|
||||
# Activate the evaluation score.
|
||||
score=yes
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Comments are removed from the similarity computation
|
||||
ignore-comments=yes
|
||||
|
||||
# Docstrings are removed from the similarity computation
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Imports are removed from the similarity computation
|
||||
ignore-imports=yes
|
||||
|
||||
# Signatures are removed from the similarity computation
|
||||
ignore-signatures=yes
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=4
|
||||
|
||||
|
||||
[SPELLING]
|
||||
|
||||
# Limits count of emitted suggestions for spelling mistakes.
|
||||
max-spelling-suggestions=4
|
||||
|
||||
# Spelling dictionary name. No available dictionaries : You need to install
|
||||
# both the python package and the system dependency for enchant to work.
|
||||
spelling-dict=
|
||||
|
||||
# List of comma separated words that should be considered directives if they
|
||||
# appear at the beginning of a comment and should not be checked.
|
||||
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
|
||||
|
||||
# List of comma separated words that should not be checked.
|
||||
spelling-ignore-words=
|
||||
|
||||
# A path to a file that contains the private dictionary; one word per line.
|
||||
spelling-private-dict-file=
|
||||
|
||||
# Tells whether to store unknown words to the private dictionary (see the
|
||||
# --spelling-private-dict-file option) instead of raising a message.
|
||||
spelling-store-unknown-words=no
|
||||
|
||||
|
||||
[STRING]
|
||||
|
||||
# This flag controls whether inconsistent-quotes generates a warning when the
|
||||
# character used as a quote delimiter is used inconsistently within a module.
|
||||
check-quote-consistency=no
|
||||
|
||||
# This flag controls whether the implicit-str-concat should generate a warning
|
||||
# on implicit string concatenation in sequences defined over several lines.
|
||||
check-str-concat-over-line-jumps=no
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# List of decorators that produce context managers, such as
|
||||
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||
# produce valid context managers.
|
||||
contextmanager-decorators=contextlib.contextmanager
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=
|
||||
|
||||
# Tells whether to warn about missing members when the owner of the attribute
|
||||
# is inferred to be None.
|
||||
ignore-none=yes
|
||||
|
||||
# This flag controls whether pylint should warn about no-member and similar
|
||||
# checks whenever an opaque object is returned when inferring. The inference
|
||||
# can return multiple potential results while evaluating a Python object, but
|
||||
# some branches might not be evaluated, which results in partial inference. In
|
||||
# that case, it might be useful to still emit no-member and other checks for
|
||||
# the rest of the inferred objects.
|
||||
ignore-on-opaque-inference=yes
|
||||
|
||||
# List of symbolic message names to ignore for Mixin members.
|
||||
ignored-checks-for-mixins=no-member,
|
||||
not-async-context-manager,
|
||||
not-context-manager,
|
||||
attribute-defined-outside-init
|
||||
|
||||
# List of class names for which member attributes should not be checked (useful
|
||||
# for classes with dynamically set attributes). This supports the use of
|
||||
# qualified names.
|
||||
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
|
||||
|
||||
# Show a hint with possible names when a member name was not found. The aspect
|
||||
# of finding the hint is based on edit distance.
|
||||
missing-member-hint=yes
|
||||
|
||||
# The minimum edit distance a name should have in order to be considered a
|
||||
# similar match for a missing member name.
|
||||
missing-member-hint-distance=1
|
||||
|
||||
# The total number of similar names that should be taken in consideration when
|
||||
# showing a hint for a missing member.
|
||||
missing-member-max-choices=1
|
||||
|
||||
# Regex pattern to define which classes are considered mixins.
|
||||
mixin-class-rgx=.*[Mm]ixin
|
||||
|
||||
# List of decorators that change the signature of a decorated function.
|
||||
signature-mutators=
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid defining new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
# Tells whether unused global variables should be treated as a violation.
|
||||
allow-global-unused-variables=yes
|
||||
|
||||
# List of names allowed to shadow builtins
|
||||
allowed-redefined-builtins=
|
||||
|
||||
# List of strings which can identify a callback function by name. A callback
|
||||
# name must start or end with one of those strings.
|
||||
callbacks=cb_,
|
||||
_cb
|
||||
|
||||
# A regular expression matching the name of dummy variables (i.e. expected to
|
||||
# not be used).
|
||||
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||
|
||||
# Argument names that match this expression will be ignored.
|
||||
ignored-argument-names=_.*|^ignored_|^unused_
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# List of qualified module names which can have objects that can redefine
|
||||
# builtins.
|
||||
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
||||
+24
-7
@@ -3,27 +3,44 @@ requires = ["setuptools>=61", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "netbox-plugin-bind-provisioner"
|
||||
name = "netbox-plugin-dns-bridge"
|
||||
dynamic = ["version"]
|
||||
description = "A Bind provisioning plugin that uses netbox_dns for its data source"
|
||||
description = "A bridge between netbox-plugin-dns and your DNS infrastructure."
|
||||
authors = [
|
||||
{ name = "Sven Luethi" },
|
||||
]
|
||||
license = { text = "GPL-2.0" }
|
||||
license = { file = "LICENSE.md" }
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.7"
|
||||
dependencies = ["netbox-plugin-dns"]
|
||||
dependencies = [
|
||||
"netbox-plugin-dns>=1.5.0",
|
||||
"dnspython>=2.8.0"
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = [
|
||||
"pytest>=8.0",
|
||||
"pytest-django>=4.8",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
DJANGO_SETTINGS_MODULE = "netbox.settings"
|
||||
python_files = ["test_*.py"]
|
||||
testpaths = ["netbox_dns_bridge/tests"]
|
||||
|
||||
[tool.setuptools]
|
||||
include-package-data = true
|
||||
zip-safe = false
|
||||
package-dir = { "" = "src" }
|
||||
package-dir = { "" = "." }
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
netbox_dns_bridge = ["templates/**/*.html"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
where = ["."]
|
||||
|
||||
[tool.setuptools.dynamic]
|
||||
version = { attr = "netbox_plugin_bind_provisioner.__version__" }
|
||||
version = { attr = "netbox_dns_bridge.__version__" }
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/Suraxius/netbox-plugin-bind-provisioner"
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
netbox-plugin-dns>=1.2.0
|
||||
dnspython>=2.8.0
|
||||
@@ -1,37 +0,0 @@
|
||||
import logging
|
||||
from netbox.plugins import PluginConfig
|
||||
from django.db import models
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.dispatch import receiver
|
||||
from django.conf import settings
|
||||
|
||||
__version__ = "1.0.4"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG, # Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", # Log format
|
||||
datefmt="%Y-%m-%d %H:%M:%S", # Date format for timestamps
|
||||
)
|
||||
|
||||
|
||||
class BindProvisionerConfig(PluginConfig):
|
||||
name = "netbox_plugin_bind_provisioner"
|
||||
verbose_name = "Netbox Bind Provisioner"
|
||||
description = "Provisions Zones to a Bind Server configured as hidden master"
|
||||
version = __version__
|
||||
author = "Sven Luethi"
|
||||
author_email = "sven.luethi@everyware.ch"
|
||||
base_url = "bind_provisioner"
|
||||
|
||||
def ready(self):
|
||||
self.settings = settings.PLUGINS_CONFIG.get(self.name, None)
|
||||
if not self.settings:
|
||||
raise RuntimeError(
|
||||
f"{self.name}: Plugin {self.verbose_name} failed to initialize due to missing settings. Terminating Netbox."
|
||||
)
|
||||
|
||||
|
||||
config = BindProvisionerConfig
|
||||
default_app_config = ".apps.NetboxBindProvisionerConfig"
|
||||
@@ -1,744 +0,0 @@
|
||||
import logging
|
||||
import socketserver
|
||||
import os
|
||||
#import re
|
||||
import threading
|
||||
import dns.query
|
||||
import dns.message
|
||||
import dns.tsigkeyring
|
||||
import dns.name
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.rdtypes
|
||||
import dns.exception
|
||||
import dns.renderer
|
||||
|
||||
# from hashlib import sha256
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.conf import settings
|
||||
from django.utils import timezone
|
||||
from netbox_dns.models import Zone, Record, View
|
||||
from netbox_dns.choices import ZoneStatusChoices, RecordStatusChoices
|
||||
from datetime import datetime
|
||||
from netbox_plugin_bind_provisioner.models import IntegerKeyValueSetting
|
||||
|
||||
logger = logging.getLogger("bind-transfer-endpoint")
|
||||
|
||||
|
||||
class CatalogZone:
|
||||
lock = threading.Lock()
|
||||
_serial_max = 0xFFFFFFFF
|
||||
_serial_obj = None
|
||||
_previous_last_zone_update = None
|
||||
|
||||
# Following function loads the last serial from the DB. No return value
|
||||
# but it sets the setting "catalog_serial" or terminates the plugin on failure.
|
||||
@classmethod
|
||||
def initSerial(cls):
|
||||
try:
|
||||
cls._serial_obj = IntegerKeyValueSetting.objects.get(
|
||||
key="catalog-zone-soa-serial"
|
||||
)
|
||||
logger.debug(
|
||||
f"Catalog zone SOA serial number {cls._serial_obj.value} loaded from database"
|
||||
)
|
||||
except IntegerKeyValueSetting.DoesNotExist:
|
||||
cls._serial_obj = IntegerKeyValueSetting.objects.create(
|
||||
key="catalog-zone-soa-serial", value=1
|
||||
)
|
||||
logger.debug(
|
||||
f"Catalog zone SOA serial number was not set in the database. Set to {cls._serial_obj.value}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _incrementSerial(cls):
|
||||
if 0 < cls._serial_obj.value < cls._serial_max:
|
||||
cls._serial_obj.value += 1
|
||||
cls._serial_obj.save()
|
||||
else:
|
||||
logger.warn(
|
||||
f"Failed to incremenet catalog serial {cls._serial_obj.value}. Will overflow serial back to 1"
|
||||
)
|
||||
cls._serial_obj = 1
|
||||
cls._serial_obj.save()
|
||||
logger.debug(
|
||||
f"Catalog zone SOA serial number incremented to {_serial_obj.value}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create(cls, name, view_name):
|
||||
# Synchronize following across threads as TCP and UDP listener both use it.
|
||||
with cls.lock:
|
||||
# cls = self.__class__
|
||||
# datestamp = datetime.now().strftime("%y%m%d")
|
||||
# latest_zone = Zone.objects.filter().order_by("-last_updated").first()
|
||||
latest_zone = (
|
||||
Zone.objects.filter(status=ZoneStatusChoices.STATUS_ACTIVE)
|
||||
.order_by("-last_updated")
|
||||
.first()
|
||||
)
|
||||
|
||||
last_zone_update = getattr(latest_zone, "last_updated", None)
|
||||
|
||||
# Check if there was a zone updated since last call
|
||||
# If no zone was found previously then this will be false since (None != None) = False
|
||||
if cls._previous_last_zone_update != last_zone_update:
|
||||
if last_zone_update is not None:
|
||||
logger.debug(
|
||||
f"Zone {latest_zone.name} was updated in view {latest_zone.view.name}"
|
||||
)
|
||||
# Setting previous last zone update for next iteration:
|
||||
cls._previous_last_zone_update = last_zone_update
|
||||
cls._incrementSerial()
|
||||
|
||||
# Zone origin
|
||||
origin = dns.name.from_text(name, dns.name.root)
|
||||
|
||||
# Create a new empty zone
|
||||
zone = dns.zone.Zone(origin)
|
||||
zone.rdclass = dns.rdataclass.IN
|
||||
|
||||
# get zones from netbox
|
||||
nb_zones = Zone.objects.filter(
|
||||
view__name=view_name, status=ZoneStatusChoices.STATUS_ACTIVE
|
||||
)
|
||||
|
||||
ptr_base = dns.name.from_text("zones", origin)
|
||||
|
||||
for nb_zone in nb_zones:
|
||||
ttl = nb_zone.soa_ttl
|
||||
qname = dns.name.from_text(nb_zone.name, dns.name.root)
|
||||
# zone_id = sha256(qname.to_text().encode()).hexdigest()[0:63]
|
||||
zone_id = str(nb_zone.id)
|
||||
|
||||
# Create PTR record
|
||||
ptr_name = dns.name.from_text(zone_id, ptr_base)
|
||||
assert ptr_name.is_subdomain(origin)
|
||||
rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN, dns.rdatatype.PTR, qname.to_text()
|
||||
)
|
||||
rdataset = zone.find_rdataset(ptr_name, dns.rdatatype.PTR, create=True)
|
||||
rdataset.add(rdata, ttl)
|
||||
|
||||
# Configure DNSSec Policy for member Zone if DNSSec is enabled
|
||||
if nb_zone.dnssec_policy:
|
||||
# Configure policy
|
||||
rid = dns.name.from_text("group", ptr_name)
|
||||
policy_name = nb_zone.dnssec_policy.name.rstrip(" ")
|
||||
group_name = f"dnssec-policy-{policy_name}"
|
||||
rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN, dns.rdatatype.TXT, group_name
|
||||
)
|
||||
rdataset = zone.find_rdataset(rid, dns.rdatatype.TXT, create=True)
|
||||
rdataset.add(rdata, ttl)
|
||||
|
||||
## Configure dnssec status for member zone
|
||||
# status = str(1 if nb_zone.dnssec_policy else 0)
|
||||
# rid = dns.name.from_text("enabled.dnssec.ext", ptr_name)
|
||||
# rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT, status)
|
||||
# rdataset = zone.find_rdataset(rid, dns.rdatatype.TXT, create=True)
|
||||
# rdataset.add(rdata, ttl)
|
||||
|
||||
# SOA Record components
|
||||
ttl = 3600
|
||||
rclass = dns.rdataclass.IN
|
||||
rtype = dns.rdatatype.SOA
|
||||
mname = dns.name.root # dns.name.from_text("invalid.", origin)
|
||||
rname = dns.name.root # dns.name.from_text("contact.master.", origin)
|
||||
serial = cls._serial_obj.value
|
||||
refresh = 60
|
||||
retry = 10
|
||||
expire = 1209600
|
||||
minimum = 86400
|
||||
|
||||
# Create SOA rdata object
|
||||
soa_rdata = dns.rdata.from_text(
|
||||
rclass,
|
||||
rtype,
|
||||
f"{mname} {rname} {serial} {refresh} {retry} {expire} {minimum}",
|
||||
)
|
||||
|
||||
# Create Rdataset and add the RDATA to it
|
||||
soa_rdataset = dns.rdataset.Rdataset(rclass, rtype)
|
||||
soa_rdataset.add(soa_rdata, ttl)
|
||||
|
||||
# Add to the origin node in the zone
|
||||
node = zone.find_node(origin, create=True)
|
||||
node.rdatasets.append(soa_rdataset)
|
||||
|
||||
# NS record for catz.
|
||||
ns_name = dns.name.from_text("invalid", dns.name.root)
|
||||
ns_rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN, dns.rdatatype.NS, str(ns_name)
|
||||
)
|
||||
ns_rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.NS)
|
||||
ns_rdataset.add(ns_rdata, 86400)
|
||||
|
||||
# Add to node (catz. is the origin)
|
||||
ns_node = zone.find_node(origin, create=True)
|
||||
ns_node.rdatasets.append(ns_rdataset)
|
||||
|
||||
# TXT record for version.catz.
|
||||
version_name = dns.name.from_text(
|
||||
"version", origin
|
||||
) # relative to origin "catz."
|
||||
txt_rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT, '"2"')
|
||||
|
||||
txt_rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.TXT)
|
||||
txt_rdataset.add(txt_rdata, 86400)
|
||||
|
||||
# Add to node version.catz.
|
||||
txt_node = zone.find_node(version_name, create=True)
|
||||
txt_node.rdatasets.append(txt_rdataset)
|
||||
|
||||
return zone
|
||||
|
||||
@classmethod
|
||||
def importLegacySerialFile(cls, file_path):
|
||||
if os.path.exists(file_path):
|
||||
try:
|
||||
with open(file_path, "r") as f:
|
||||
serial = int(f.read().strip())
|
||||
cls._serial_obj.value = int(serial)
|
||||
cls._serial_obj.save()
|
||||
logger.info(
|
||||
f"Legacy catalog serial file {file_path} imported into database and file removed. Serial is now {serial}"
|
||||
)
|
||||
os.remove(file_path)
|
||||
except OSError as e:
|
||||
logger.error(
|
||||
f"Failed to import catalog zone serial from legacy file {file_path}"
|
||||
)
|
||||
|
||||
|
||||
class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
|
||||
# getZoneFromNB rewritten
|
||||
def getZoneFromNB(self, zone_name, view_name):
|
||||
# Find the zone
|
||||
try:
|
||||
nb_zone = Zone.objects.get(
|
||||
name=zone_name,
|
||||
view__name=view_name,
|
||||
status=ZoneStatusChoices.STATUS_ACTIVE,
|
||||
)
|
||||
except Zone.DoesNotExist:
|
||||
return None
|
||||
|
||||
# Build DNS zone
|
||||
zone = dns.zone.Zone(zone_name, dns.name.root)
|
||||
zone.rdclass = dns.rdataclass.IN
|
||||
|
||||
nb_records = Record.objects.filter(
|
||||
zone=nb_zone, status=RecordStatusChoices.STATUS_ACTIVE
|
||||
)
|
||||
|
||||
rdatasets_dict = {}
|
||||
|
||||
for record in nb_records:
|
||||
rdtype = dns.rdatatype.from_text(record.type)
|
||||
if not record.name:
|
||||
name = zone.origin
|
||||
elif record.name.endswith("."):
|
||||
name = dns.name.from_text(record.name)
|
||||
else:
|
||||
name = dns.name.from_text(record.name, origin=zone.origin)
|
||||
|
||||
# If the record has no TTL, use the zone default
|
||||
ttl = record.ttl or nb_zone.default_ttl
|
||||
|
||||
# Apply quoting for TXT records to stop tokanizer
|
||||
# from cutting it up:
|
||||
value = record.value
|
||||
if rdtype == dns.rdatatype.TXT:
|
||||
if value.startswith('"') and value.endswith('"'):
|
||||
value = value[1:-1].replace('" "', '').replace('"', '\"')
|
||||
|
||||
if len(value) > 255:
|
||||
# This is a bug fix for netbox. If netbox allowed for
|
||||
# an unquoted value to be larger then 255 characters,
|
||||
# it misunderstood everything behind a ; as a comment.
|
||||
chunks = ['"{}"'.format(value[i:i+255]) for i in range(0, len(value), 255)]
|
||||
value = " ".join(chunks)
|
||||
else:
|
||||
value = f'"{value}"'
|
||||
|
||||
rdata = dns.rdata.from_text(
|
||||
dns.rdataclass.IN,
|
||||
rdtype,
|
||||
value,
|
||||
relativize=False,
|
||||
origin=zone.origin,
|
||||
)
|
||||
|
||||
# Initialize rdataset if it doesn't exist for this name and type
|
||||
if name not in rdatasets_dict:
|
||||
rdatasets_dict[name] = {}
|
||||
if rdtype not in rdatasets_dict[name]:
|
||||
rdatasets_dict[name][rdtype] = dns.rdataset.Rdataset(
|
||||
dns.rdataclass.IN, rdtype
|
||||
)
|
||||
|
||||
# Add the rdata to the appropriate rdataset
|
||||
rdatasets_dict[name][rdtype].add(rdata, ttl)
|
||||
|
||||
# Now, add all rdatasets to the zone
|
||||
for name, rdtypes in rdatasets_dict.items():
|
||||
for rdtype, rdataset in rdtypes.items():
|
||||
# Ensure rdataset has the same rdclass as the zone
|
||||
if rdataset.rdclass != zone.rdclass:
|
||||
raise ValueError(
|
||||
f"rdataset rdclass {rdataset.rdclass} does not match zone rdclass {zone.rdclass}"
|
||||
)
|
||||
|
||||
# Check if the rdataset has any rdata before creating an RRset
|
||||
if not rdataset:
|
||||
logger.debug(f"Skipping empty rdataset for {name} {rdtype}")
|
||||
continue # Skip empty rdataset
|
||||
|
||||
# Replace the rdataset for the given name and type
|
||||
zone.replace_rdataset(name, rdataset)
|
||||
return zone
|
||||
|
||||
|
||||
def denyRequestBadTSIG(self, wire, tsig_error: dns.rcode):
|
||||
# Use empty keyring to parse TSIG without validating
|
||||
query = dns.message.from_wire(
|
||||
wire, keyring={}, ignore_trailing=True, continue_on_error=True
|
||||
)
|
||||
|
||||
# Make a response
|
||||
response = dns.message.make_response(query)
|
||||
response.set_rcode(dns.rcode.REFUSED)
|
||||
|
||||
if query.had_tsig:
|
||||
# Add TSIG with BADKEY, but do not sign (no MAC)
|
||||
response.use_tsig(
|
||||
keyring={}, # empty; we're not signing
|
||||
keyname=query.keyname,
|
||||
tsig_error=tsig_error,
|
||||
)
|
||||
self.denyRequest(query)
|
||||
|
||||
|
||||
class UDPRequestHandler(DNSBaseRequestHandler):
|
||||
def denyRequest(self, query, rcode: dns.rcode = dns.rcode.REFUSED):
|
||||
response = dns.message.make_response(query)
|
||||
response.set_rcode(rcode)
|
||||
wire = response.to_wire(multi=False)
|
||||
sock = self.request[1]
|
||||
sock.sendto(wire, self.client_address)
|
||||
|
||||
def handle(self):
|
||||
data, sock = self.request
|
||||
peer = self.client_address[0]
|
||||
query = None
|
||||
|
||||
try:
|
||||
query = dns.message.from_wire(
|
||||
data,
|
||||
keyring=self.server.keyring,
|
||||
continue_on_error=False,
|
||||
ignore_trailing=True,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Error parsing query: ", e)
|
||||
return
|
||||
|
||||
# Create a response
|
||||
response = dns.message.make_response(query)
|
||||
|
||||
# Set the Authoritative Answer flag
|
||||
response.flags |= dns.flags.AA
|
||||
|
||||
question = query.question[0]
|
||||
|
||||
# Get the queried record name and type:
|
||||
qname = question.name
|
||||
qtype = question.rdtype
|
||||
dname = qname.to_text().rstrip(".")
|
||||
|
||||
# Only process SOA queries
|
||||
if qtype != dns.rdatatype.SOA:
|
||||
logger.warning(
|
||||
f"Request denied from {peer}: Request was not SOA (Type: {qtype})"
|
||||
)
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
# Identify TSIG key used
|
||||
if not query.had_tsig:
|
||||
logger.warning(f"Request denied from {peer}: No TSIG key used")
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
key_name = query.keyname.canonicalize().to_text()
|
||||
|
||||
# Check if key matches a view
|
||||
nb_view = self.server.tsig_view_map.get(key_name)
|
||||
if not nb_view:
|
||||
logger.warning(
|
||||
f"Request denied from {peer}: {key_name} does not match a view"
|
||||
)
|
||||
self.denyRequestBadTSIG(wire, dns.rcode.BADKEY)
|
||||
return
|
||||
|
||||
# Check if catalog zone
|
||||
if dname == "catz" or dname == f"{nb_view.name}.catz":
|
||||
zone = CatalogZone.create(dname, nb_view.name)
|
||||
# If generic zone, retreive from NB
|
||||
else:
|
||||
zone = self.getZoneFromNB(dname, nb_view.name)
|
||||
# When zone was not found, let client know
|
||||
if not zone:
|
||||
logger.warning(f"Zone {nb_view.name}/{dname} not found in NB")
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
# Retrieve the existing SOA record from the Zone
|
||||
soa_rdataset = zone.get_rdataset(zone.origin, dns.rdatatype.SOA)
|
||||
|
||||
# We assume that the SOA rdataset has at least one record (it usually does).
|
||||
soa_rdata = soa_rdataset[0] # Get the first SOA record
|
||||
|
||||
# Now, create the rrset from the soa_rdata
|
||||
rrset = dns.rrset.from_rdata(zone.origin, soa_rdataset.ttl, soa_rdata)
|
||||
|
||||
# Append the rrset to the response's answer section
|
||||
response.answer.append(rrset)
|
||||
|
||||
# TSIG response
|
||||
if query.had_tsig:
|
||||
# If key was found in DB
|
||||
if query.keyname in self.server.keyring:
|
||||
response.use_tsig(
|
||||
self.server.keyring, keyname=query.keyname, original_id=query.id
|
||||
)
|
||||
else:
|
||||
# If key is unknown
|
||||
response.set_rcode(dns.rcode.REFUSED)
|
||||
# Generate new key for keyname provided
|
||||
# keyname = query.keyname
|
||||
# b64 = base64.b64encode(urandom(32)).decode("ascii")
|
||||
# newkey = dns.tsigkeyring.from_text({ keyname: b64 })
|
||||
response.use_tsig(
|
||||
self.server.keyring,
|
||||
keyname=query.keyname,
|
||||
tsig_error=dns.rcode.BADKEY,
|
||||
)
|
||||
|
||||
# Send back the response
|
||||
response_wire = response.to_wire(max_size=512)
|
||||
sock.sendto(response_wire, self.client_address)
|
||||
logger.debug(f"{peer} SOA {nb_view.name}/{dname}")
|
||||
|
||||
|
||||
class TCPRequestHandler(DNSBaseRequestHandler):
|
||||
def denyRequest(self, query, rcode: dns.rcode = dns.rcode.REFUSED):
|
||||
response = dns.message.make_response(query)
|
||||
response.set_rcode(rcode)
|
||||
wire = response.to_wire(multi=False)
|
||||
length = len(wire).to_bytes(2, byteorder="big")
|
||||
self.request.sendall(length + wire)
|
||||
|
||||
def handle(self):
|
||||
MAX_WIRE = 65535
|
||||
# MAX_WIRE = 2000 # For testing fragmentation
|
||||
RESERVED_TSIG = 300
|
||||
# create a var for setting the client ip in log messages
|
||||
peer = self.client_address[0]
|
||||
|
||||
try:
|
||||
# Receive the entire message....
|
||||
sock = self.request # TCP socket
|
||||
# Read 2-byte length prefix
|
||||
length_data = sock.recv(2)
|
||||
if len(length_data) < 2:
|
||||
return
|
||||
length = int.from_bytes(length_data, byteorder="big")
|
||||
wire = b""
|
||||
while len(wire) < length:
|
||||
chunk = sock.recv(length - len(wire))
|
||||
if not chunk:
|
||||
return # connection closed
|
||||
wire += chunk
|
||||
|
||||
# Parse the query
|
||||
query = None
|
||||
try:
|
||||
query = dns.message.from_wire(wire, keyring=self.server.keyring)
|
||||
# If TSIG signature doesnt match our key, refuse query:
|
||||
except dns.tsig.BadSignature as e:
|
||||
logger.warning(
|
||||
f"Request denied from {peer} failed TSIG verification: {e}"
|
||||
)
|
||||
self.denyRequestBadTSIG(wire, dns.rcode.BADSIG)
|
||||
return
|
||||
# If TSIG Key used is not in our list, refuse query:
|
||||
except dns.message.UnknownTSIGKey as e:
|
||||
logger.warning(f"Request denied from {peer} with bad TSIG key: {e}")
|
||||
self.denyRequestBadTSIG(wire, dns.rcode.BADKEY)
|
||||
return
|
||||
|
||||
# If there was no question in the query, refuse
|
||||
if len(query.question) != 1:
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
# Get the queried record name and type:
|
||||
qname = query.question[0].name
|
||||
qtype = query.question[0].rdtype
|
||||
|
||||
dname = qname.to_text().rstrip(".")
|
||||
|
||||
# Only process AXFR queries
|
||||
if qtype != dns.rdatatype.AXFR:
|
||||
# if qtype != dns.rdatatype.AXFR or qtype != dns.rdatatype.SOA:
|
||||
logger.warning(
|
||||
f"Request denied from {peer}: Request was not AXFR (Type: {qtype})"
|
||||
)
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
# Identify TSIG key used
|
||||
if not query.had_tsig:
|
||||
logger.warning(f"Request denied from {peer}: No TSIG key used")
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
key_name = query.keyname.canonicalize().to_text()
|
||||
|
||||
# Check if the key matches a view
|
||||
nb_view = self.server.tsig_view_map.get(key_name)
|
||||
if not nb_view:
|
||||
logger.warning(
|
||||
f"Request denied from {peer}: {key_name} does not match a view"
|
||||
)
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
# Check if catalog zone
|
||||
if dname == "catz" or dname == f"{nb_view.name}.catz":
|
||||
zone = CatalogZone.create(dname, nb_view.name)
|
||||
else:
|
||||
zone = self.getZoneFromNB(dname, nb_view.name)
|
||||
|
||||
# When zone was not found, let client know
|
||||
if not zone:
|
||||
logger.warning(f"Zone {dname} not found in view {nb_view.name}")
|
||||
self.denyRequest(query)
|
||||
return
|
||||
|
||||
# 1. Prepare SOA + RRsets (identical to your code)
|
||||
soa_rrset = None
|
||||
rrsets = []
|
||||
for name, rdataset in zone.iterate_rdatasets():
|
||||
if not name.is_absolute():
|
||||
name = name.concatenate(zone.origin)
|
||||
rrset = dns.rrset.from_rdata_list(name, rdataset.ttl, rdataset)
|
||||
if rdataset.rdtype == dns.rdatatype.SOA and soa_rrset is None:
|
||||
soa_rrset = rrset
|
||||
else:
|
||||
rrsets.append(rrset)
|
||||
|
||||
if soa_rrset is None:
|
||||
logger.error(f"Zone {dname} has no SOA — aborting AXFR")
|
||||
return
|
||||
|
||||
rrsets.insert(0, soa_rrset) # Opening SOA
|
||||
rrsets.append(soa_rrset) # Closing SOA
|
||||
|
||||
# 2. Create a Renderer for the first message
|
||||
r = dns.renderer.Renderer(
|
||||
id=query.id,
|
||||
flags=(dns.flags.QR | dns.flags.AA),
|
||||
max_size=MAX_WIRE,
|
||||
origin=None,
|
||||
)
|
||||
r.add_question(
|
||||
query.question[0].name,
|
||||
query.question[0].rdtype,
|
||||
query.question[0].rdclass,
|
||||
)
|
||||
|
||||
# 3. Loop through RRsets
|
||||
tsig_ctx = None
|
||||
for rrset in rrsets:
|
||||
# logger.debug(f"Iterating over rrset {rrset}. tsig_ctx: {tsig_ctx}")
|
||||
try:
|
||||
# logger.debug(f"Adding {rrset} to renderer object")
|
||||
r.add_rrset(dns.renderer.ANSWER, rrset)
|
||||
if r.max_size - len(r.output.getvalue()) < RESERVED_TSIG:
|
||||
raise dns.exception.TooBig("TSIG wont fit")
|
||||
except dns.exception.TooBig:
|
||||
# TSIG chain previous message
|
||||
r.write_header()
|
||||
tsig_ctx = r.add_multi_tsig(
|
||||
ctx=tsig_ctx,
|
||||
secret=self.server.keyring[query.keyname],
|
||||
keyname=query.keyname,
|
||||
fudge=300,
|
||||
id=query.id,
|
||||
tsig_error=0,
|
||||
other_data=b"",
|
||||
request_mac=r.mac if tsig_ctx else query.mac,
|
||||
)
|
||||
wire = r.get_wire()
|
||||
self.request.sendall(len(wire).to_bytes(2, "big") + wire)
|
||||
|
||||
# Start new renderer
|
||||
r = dns.renderer.Renderer(
|
||||
id=query.id,
|
||||
flags=(dns.flags.QR | dns.flags.AA),
|
||||
max_size=MAX_WIRE,
|
||||
origin=None,
|
||||
)
|
||||
r.add_question(
|
||||
query.question[0].name,
|
||||
query.question[0].rdtype,
|
||||
query.question[0].rdclass,
|
||||
)
|
||||
r.add_rrset(dns.renderer.ANSWER, rrset)
|
||||
|
||||
# 4. Final message with terminating TSIG
|
||||
r.write_header()
|
||||
# logger.debug(f"Final message. tsig_ctx: {tsig_ctx}")
|
||||
tsig_ctx = r.add_multi_tsig(
|
||||
ctx=tsig_ctx,
|
||||
secret=self.server.keyring[query.keyname],
|
||||
keyname=query.keyname,
|
||||
fudge=300,
|
||||
id=query.id,
|
||||
tsig_error=0,
|
||||
other_data=b"",
|
||||
# request_mac=r.mac if tsig_ctx else None,
|
||||
request_mac=r.mac if tsig_ctx else query.mac,
|
||||
)
|
||||
wire = r.get_wire()
|
||||
self.request.sendall(len(wire).to_bytes(2, "big") + wire)
|
||||
|
||||
# logger.debug(f"Zone transfer request for {nb_view.name}/{dname} from {peer}")
|
||||
logger.debug(f"{peer} AXFR {nb_view.name}/{dname}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling request from {peer}: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
class TCPDNSServer(socketserver.TCPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, server_address, handler_class, keyring, tsig_view_map):
|
||||
super().__init__(server_address, handler_class)
|
||||
self.keyring = keyring
|
||||
self.tsig_view_map = tsig_view_map
|
||||
|
||||
|
||||
class UDPDNSServer(socketserver.UDPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, server_address, handler_class, keyring, tsig_view_map):
|
||||
super().__init__(server_address, handler_class)
|
||||
self.keyring = keyring
|
||||
self.tsig_view_map = tsig_view_map
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Run a minimal AXFR DNS server using NetBox DNS plugin data"
|
||||
|
||||
def loadSettings(self):
|
||||
self.settings = settings.PLUGINS_CONFIG.get(
|
||||
"netbox_plugin_bind_provisioner", None
|
||||
)
|
||||
if not self.settings:
|
||||
raise RuntimeError(
|
||||
"Command failed to initialize due to missing settings. Terminating Netbox."
|
||||
)
|
||||
|
||||
self.tsig_keys = self.settings.get("tsig_keys", None)
|
||||
if not self.tsig_keys:
|
||||
raise RuntimeError("tsig_keys variable not set in plugin settings.")
|
||||
|
||||
# Load TSIG keys and map them to views
|
||||
def loadTSIGKeySettings(self):
|
||||
self.keyring = {}
|
||||
self.tsig_view_map = {}
|
||||
|
||||
for view_name, data in self.tsig_keys.items():
|
||||
raw_key_name = data.get("keyname")
|
||||
secret = data.get("secret")
|
||||
algorithm_str = data.get("algorithm", "hmac-sha256")
|
||||
|
||||
if not raw_key_name or not secret:
|
||||
logger.error(
|
||||
f"Skipping TSIG key for view {view_name}: missing keyname or secret."
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
nb_view = View.objects.get(name=view_name)
|
||||
except View.DoesNotExist:
|
||||
logger.error(
|
||||
f"Skipping TSIG key {raw_key_name}: view '{view_name}' not found."
|
||||
)
|
||||
continue
|
||||
|
||||
# Normalize key name to absolute DNS name
|
||||
key_name_obj = dns.name.from_text(raw_key_name, origin=None).canonicalize()
|
||||
if not key_name_obj.is_absolute():
|
||||
key_name_obj = key_name_obj.concatenate(dns.name.root)
|
||||
key_name_str = key_name_obj.to_text() # Will always include trailing do
|
||||
|
||||
self.keyring[key_name_obj] = dns.tsig.Key(
|
||||
name=key_name_obj, secret=secret, algorithm=algorithm_str
|
||||
)
|
||||
self.tsig_view_map[key_name_str] = nb_view
|
||||
logger.debug(f"Loaded TSIG key: {key_name_str} view: {nb_view.name}")
|
||||
|
||||
if not self.keyring:
|
||||
msg = "No TSIG keys found in database."
|
||||
logger.critical(msg)
|
||||
raise RuntimeError(msg)
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--port", type=int, default=5354, help="Port number to listen on"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--address", type=str, default="0.0.0.0", help="IP to bind to"
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
# Load parameters
|
||||
port = options["port"]
|
||||
address = options["address"]
|
||||
CatalogZone.initSerial()
|
||||
# Initialize settings
|
||||
self.loadSettings()
|
||||
# self.loadCatalogZoneSettings()
|
||||
self.loadTSIGKeySettings()
|
||||
# Following is temporary. Function and invocation can be deleted once v1.0 is reached.
|
||||
serial_file = self.settings.get("catalog_serial_file", None)
|
||||
if serial_file:
|
||||
CatalogZone.importLegacySerialFile(serial_file)
|
||||
|
||||
udp_server = UDPDNSServer(
|
||||
(address, port), UDPRequestHandler, self.keyring, self.tsig_view_map
|
||||
)
|
||||
tcp_server = TCPDNSServer(
|
||||
(address, port), TCPRequestHandler, self.keyring, self.tsig_view_map
|
||||
)
|
||||
|
||||
def run_udp_server(server):
|
||||
logger.debug(f"SOA endpoint listening on {address} udp/{port}")
|
||||
server.serve_forever()
|
||||
|
||||
udp_thread = threading.Thread(
|
||||
target=run_udp_server, args=(udp_server,), daemon=True
|
||||
)
|
||||
udp_thread.start()
|
||||
|
||||
logger.debug(f"AXFR endpoint listening on {address} tcp/{port}")
|
||||
tcp_server.serve_forever()
|
||||
@@ -1,51 +0,0 @@
|
||||
# Generated by Django 5.2.8 on 2025-11-23 14:36
|
||||
|
||||
import netbox.models.deletion
|
||||
import taggit.managers
|
||||
import utilities.json
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
("extras", "0133_make_cf_minmax_decimal"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="IntegerKeyValueSetting",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("created", models.DateTimeField(auto_now_add=True, null=True)),
|
||||
("last_updated", models.DateTimeField(auto_now=True, null=True)),
|
||||
(
|
||||
"custom_field_data",
|
||||
models.JSONField(
|
||||
blank=True,
|
||||
default=dict,
|
||||
encoder=utilities.json.CustomFieldJSONEncoder,
|
||||
),
|
||||
),
|
||||
("key", models.CharField(max_length=64)),
|
||||
("value", models.IntegerField()),
|
||||
(
|
||||
"tags",
|
||||
taggit.managers.TaggableManager(
|
||||
through="extras.TaggedItem", to="extras.Tag"
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"abstract": False,
|
||||
},
|
||||
bases=(netbox.models.deletion.DeleteMixin, models.Model),
|
||||
),
|
||||
]
|
||||
@@ -1,24 +0,0 @@
|
||||
from django.db import models
|
||||
import netbox.models
|
||||
import netbox_dns.models
|
||||
|
||||
|
||||
# class CatalogZoneSerial(models.Model):
|
||||
class IntegerKeyValueSetting(netbox.models.NetBoxModel):
|
||||
# view = models.ForeignKey(netbox_dns.models.View, on_delete=models.CASCADE)
|
||||
key = models.CharField(max_length=64)
|
||||
value = models.IntegerField()
|
||||
|
||||
def __str__(self):
|
||||
# return f'{self.view.name}: {self.serial}'
|
||||
return f"{self.key}: {str(self.value)}"
|
||||
|
||||
|
||||
# class TSIGKey(netbox.models.NetBoxModel):
|
||||
# view = models.ForeignKey(netbox_dns.models.View, on_delete=models.CASCADE)
|
||||
# name = models.CharField(max_length=256)
|
||||
# algorithm = models.CharField(max_length=25)
|
||||
# secret = models.CharField(max_length=50)
|
||||
#
|
||||
# def __str__(self):
|
||||
# return f'key "{self.name}" {{ algorithm {self.algorithm}; secret "{self.secret}"; }};'
|
||||
@@ -1,35 +0,0 @@
|
||||
import os
|
||||
import dns.zone
|
||||
import dns.rdatatype
|
||||
import dns.rdataclass
|
||||
import dns.exception
|
||||
import netbox_dns.models
|
||||
|
||||
def export_bind_zone_file(nb_zone: netbox_dns.models.Zone, file_path: str):
|
||||
|
||||
# Create dnspython zone object
|
||||
dp_zone = dns.zone.Zone(origin=dns.name.from_text(nb_zone.name))
|
||||
|
||||
for record in nb_zone.records.all():
|
||||
rname = record.name or "@"
|
||||
rdclass = dns.rdataclass.IN
|
||||
rdatatype = dns.rdatatype.from_text(record.type)
|
||||
|
||||
# Create rdata object
|
||||
rdata = dns.rdata.from_text(rdclass, rdatatype, record.value)
|
||||
|
||||
# Create rdataset
|
||||
rdataset = dns.rdataset.Rdataset(rdclass, rdatatype, record.ttl)
|
||||
rdataset.add(rdata)
|
||||
|
||||
# Add to zone
|
||||
node = dp_zone.find_node(rname, create=True)
|
||||
node.rdatasets.append(rdataset)
|
||||
|
||||
# Write zone to file in BIND format
|
||||
try:
|
||||
with open(file_path, "w") as f:
|
||||
dp_zone.to_file(f, sorted=True)
|
||||
except IOError as e:
|
||||
raise IOError(f"Failed to write zone file to {file_path}: {e}")
|
||||
|
||||
Reference in new issue
Block a user