diff --git a/.github/workflows/check-license-dependencies.yml b/.github/workflows/check-license-dependencies.yml
new file mode 100644
index 000000000..d3da427b0
--- /dev/null
+++ b/.github/workflows/check-license-dependencies.yml
@@ -0,0 +1,41 @@
+name: Check License Dependencies
+
+on:
+ push:
+ branches: [ main ]
+ pull_request:
+
+jobs:
+ check-dependencies:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check for problematic license dependencies
+ run: |
+ echo "Checking for dependencies on management/, signal/, and relay/ packages..."
+
+ # Find all directories except the problematic ones and system dirs
+ FOUND_ISSUES=0
+ find . -maxdepth 1 -type d -not -name "." -not -name "management" -not -name "signal" -not -name "relay" -not -name ".git*" | sort | while read dir; do
+ echo "=== Checking $dir ==="
+ # Search for problematic imports, excluding test files
+ RESULTS=$(grep -r "github.com/netbirdio/netbird/\(management\|signal\|relay\)" "$dir" --include="*.go" | grep -v "_test.go" | grep -v "test_" | grep -v "/test/" || true)
+ if [ ! -z "$RESULTS" ]; then
+ echo "❌ Found problematic dependencies:"
+ echo "$RESULTS"
+ FOUND_ISSUES=1
+ else
+ echo "✓ No problematic dependencies found"
+ fi
+ done
+ if [ $FOUND_ISSUES -eq 1 ]; then
+ echo ""
+ echo "❌ Found dependencies on management/, signal/, or relay/ packages"
+ echo "These packages will change license and should not be imported by client or shared code"
+ exit 1
+ else
+ echo ""
+ echo "✅ All license dependencies are clean"
+ fi
diff --git a/.github/workflows/golang-test-linux.yml b/.github/workflows/golang-test-linux.yml
index 0d7233c3e..0013833c4 100644
--- a/.github/workflows/golang-test-linux.yml
+++ b/.github/workflows/golang-test-linux.yml
@@ -259,7 +259,7 @@ jobs:
CGO_ENABLED=1 GOARCH=${{ matrix.arch }} \
go test ${{ matrix.raceFlag }} \
-exec 'sudo' \
- -timeout 10m ./relay/...
+ -timeout 10m ./relay/... ./shared/relay/...
test_signal:
name: "Signal / Unit"
@@ -309,7 +309,7 @@ jobs:
CGO_ENABLED=1 GOARCH=${{ matrix.arch }} \
go test \
-exec 'sudo' \
- -timeout 10m ./signal/...
+ -timeout 10m ./signal/... ./shared/signal/...
test_management:
name: "Management / Unit"
@@ -369,7 +369,7 @@ jobs:
CI=true \
go test -tags=devcert \
-exec "sudo --preserve-env=CI,NETBIRD_STORE_ENGINE" \
- -timeout 20m ./management/...
+ -timeout 20m ./management/... ./shared/management/...
benchmark:
name: "Management / Benchmark"
@@ -430,7 +430,7 @@ jobs:
CI=true \
go test -tags devcert -run=^$ -bench=. \
-exec 'sudo --preserve-env=CI,NETBIRD_STORE_ENGINE' \
- -timeout 20m ./management/...
+ -timeout 20m ./management/... ./shared/management/...
api_benchmark:
name: "Management / Benchmark (API)"
@@ -521,7 +521,7 @@ jobs:
-run=^$ \
-bench=. \
-exec 'sudo --preserve-env=CI,NETBIRD_STORE_ENGINE,GIT_BRANCH,GITHUB_RUN_ID' \
- -timeout 20m ./management/...
+ -timeout 20m ./management/... ./shared/management/...
api_integration_test:
name: "Management / Integration"
@@ -571,4 +571,4 @@ jobs:
CI=true \
go test -tags=integration \
-exec 'sudo --preserve-env=CI,NETBIRD_STORE_ENGINE' \
- -timeout 20m ./management/...
+ -timeout 20m ./management/... ./shared/management/...
\ No newline at end of file
diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml
index 77096790f..26f3b8f02 100644
--- a/.github/workflows/update-docs.yml
+++ b/.github/workflows/update-docs.yml
@@ -5,7 +5,7 @@ on:
tags:
- 'v*'
paths:
- - 'management/server/http/api/openapi.yml'
+ - 'shared/management/http/api/openapi.yml'
jobs:
trigger_docs_api_update:
diff --git a/LICENSE b/LICENSE
index 7cba76dfd..594691464 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,3 +1,6 @@
+This BSD‑3‑Clause license applies to all parts of the repository except for the directories management/, signal/ and relay/.
+Those directories are licensed under the GNU Affero General Public License version 3.0 (AGPLv3). See the respective LICENSE files inside each directory.
+
BSD 3-Clause License
Copyright (c) 2022 NetBird GmbH & AUTHORS
diff --git a/LICENSES/AGPL-3.0.txt b/LICENSES/AGPL-3.0.txt
new file mode 100644
index 000000000..be3f7b28e
--- /dev/null
+++ b/LICENSES/AGPL-3.0.txt
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ 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
+them 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey 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;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ 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.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+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.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ 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
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/LICENSES/BSD-3-Clause.txt b/LICENSES/BSD-3-Clause.txt
new file mode 100644
index 000000000..7cba76dfd
--- /dev/null
+++ b/LICENSES/BSD-3-Clause.txt
@@ -0,0 +1,13 @@
+BSD 3-Clause License
+
+Copyright (c) 2022 NetBird GmbH & AUTHORS
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/LICENSES/REUSE.toml b/LICENSES/REUSE.toml
new file mode 100644
index 000000000..68f32724c
--- /dev/null
+++ b/LICENSES/REUSE.toml
@@ -0,0 +1,6 @@
+[project]
+default_license = "BSD-3-Clause"
+
+[[files]]
+paths = ["management/", "signal/", "relay/"]
+license = "AGPL-3.0-only"
diff --git a/README.md b/README.md
index d5469c28b..ea7655869 100644
--- a/README.md
+++ b/README.md
@@ -134,5 +134,9 @@ In November 2022, NetBird joined the [StartUpSecure program](https://www.forschu
We use open-source technologies like [WireGuard®](https://www.wireguard.com/), [Pion ICE (WebRTC)](https://github.com/pion/ice), [Coturn](https://github.com/coturn/coturn), and [Rosenpass](https://rosenpass.eu). We very much appreciate the work these guys are doing and we'd greatly appreciate if you could support them in any way (e.g., by giving a star or a contribution).
### Legal
- _WireGuard_ and the _WireGuard_ logo are [registered trademarks](https://www.wireguard.com/trademark-policy/) of Jason A. Donenfeld.
+This repository is licensed under BSD-3-Clause license that applies to all parts of the repository except for the directories management/, signal/ and relay/.
+Those directories are licensed under the GNU Affero General Public License version 3.0 (AGPLv3). See the respective LICENSE files inside each directory.
+
+_WireGuard_ and the _WireGuard_ logo are [registered trademarks](https://www.wireguard.com/trademark-policy/) of Jason A. Donenfeld.
+
diff --git a/client/cmd/debug.go b/client/cmd/debug.go
index a79fd40d0..c59847717 100644
--- a/client/cmd/debug.go
+++ b/client/cmd/debug.go
@@ -17,7 +17,7 @@ import (
"github.com/netbirdio/netbird/client/proto"
"github.com/netbirdio/netbird/client/server"
nbstatus "github.com/netbirdio/netbird/client/status"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/upload-server/types"
)
@@ -77,11 +77,11 @@ var forCmd = &cobra.Command{
var persistenceCmd = &cobra.Command{
Use: "persistence [on|off]",
- Short: "Set network map memory persistence",
- Long: `Configure whether the latest network map should persist in memory. When enabled, the last known network map will be kept in memory.`,
+ Short: "Set sync response memory persistence",
+ Long: `Configure whether the latest sync response should persist in memory. When enabled, the last known sync response will be kept in memory.`,
Example: " netbird debug persistence on",
Args: cobra.ExactArgs(1),
- RunE: setNetworkMapPersistence,
+ RunE: setSyncResponsePersistence,
}
func debugBundle(cmd *cobra.Command, _ []string) error {
@@ -206,11 +206,11 @@ func runForDuration(cmd *cobra.Command, args []string) error {
time.Sleep(1 * time.Second)
- // Enable network map persistence before bringing the service up
- if _, err := client.SetNetworkMapPersistence(cmd.Context(), &proto.SetNetworkMapPersistenceRequest{
+ // Enable sync response persistence before bringing the service up
+ if _, err := client.SetSyncResponsePersistence(cmd.Context(), &proto.SetSyncResponsePersistenceRequest{
Enabled: true,
}); err != nil {
- return fmt.Errorf("failed to enable network map persistence: %v", status.Convert(err).Message())
+ return fmt.Errorf("failed to enable sync response persistence: %v", status.Convert(err).Message())
}
if _, err := client.Up(cmd.Context(), &proto.UpRequest{}); err != nil {
@@ -273,7 +273,7 @@ func runForDuration(cmd *cobra.Command, args []string) error {
return nil
}
-func setNetworkMapPersistence(cmd *cobra.Command, args []string) error {
+func setSyncResponsePersistence(cmd *cobra.Command, args []string) error {
conn, err := getClient(cmd)
if err != nil {
return err
@@ -290,14 +290,14 @@ func setNetworkMapPersistence(cmd *cobra.Command, args []string) error {
}
client := proto.NewDaemonServiceClient(conn)
- _, err = client.SetNetworkMapPersistence(cmd.Context(), &proto.SetNetworkMapPersistenceRequest{
+ _, err = client.SetSyncResponsePersistence(cmd.Context(), &proto.SetSyncResponsePersistenceRequest{
Enabled: persistence == "on",
})
if err != nil {
- return fmt.Errorf("failed to set network map persistence: %v", status.Convert(err).Message())
+ return fmt.Errorf("failed to set sync response persistence: %v", status.Convert(err).Message())
}
- cmd.Printf("Network map persistence set to: %s\n", persistence)
+ cmd.Printf("Sync response persistence set to: %s\n", persistence)
return nil
}
@@ -357,13 +357,13 @@ func formatDuration(d time.Duration) string {
}
func generateDebugBundle(config *profilemanager.Config, recorder *peer.Status, connectClient *internal.ConnectClient, logFilePath string) {
- var networkMap *mgmProto.NetworkMap
+ var syncResponse *mgmProto.SyncResponse
var err error
if connectClient != nil {
- networkMap, err = connectClient.GetLatestNetworkMap()
+ syncResponse, err = connectClient.GetLatestSyncResponse()
if err != nil {
- log.Warnf("Failed to get latest network map: %v", err)
+ log.Warnf("Failed to get latest sync response: %v", err)
}
}
@@ -371,7 +371,7 @@ func generateDebugBundle(config *profilemanager.Config, recorder *peer.Status, c
debug.GeneratorDependencies{
InternalConfig: config,
StatusRecorder: recorder,
- NetworkMap: networkMap,
+ SyncResponse: syncResponse,
LogFile: logFilePath,
},
debug.BundleConfig{
diff --git a/client/cmd/logout.go b/client/cmd/logout.go
new file mode 100644
index 000000000..071be5ca9
--- /dev/null
+++ b/client/cmd/logout.go
@@ -0,0 +1,57 @@
+package cmd
+
+import (
+ "context"
+ "fmt"
+ "os/user"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/netbirdio/netbird/client/proto"
+)
+
+var logoutCmd = &cobra.Command{
+ Use: "logout",
+ Short: "logout from the Netbird Management Service and delete peer",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ SetFlagsFromEnvVars(rootCmd)
+
+ cmd.SetOut(cmd.OutOrStdout())
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*7)
+ defer cancel()
+
+ conn, err := DialClientGRPCServer(ctx, daemonAddr)
+ if err != nil {
+ return fmt.Errorf("connect to daemon: %v", err)
+ }
+ defer conn.Close()
+
+ daemonClient := proto.NewDaemonServiceClient(conn)
+
+ req := &proto.LogoutRequest{}
+
+ if profileName != "" {
+ req.ProfileName = &profileName
+
+ currUser, err := user.Current()
+ if err != nil {
+ return fmt.Errorf("get current user: %v", err)
+ }
+ username := currUser.Username
+ req.Username = &username
+ }
+
+ if _, err := daemonClient.Logout(ctx, req); err != nil {
+ return fmt.Errorf("logout: %v", err)
+ }
+
+ cmd.Println("Logged out successfully")
+ return nil
+ },
+}
+
+func init() {
+ logoutCmd.PersistentFlags().StringVar(&profileName, profileNameFlag, "", profileNameDesc)
+}
diff --git a/client/cmd/profile.go b/client/cmd/profile.go
index f32e9c844..d420dcbd9 100644
--- a/client/cmd/profile.go
+++ b/client/cmd/profile.go
@@ -3,9 +3,8 @@ package cmd
import (
"context"
"fmt"
- "time"
-
"os/user"
+ "time"
"github.com/spf13/cobra"
@@ -22,10 +21,11 @@ var profileCmd = &cobra.Command{
}
var profileListCmd = &cobra.Command{
- Use: "list",
- Short: "list all profiles",
- Long: `List all available profiles in the Netbird client.`,
- RunE: listProfilesFunc,
+ Use: "list",
+ Short: "list all profiles",
+ Long: `List all available profiles in the Netbird client.`,
+ Aliases: []string{"ls"},
+ RunE: listProfilesFunc,
}
var profileAddCmd = &cobra.Command{
diff --git a/client/cmd/root.go b/client/cmd/root.go
index e3ce79964..86c76e6ab 100644
--- a/client/cmd/root.go
+++ b/client/cmd/root.go
@@ -127,12 +127,13 @@ func init() {
rootCmd.PersistentFlags().StringVar(&preSharedKey, preSharedKeyFlag, "", "Sets Wireguard PreSharedKey property. If set, then only peers that have the same key can communicate.")
rootCmd.PersistentFlags().StringVarP(&hostName, "hostname", "n", "", "Sets a custom hostname for the device")
rootCmd.PersistentFlags().BoolVarP(&anonymizeFlag, "anonymize", "A", false, "anonymize IP addresses and non-netbird.io domains in logs and status output")
- rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath, "(DEPRECATED) Netbird config file location")
+ rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath, "Overrides the default profile file location")
rootCmd.AddCommand(upCmd)
rootCmd.AddCommand(downCmd)
rootCmd.AddCommand(statusCmd)
rootCmd.AddCommand(loginCmd)
+ rootCmd.AddCommand(logoutCmd)
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(sshCmd)
rootCmd.AddCommand(networksCMD)
diff --git a/client/cmd/service_controller.go b/client/cmd/service_controller.go
index 6dc6bca9b..14a41e607 100644
--- a/client/cmd/service_controller.go
+++ b/client/cmd/service_controller.go
@@ -61,7 +61,7 @@ func (p *program) Start(svc service.Service) error {
}
}
- serverInstance := server.New(p.ctx, util.FindFirstLogPath(logFiles), profilesDisabled)
+ serverInstance := server.New(p.ctx, util.FindFirstLogPath(logFiles), configPath, profilesDisabled)
if err := serverInstance.Start(); err != nil {
log.Fatalf("failed to start daemon: %v", err)
}
diff --git a/client/cmd/service_installer.go b/client/cmd/service_installer.go
index be8a897dc..ac22000bd 100644
--- a/client/cmd/service_installer.go
+++ b/client/cmd/service_installer.go
@@ -41,6 +41,10 @@ func buildServiceArguments() []string {
args = append(args, "--management-url", managementURL)
}
+ if configPath != "" {
+ args = append(args, "--config", configPath)
+ }
+
for _, logFile := range logFiles {
args = append(args, "--log-file", logFile)
}
diff --git a/client/cmd/testutil_test.go b/client/cmd/testutil_test.go
index 5dbc8cd7f..47804a102 100644
--- a/client/cmd/testutil_test.go
+++ b/client/cmd/testutil_test.go
@@ -26,9 +26,9 @@ import (
clientProto "github.com/netbirdio/netbird/client/proto"
client "github.com/netbirdio/netbird/client/server"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
mgmt "github.com/netbirdio/netbird/management/server"
- sigProto "github.com/netbirdio/netbird/signal/proto"
+ sigProto "github.com/netbirdio/netbird/shared/signal/proto"
sig "github.com/netbirdio/netbird/signal/server"
)
@@ -134,7 +134,7 @@ func startClientDaemon(
s := grpc.NewServer()
server := client.New(ctx,
- "", false)
+ "", "", false)
if err := server.Start(); err != nil {
t.Fatal(err)
}
diff --git a/client/cmd/up.go b/client/cmd/up.go
index a0c26a207..b62925e5e 100644
--- a/client/cmd/up.go
+++ b/client/cmd/up.go
@@ -23,7 +23,7 @@ import (
"github.com/netbirdio/netbird/client/internal/profilemanager"
"github.com/netbirdio/netbird/client/proto"
"github.com/netbirdio/netbird/client/system"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/util"
)
@@ -79,7 +79,7 @@ func init() {
upCmd.PersistentFlags().BoolVar(&noBrowser, noBrowserFlag, false, noBrowserDesc)
upCmd.PersistentFlags().StringVar(&profileName, profileNameFlag, "", profileNameDesc)
- upCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "(DEPRECATED) Netbird config file location")
+ upCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "(DEPRECATED) Netbird config file location. ")
}
@@ -146,6 +146,11 @@ func upFunc(cmd *cobra.Command, args []string) error {
}
func runInForegroundMode(ctx context.Context, cmd *cobra.Command, activeProf *profilemanager.Profile) error {
+ // override the default profile filepath if provided
+ if configPath != "" {
+ _ = profilemanager.NewServiceManager(configPath)
+ }
+
err := handleRebrand(cmd)
if err != nil {
return err
@@ -197,6 +202,11 @@ func runInForegroundMode(ctx context.Context, cmd *cobra.Command, activeProf *pr
}
func runInDaemonMode(ctx context.Context, cmd *cobra.Command, pm *profilemanager.ProfileManager, activeProf *profilemanager.Profile, profileSwitched bool) error {
+ // Check if deprecated config flag is set and show warning
+ if cmd.Flag("config").Changed && configPath != "" {
+ cmd.PrintErrf("Warning: Config flag is deprecated on up command, it should be set as a service argument with $NB_CONFIG environment or with \"-config\" flag; netbird service reconfigure --service-env=\"NB_CONFIG=\" or netbird service run --config=\n")
+ }
+
customDNSAddressConverted, err := parseCustomDNSAddress(cmd.Flag(dnsResolverAddress).Changed)
if err != nil {
return fmt.Errorf("parse custom DNS address: %v", err)
diff --git a/client/firewall/manager/set.go b/client/firewall/manager/set.go
index 4c88f6eac..dda93bf47 100644
--- a/client/firewall/manager/set.go
+++ b/client/firewall/manager/set.go
@@ -9,7 +9,7 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
type Set struct {
diff --git a/client/firewall/uspfilter/filter_filter_test.go b/client/firewall/uspfilter/filter_filter_test.go
index b630c9e66..009860f73 100644
--- a/client/firewall/uspfilter/filter_filter_test.go
+++ b/client/firewall/uspfilter/filter_filter_test.go
@@ -15,7 +15,7 @@ import (
"github.com/netbirdio/netbird/client/iface/device"
"github.com/netbirdio/netbird/client/iface/mocks"
"github.com/netbirdio/netbird/client/iface/wgaddr"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
func TestPeerACLFiltering(t *testing.T) {
diff --git a/client/firewall/uspfilter/filter_test.go b/client/firewall/uspfilter/filter_test.go
index 5b5cd5a53..3197be4e8 100644
--- a/client/firewall/uspfilter/filter_test.go
+++ b/client/firewall/uspfilter/filter_test.go
@@ -20,7 +20,7 @@ import (
"github.com/netbirdio/netbird/client/iface/device"
"github.com/netbirdio/netbird/client/iface/wgaddr"
"github.com/netbirdio/netbird/client/internal/netflow"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
var logger = log.NewFromLogrus(logrus.StandardLogger())
diff --git a/client/iface/wgproxy/bind/proxy.go b/client/iface/wgproxy/bind/proxy.go
index 179ac0b75..f68e84810 100644
--- a/client/iface/wgproxy/bind/proxy.go
+++ b/client/iface/wgproxy/bind/proxy.go
@@ -171,7 +171,7 @@ func fakeAddress(peerAddress *net.UDPAddr) (*netip.AddrPort, error) {
fakeIP, err := netip.ParseAddr(fmt.Sprintf("127.1.%s.%s", octets[2], octets[3]))
if err != nil {
- return nil, fmt.Errorf("failed to parse new IP: %w", err)
+ return nil, fmt.Errorf("parse new IP: %w", err)
}
netipAddr := netip.AddrPortFrom(fakeIP, uint16(peerAddress.Port))
diff --git a/client/iface/wgproxy/ebpf/wrapper.go b/client/iface/wgproxy/ebpf/wrapper.go
index dbf9128a8..b25dc4198 100644
--- a/client/iface/wgproxy/ebpf/wrapper.go
+++ b/client/iface/wgproxy/ebpf/wrapper.go
@@ -95,7 +95,7 @@ func (e *ProxyWrapper) CloseConn() error {
e.closeListener.SetCloseListener(nil)
if err := e.remoteConn.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
- return fmt.Errorf("failed to close remote conn: %w", err)
+ return fmt.Errorf("close remote conn: %w", err)
}
return nil
}
diff --git a/client/internal/acl/manager.go b/client/internal/acl/manager.go
index 32dc7fbb8..5ca950297 100644
--- a/client/internal/acl/manager.go
+++ b/client/internal/acl/manager.go
@@ -18,8 +18,8 @@ import (
firewall "github.com/netbirdio/netbird/client/firewall/manager"
"github.com/netbirdio/netbird/client/internal/acl/id"
"github.com/netbirdio/netbird/client/ssh"
- "github.com/netbirdio/netbird/management/domain"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
)
var ErrSourceRangesEmpty = errors.New("sources range is empty")
diff --git a/client/internal/acl/manager_test.go b/client/internal/acl/manager_test.go
index b378de8c8..664476ef4 100644
--- a/client/internal/acl/manager_test.go
+++ b/client/internal/acl/manager_test.go
@@ -12,7 +12,7 @@ import (
"github.com/netbirdio/netbird/client/iface/wgaddr"
"github.com/netbirdio/netbird/client/internal/acl/mocks"
"github.com/netbirdio/netbird/client/internal/netflow"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
)
var flowLogger = netflow.NewManager(nil, []byte{}, nil).GetLogger()
diff --git a/client/internal/auth/pkce_flow_test.go b/client/internal/auth/pkce_flow_test.go
index f42cce51f..b2347d12d 100644
--- a/client/internal/auth/pkce_flow_test.go
+++ b/client/internal/auth/pkce_flow_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/netbirdio/netbird/client/internal"
- mgm "github.com/netbirdio/netbird/management/client/common"
+ mgm "github.com/netbirdio/netbird/shared/management/client/common"
)
func TestPromptLogin(t *testing.T) {
diff --git a/client/internal/connect.go b/client/internal/connect.go
index cd4dd3cb7..d6be285f9 100644
--- a/client/internal/connect.go
+++ b/client/internal/connect.go
@@ -26,11 +26,11 @@ import (
cProto "github.com/netbirdio/netbird/client/proto"
"github.com/netbirdio/netbird/client/ssh"
"github.com/netbirdio/netbird/client/system"
- mgm "github.com/netbirdio/netbird/management/client"
- mgmProto "github.com/netbirdio/netbird/management/proto"
- "github.com/netbirdio/netbird/relay/auth/hmac"
- relayClient "github.com/netbirdio/netbird/relay/client"
- signal "github.com/netbirdio/netbird/signal/client"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
+ "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
+ signal "github.com/netbirdio/netbird/shared/signal/client"
"github.com/netbirdio/netbird/util"
nbnet "github.com/netbirdio/netbird/util/net"
"github.com/netbirdio/netbird/version"
@@ -43,7 +43,7 @@ type ConnectClient struct {
engine *Engine
engineMutex sync.Mutex
- persistNetworkMap bool
+ persistSyncResponse bool
}
func NewConnectClient(
@@ -270,7 +270,7 @@ func (c *ConnectClient) run(mobileDependency MobileDependency, runningChan chan
c.engineMutex.Lock()
c.engine = NewEngine(engineCtx, cancel, signalClient, mgmClient, relayManager, engineConfig, mobileDependency, c.statusRecorder, checks)
- c.engine.SetNetworkMapPersistence(c.persistNetworkMap)
+ c.engine.SetSyncResponsePersistence(c.persistSyncResponse)
c.engineMutex.Unlock()
if err := c.engine.Start(); err != nil {
@@ -349,23 +349,23 @@ func (c *ConnectClient) Engine() *Engine {
return e
}
-// GetLatestNetworkMap returns the latest network map from the engine.
-func (c *ConnectClient) GetLatestNetworkMap() (*mgmProto.NetworkMap, error) {
+// GetLatestSyncResponse returns the latest sync response from the engine.
+func (c *ConnectClient) GetLatestSyncResponse() (*mgmProto.SyncResponse, error) {
engine := c.Engine()
if engine == nil {
return nil, errors.New("engine is not initialized")
}
- networkMap, err := engine.GetLatestNetworkMap()
+ syncResponse, err := engine.GetLatestSyncResponse()
if err != nil {
- return nil, fmt.Errorf("get latest network map: %w", err)
+ return nil, fmt.Errorf("get latest sync response: %w", err)
}
- if networkMap == nil {
- return nil, errors.New("network map is not available")
+ if syncResponse == nil {
+ return nil, errors.New("sync response is not available")
}
- return networkMap, nil
+ return syncResponse, nil
}
// Status returns the current client status
@@ -398,18 +398,18 @@ func (c *ConnectClient) Stop() error {
return nil
}
-// SetNetworkMapPersistence enables or disables network map persistence.
-// When enabled, the last received network map will be stored and can be retrieved
-// through the Engine's getLatestNetworkMap method. When disabled, any stored
-// network map will be cleared.
-func (c *ConnectClient) SetNetworkMapPersistence(enabled bool) {
+// SetSyncResponsePersistence enables or disables sync response persistence.
+// When enabled, the last received sync response will be stored and can be retrieved
+// through the Engine's GetLatestSyncResponse method. When disabled, any stored
+// sync response will be cleared.
+func (c *ConnectClient) SetSyncResponsePersistence(enabled bool) {
c.engineMutex.Lock()
- c.persistNetworkMap = enabled
+ c.persistSyncResponse = enabled
c.engineMutex.Unlock()
engine := c.Engine()
if engine != nil {
- engine.SetNetworkMapPersistence(enabled)
+ engine.SetSyncResponsePersistence(enabled)
}
}
diff --git a/client/internal/debug/debug.go b/client/internal/debug/debug.go
index 71ebf431d..ec920c5f3 100644
--- a/client/internal/debug/debug.go
+++ b/client/internal/debug/debug.go
@@ -27,7 +27,7 @@ import (
"github.com/netbirdio/netbird/client/anonymize"
"github.com/netbirdio/netbird/client/internal/peer"
"github.com/netbirdio/netbird/client/internal/profilemanager"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/util"
)
@@ -46,7 +46,7 @@ iptables.txt: Anonymized iptables rules with packet counters, if --system-info f
nftables.txt: Anonymized nftables rules with packet counters, if --system-info flag was provided.
resolved_domains.txt: Anonymized resolved domain IP addresses from the status recorder.
config.txt: Anonymized configuration information of the NetBird client.
-network_map.json: Anonymized network map containing peer configurations, routes, DNS settings, and firewall rules.
+network_map.json: Anonymized sync response containing peer configurations, routes, DNS settings, and firewall rules.
state.json: Anonymized client state dump containing netbird states.
mutex.prof: Mutex profiling information.
goroutine.prof: Goroutine profiling information.
@@ -73,7 +73,7 @@ Domains
All domain names (except for the netbird domains) are replaced with randomly generated strings ending in ".domain". Anonymized domains are consistent across all files in the bundle.
Reoccuring domain names are replaced with the same anonymized domain.
-Network Map
+Sync Response
The network_map.json file contains the following anonymized information:
- Peer configurations (addresses, FQDNs, DNS settings)
- Remote and offline peer information (allowed IPs, FQDNs)
@@ -81,7 +81,7 @@ The network_map.json file contains the following anonymized information:
- DNS configuration (nameservers, domains, custom zones)
- Firewall rules (peer IPs, source/destination ranges)
-SSH keys in the network map are replaced with a placeholder value. All IP addresses and domains in the network map follow the same anonymization rules as described above.
+SSH keys in the sync response are replaced with a placeholder value. All IP addresses and domains in the sync response follow the same anonymization rules as described above.
State File
The state.json file contains anonymized internal state information of the NetBird client, including:
@@ -201,7 +201,7 @@ type BundleGenerator struct {
// deps
internalConfig *profilemanager.Config
statusRecorder *peer.Status
- networkMap *mgmProto.NetworkMap
+ syncResponse *mgmProto.SyncResponse
logFile string
anonymize bool
@@ -222,7 +222,7 @@ type BundleConfig struct {
type GeneratorDependencies struct {
InternalConfig *profilemanager.Config
StatusRecorder *peer.Status
- NetworkMap *mgmProto.NetworkMap
+ SyncResponse *mgmProto.SyncResponse
LogFile string
}
@@ -238,7 +238,7 @@ func NewBundleGenerator(deps GeneratorDependencies, cfg BundleConfig) *BundleGen
internalConfig: deps.InternalConfig,
statusRecorder: deps.StatusRecorder,
- networkMap: deps.NetworkMap,
+ syncResponse: deps.SyncResponse,
logFile: deps.LogFile,
anonymize: cfg.Anonymize,
@@ -311,8 +311,8 @@ func (g *BundleGenerator) createArchive() error {
log.Errorf("failed to add profiles to debug bundle: %v", err)
}
- if err := g.addNetworkMap(); err != nil {
- return fmt.Errorf("add network map: %w", err)
+ if err := g.addSyncResponse(); err != nil {
+ return fmt.Errorf("add sync response: %w", err)
}
if err := g.addStateFile(); err != nil {
@@ -526,15 +526,15 @@ func (g *BundleGenerator) addResolvedDomains() error {
return nil
}
-func (g *BundleGenerator) addNetworkMap() error {
- if g.networkMap == nil {
- log.Debugf("skipping empty network map in debug bundle")
+func (g *BundleGenerator) addSyncResponse() error {
+ if g.syncResponse == nil {
+ log.Debugf("skipping empty sync response in debug bundle")
return nil
}
if g.anonymize {
- if err := anonymizeNetworkMap(g.networkMap, g.anonymizer); err != nil {
- return fmt.Errorf("anonymize network map: %w", err)
+ if err := anonymizeSyncResponse(g.syncResponse, g.anonymizer); err != nil {
+ return fmt.Errorf("anonymize sync response: %w", err)
}
}
@@ -545,20 +545,20 @@ func (g *BundleGenerator) addNetworkMap() error {
AllowPartial: true,
}
- jsonBytes, err := options.Marshal(g.networkMap)
+ jsonBytes, err := options.Marshal(g.syncResponse)
if err != nil {
return fmt.Errorf("generate json: %w", err)
}
if err := g.addFileToZip(bytes.NewReader(jsonBytes), "network_map.json"); err != nil {
- return fmt.Errorf("add network map to zip: %w", err)
+ return fmt.Errorf("add sync response to zip: %w", err)
}
return nil
}
func (g *BundleGenerator) addStateFile() error {
- sm := profilemanager.ServiceManager{}
+ sm := profilemanager.NewServiceManager("")
path := sm.GetStatePath()
if path == "" {
return nil
@@ -597,7 +597,7 @@ func (g *BundleGenerator) addStateFile() error {
}
func (g *BundleGenerator) addCorruptedStateFiles() error {
- sm := profilemanager.ServiceManager{}
+ sm := profilemanager.NewServiceManager("")
pattern := sm.GetStatePath()
if pattern == "" {
return nil
@@ -921,6 +921,88 @@ func anonymizeNetworkMap(networkMap *mgmProto.NetworkMap, anonymizer *anonymize.
return nil
}
+func anonymizeNetbirdConfig(config *mgmProto.NetbirdConfig, anonymizer *anonymize.Anonymizer) {
+ for _, stun := range config.Stuns {
+ if stun.Uri != "" {
+ stun.Uri = anonymizer.AnonymizeURI(stun.Uri)
+ }
+ }
+
+ for _, turn := range config.Turns {
+ if turn.HostConfig != nil && turn.HostConfig.Uri != "" {
+ turn.HostConfig.Uri = anonymizer.AnonymizeURI(turn.HostConfig.Uri)
+ }
+ if turn.User != "" {
+ turn.User = "turn-user-placeholder"
+ }
+ if turn.Password != "" {
+ turn.Password = "turn-password-placeholder"
+ }
+ }
+
+ if config.Signal != nil && config.Signal.Uri != "" {
+ config.Signal.Uri = anonymizer.AnonymizeURI(config.Signal.Uri)
+ }
+
+ if config.Relay != nil {
+ for i, url := range config.Relay.Urls {
+ config.Relay.Urls[i] = anonymizer.AnonymizeURI(url)
+ }
+ if config.Relay.TokenPayload != "" {
+ config.Relay.TokenPayload = "relay-token-payload-placeholder"
+ }
+ if config.Relay.TokenSignature != "" {
+ config.Relay.TokenSignature = "relay-token-signature-placeholder"
+ }
+ }
+
+ if config.Flow != nil {
+ if config.Flow.Url != "" {
+ config.Flow.Url = anonymizer.AnonymizeURI(config.Flow.Url)
+ }
+ if config.Flow.TokenPayload != "" {
+ config.Flow.TokenPayload = "flow-token-payload-placeholder"
+ }
+ if config.Flow.TokenSignature != "" {
+ config.Flow.TokenSignature = "flow-token-signature-placeholder"
+ }
+ }
+}
+
+func anonymizeSyncResponse(syncResponse *mgmProto.SyncResponse, anonymizer *anonymize.Anonymizer) error {
+ if syncResponse.NetbirdConfig != nil {
+ anonymizeNetbirdConfig(syncResponse.NetbirdConfig, anonymizer)
+ }
+
+ if syncResponse.PeerConfig != nil {
+ anonymizePeerConfig(syncResponse.PeerConfig, anonymizer)
+ }
+
+ for _, p := range syncResponse.RemotePeers {
+ anonymizeRemotePeer(p, anonymizer)
+ }
+
+ if syncResponse.NetworkMap != nil {
+ if err := anonymizeNetworkMap(syncResponse.NetworkMap, anonymizer); err != nil {
+ return err
+ }
+ }
+
+ for _, check := range syncResponse.Checks {
+ for i, file := range check.Files {
+ check.Files[i] = anonymizer.AnonymizeString(file)
+ }
+ }
+
+ return nil
+}
+
+func anonymizeSSHConfig(sshConfig *mgmProto.SSHConfig) {
+ if sshConfig != nil && len(sshConfig.SshPubKey) > 0 {
+ sshConfig.SshPubKey = []byte("ssh-placeholder-key")
+ }
+}
+
func anonymizePeerConfig(config *mgmProto.PeerConfig, anonymizer *anonymize.Anonymizer) {
if config == nil {
return
@@ -930,9 +1012,7 @@ func anonymizePeerConfig(config *mgmProto.PeerConfig, anonymizer *anonymize.Anon
config.Address = anonymizer.AnonymizeIP(addr).String()
}
- if config.SshConfig != nil && len(config.SshConfig.SshPubKey) > 0 {
- config.SshConfig.SshPubKey = []byte("ssh-placeholder-key")
- }
+ anonymizeSSHConfig(config.SshConfig)
config.Dns = anonymizer.AnonymizeString(config.Dns)
config.Fqdn = anonymizer.AnonymizeDomain(config.Fqdn)
@@ -954,9 +1034,7 @@ func anonymizeRemotePeer(peer *mgmProto.RemotePeerConfig, anonymizer *anonymize.
peer.Fqdn = anonymizer.AnonymizeDomain(peer.Fqdn)
- if peer.SshConfig != nil && len(peer.SshConfig.SshPubKey) > 0 {
- peer.SshConfig.SshPubKey = []byte("ssh-placeholder-key")
- }
+ anonymizeSSHConfig(peer.SshConfig)
}
func anonymizeRoute(route *mgmProto.Route, anonymizer *anonymize.Anonymizer) {
diff --git a/client/internal/debug/debug_test.go b/client/internal/debug/debug_test.go
index eb91fed66..59837c328 100644
--- a/client/internal/debug/debug_test.go
+++ b/client/internal/debug/debug_test.go
@@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/netbirdio/netbird/client/anonymize"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
)
func TestAnonymizeStateFile(t *testing.T) {
diff --git a/client/internal/debug/format.go b/client/internal/debug/format.go
index 54fc77f93..aae1f221f 100644
--- a/client/internal/debug/format.go
+++ b/client/internal/debug/format.go
@@ -10,7 +10,7 @@ import (
"github.com/netbirdio/netbird/client/anonymize"
"github.com/netbirdio/netbird/client/internal/peer"
"github.com/netbirdio/netbird/client/internal/routemanager/systemops"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
func formatInterfaces(interfaces []net.Interface, anonymize bool, anonymizer *anonymize.Anonymizer) string {
diff --git a/client/internal/device_auth.go b/client/internal/device_auth.go
index 8e68f7544..6bd29801d 100644
--- a/client/internal/device_auth.go
+++ b/client/internal/device_auth.go
@@ -10,7 +10,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
- mgm "github.com/netbirdio/netbird/management/client"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
)
// DeviceAuthorizationFlow represents Device Authorization Flow information
diff --git a/client/internal/dns/local/local.go b/client/internal/dns/local/local.go
index c19356a7e..b776fbbe3 100644
--- a/client/internal/dns/local/local.go
+++ b/client/internal/dns/local/local.go
@@ -12,7 +12,7 @@ import (
"github.com/netbirdio/netbird/client/internal/dns/types"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
type Resolver struct {
diff --git a/client/internal/dns/mock_server.go b/client/internal/dns/mock_server.go
index 40a2e7384..9e0d06399 100644
--- a/client/internal/dns/mock_server.go
+++ b/client/internal/dns/mock_server.go
@@ -7,7 +7,7 @@ import (
"github.com/miekg/dns"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
// MockServer is the mock instance of a dns server
diff --git a/client/internal/dns/server.go b/client/internal/dns/server.go
index e5f29d807..cd0757dc1 100644
--- a/client/internal/dns/server.go
+++ b/client/internal/dns/server.go
@@ -21,7 +21,7 @@ import (
"github.com/netbirdio/netbird/client/internal/peer"
"github.com/netbirdio/netbird/client/internal/statemanager"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
// ReadyListener is a notification mechanism what indicate the server is ready to handle host dns address changes
diff --git a/client/internal/dns/server_test.go b/client/internal/dns/server_test.go
index 50444a86f..3ac1b6eb1 100644
--- a/client/internal/dns/server_test.go
+++ b/client/internal/dns/server_test.go
@@ -32,7 +32,7 @@ import (
"github.com/netbirdio/netbird/client/internal/stdnet"
nbdns "github.com/netbirdio/netbird/dns"
"github.com/netbirdio/netbird/formatter"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
var flowLogger = netflow.NewManager(nil, []byte{}, nil).GetLogger()
diff --git a/client/internal/dnsfwd/forwarder_test.go b/client/internal/dnsfwd/forwarder_test.go
index d8228c733..c820fbb60 100644
--- a/client/internal/dnsfwd/forwarder_test.go
+++ b/client/internal/dnsfwd/forwarder_test.go
@@ -16,7 +16,7 @@ import (
firewall "github.com/netbirdio/netbird/client/firewall/manager"
"github.com/netbirdio/netbird/client/internal/dns/test"
"github.com/netbirdio/netbird/client/internal/peer"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/internal/dnsfwd/manager.go b/client/internal/dnsfwd/manager.go
index 91abce823..bf2ee839b 100644
--- a/client/internal/dnsfwd/manager.go
+++ b/client/internal/dnsfwd/manager.go
@@ -11,7 +11,7 @@ import (
nberrors "github.com/netbirdio/netbird/client/errors"
firewall "github.com/netbirdio/netbird/client/firewall/manager"
"github.com/netbirdio/netbird/client/internal/peer"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/internal/engine.go b/client/internal/engine.go
index a1aaad27b..12909e827 100644
--- a/client/internal/engine.go
+++ b/client/internal/engine.go
@@ -49,19 +49,19 @@ import (
"github.com/netbirdio/netbird/client/internal/routemanager/systemops"
"github.com/netbirdio/netbird/client/internal/statemanager"
cProto "github.com/netbirdio/netbird/client/proto"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
semaphoregroup "github.com/netbirdio/netbird/util/semaphore-group"
nbssh "github.com/netbirdio/netbird/client/ssh"
"github.com/netbirdio/netbird/client/system"
nbdns "github.com/netbirdio/netbird/dns"
- mgm "github.com/netbirdio/netbird/management/client"
- mgmProto "github.com/netbirdio/netbird/management/proto"
- auth "github.com/netbirdio/netbird/relay/auth/hmac"
- relayClient "github.com/netbirdio/netbird/relay/client"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
+ auth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
"github.com/netbirdio/netbird/route"
- signal "github.com/netbirdio/netbird/signal/client"
- sProto "github.com/netbirdio/netbird/signal/proto"
+ signal "github.com/netbirdio/netbird/shared/signal/client"
+ sProto "github.com/netbirdio/netbird/shared/signal/proto"
"github.com/netbirdio/netbird/util"
)
@@ -189,11 +189,11 @@ type Engine struct {
stateManager *statemanager.Manager
srWatcher *guard.SRWatcher
- // Network map persistence
- persistNetworkMap bool
- latestNetworkMap *mgmProto.NetworkMap
- connSemaphore *semaphoregroup.SemaphoreGroup
- flowManager nftypes.FlowManager
+ // Sync response persistence
+ persistSyncResponse bool
+ latestSyncResponse *mgmProto.SyncResponse
+ connSemaphore *semaphoregroup.SemaphoreGroup
+ flowManager nftypes.FlowManager
}
// Peer is an instance of the Connection Peer
@@ -238,7 +238,7 @@ func NewEngine(
connSemaphore: semaphoregroup.NewSemaphoreGroup(connInitLimit),
}
- sm := profilemanager.ServiceManager{}
+ sm := profilemanager.NewServiceManager("")
path := sm.GetStatePath()
if runtime.GOOS == "ios" {
@@ -698,10 +698,10 @@ func (e *Engine) handleSync(update *mgmProto.SyncResponse) error {
return nil
}
- // Store network map if persistence is enabled
- if e.persistNetworkMap {
- e.latestNetworkMap = nm
- log.Debugf("network map persisted with serial %d", nm.GetSerial())
+ // Store sync response if persistence is enabled
+ if e.persistSyncResponse {
+ e.latestSyncResponse = update
+ log.Debugf("sync response persisted with serial %d", nm.GetSerial())
}
// only apply new changes and ignore old ones
@@ -862,15 +862,10 @@ func (e *Engine) updateConfig(conf *mgmProto.PeerConfig) error {
return errors.New("wireguard interface is not initialized")
}
+ // Cannot update the IP address without restarting the engine because
+ // the firewall, route manager, and other components cache the old address
if e.wgInterface.Address().String() != conf.Address {
- oldAddr := e.wgInterface.Address().String()
- log.Debugf("updating peer address from %s to %s", oldAddr, conf.Address)
- err := e.wgInterface.UpdateAddr(conf.Address)
- if err != nil {
- return err
- }
- e.config.WgAddr = conf.Address
- log.Infof("updated peer address from %s to %s", oldAddr, conf.Address)
+ log.Infof("peer IP address has changed from %s to %s", e.wgInterface.Address().String(), conf.Address)
}
if conf.GetSshConfig() != nil {
@@ -881,7 +876,7 @@ func (e *Engine) updateConfig(conf *mgmProto.PeerConfig) error {
}
state := e.statusRecorder.GetLocalPeerState()
- state.IP = e.config.WgAddr
+ state.IP = e.wgInterface.Address().String()
state.PubKey = e.config.WgPrivateKey.PublicKey().String()
state.KernelInterface = device.WireGuardModuleIsLoaded()
state.FQDN = conf.GetFqdn()
@@ -1757,44 +1752,43 @@ func (e *Engine) stopDNSServer() {
e.statusRecorder.UpdateDNSStates(nsGroupStates)
}
-// SetNetworkMapPersistence enables or disables network map persistence
-func (e *Engine) SetNetworkMapPersistence(enabled bool) {
+// SetSyncResponsePersistence enables or disables sync response persistence
+func (e *Engine) SetSyncResponsePersistence(enabled bool) {
e.syncMsgMux.Lock()
defer e.syncMsgMux.Unlock()
- if enabled == e.persistNetworkMap {
+ if enabled == e.persistSyncResponse {
return
}
- e.persistNetworkMap = enabled
- log.Debugf("Network map persistence is set to %t", enabled)
+ e.persistSyncResponse = enabled
+ log.Debugf("Sync response persistence is set to %t", enabled)
if !enabled {
- e.latestNetworkMap = nil
+ e.latestSyncResponse = nil
}
}
-// GetLatestNetworkMap returns the stored network map if persistence is enabled
-func (e *Engine) GetLatestNetworkMap() (*mgmProto.NetworkMap, error) {
+// GetLatestSyncResponse returns the stored sync response if persistence is enabled
+func (e *Engine) GetLatestSyncResponse() (*mgmProto.SyncResponse, error) {
e.syncMsgMux.Lock()
defer e.syncMsgMux.Unlock()
- if !e.persistNetworkMap {
- return nil, errors.New("network map persistence is disabled")
+ if !e.persistSyncResponse {
+ return nil, errors.New("sync response persistence is disabled")
}
- if e.latestNetworkMap == nil {
+ if e.latestSyncResponse == nil {
//nolint:nilnil
return nil, nil
}
- log.Debugf("Retrieving latest network map with size %d bytes", proto.Size(e.latestNetworkMap))
- nm, ok := proto.Clone(e.latestNetworkMap).(*mgmProto.NetworkMap)
+ log.Debugf("Retrieving latest sync response with size %d bytes", proto.Size(e.latestSyncResponse))
+ sr, ok := proto.Clone(e.latestSyncResponse).(*mgmProto.SyncResponse)
if !ok {
-
- return nil, fmt.Errorf("failed to clone network map")
+ return nil, fmt.Errorf("failed to clone sync response")
}
- return nm, nil
+ return sr, nil
}
// GetWgAddr returns the wireguard address
diff --git a/client/internal/engine_test.go b/client/internal/engine_test.go
index 2ac531662..0406fe6dc 100644
--- a/client/internal/engine_test.go
+++ b/client/internal/engine_test.go
@@ -43,8 +43,8 @@ import (
"github.com/netbirdio/netbird/client/ssh"
"github.com/netbirdio/netbird/client/system"
nbdns "github.com/netbirdio/netbird/dns"
- mgmt "github.com/netbirdio/netbird/management/client"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmt "github.com/netbirdio/netbird/shared/management/client"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/integrations/port_forwarding"
@@ -54,10 +54,10 @@ import (
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/monotime"
- relayClient "github.com/netbirdio/netbird/relay/client"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
"github.com/netbirdio/netbird/route"
- signal "github.com/netbirdio/netbird/signal/client"
- "github.com/netbirdio/netbird/signal/proto"
+ signal "github.com/netbirdio/netbird/shared/signal/client"
+ "github.com/netbirdio/netbird/shared/signal/proto"
signalServer "github.com/netbirdio/netbird/signal/server"
"github.com/netbirdio/netbird/util"
)
diff --git a/client/internal/login.go b/client/internal/login.go
index 7c96e4081..d5412a110 100644
--- a/client/internal/login.go
+++ b/client/internal/login.go
@@ -13,8 +13,8 @@ import (
"github.com/netbirdio/netbird/client/internal/profilemanager"
"github.com/netbirdio/netbird/client/ssh"
"github.com/netbirdio/netbird/client/system"
- mgm "github.com/netbirdio/netbird/management/client"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
)
// IsLoginRequired check that the server is support SSO or not
diff --git a/client/internal/message_convert.go b/client/internal/message_convert.go
index 8ad93bfb9..97da32c06 100644
--- a/client/internal/message_convert.go
+++ b/client/internal/message_convert.go
@@ -7,7 +7,7 @@ import (
"net/netip"
firewallManager "github.com/netbirdio/netbird/client/firewall/manager"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
)
func convertToFirewallProtocol(protocol mgmProto.RuleProtocol) (firewallManager.Protocol, error) {
diff --git a/client/internal/peer/conn.go b/client/internal/peer/conn.go
index d4fe9b517..0b21eb612 100644
--- a/client/internal/peer/conn.go
+++ b/client/internal/peer/conn.go
@@ -24,7 +24,7 @@ import (
"github.com/netbirdio/netbird/client/internal/peer/id"
"github.com/netbirdio/netbird/client/internal/peer/worker"
"github.com/netbirdio/netbird/client/internal/stdnet"
- relayClient "github.com/netbirdio/netbird/relay/client"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
"github.com/netbirdio/netbird/route"
semaphoregroup "github.com/netbirdio/netbird/util/semaphore-group"
)
diff --git a/client/internal/peer/signaler.go b/client/internal/peer/signaler.go
index ed8d2ae74..ac65160a2 100644
--- a/client/internal/peer/signaler.go
+++ b/client/internal/peer/signaler.go
@@ -4,8 +4,8 @@ import (
"github.com/pion/ice/v3"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
- signal "github.com/netbirdio/netbird/signal/client"
- sProto "github.com/netbirdio/netbird/signal/proto"
+ signal "github.com/netbirdio/netbird/shared/signal/client"
+ sProto "github.com/netbirdio/netbird/shared/signal/proto"
)
type Signaler struct {
diff --git a/client/internal/peer/status.go b/client/internal/peer/status.go
index e290ef75f..bd4e63357 100644
--- a/client/internal/peer/status.go
+++ b/client/internal/peer/status.go
@@ -21,8 +21,8 @@ import (
"github.com/netbirdio/netbird/client/internal/ingressgw"
"github.com/netbirdio/netbird/client/internal/relay"
"github.com/netbirdio/netbird/client/proto"
- "github.com/netbirdio/netbird/management/domain"
- relayClient "github.com/netbirdio/netbird/relay/client"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/internal/peer/worker_relay.go b/client/internal/peer/worker_relay.go
index ef9f24a2b..f584487f5 100644
--- a/client/internal/peer/worker_relay.go
+++ b/client/internal/peer/worker_relay.go
@@ -9,7 +9,7 @@ import (
log "github.com/sirupsen/logrus"
- relayClient "github.com/netbirdio/netbird/relay/client"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
)
type RelayConnInfo struct {
diff --git a/client/internal/pkce_auth.go b/client/internal/pkce_auth.go
index f020d7a91..a713bb342 100644
--- a/client/internal/pkce_auth.go
+++ b/client/internal/pkce_auth.go
@@ -11,8 +11,8 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
- mgm "github.com/netbirdio/netbird/management/client"
- "github.com/netbirdio/netbird/management/client/common"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
+ "github.com/netbirdio/netbird/shared/management/client/common"
)
// PKCEAuthorizationFlow represents PKCE Authorization Flow information
diff --git a/client/internal/profilemanager/config.go b/client/internal/profilemanager/config.go
index df6b93402..084a03d88 100644
--- a/client/internal/profilemanager/config.go
+++ b/client/internal/profilemanager/config.go
@@ -20,15 +20,14 @@ import (
"github.com/netbirdio/netbird/client/iface"
"github.com/netbirdio/netbird/client/internal/routemanager/dynamic"
"github.com/netbirdio/netbird/client/ssh"
- mgm "github.com/netbirdio/netbird/management/client"
- "github.com/netbirdio/netbird/management/domain"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/util"
)
const (
// managementLegacyPortString is the port that was used before by the Management gRPC server.
// It is used for backward compatibility now.
- // NB: hardcoded from github.com/netbirdio/netbird/management/cmd to avoid import
managementLegacyPortString = "33073"
// DefaultManagementURL points to the NetBird's cloud management endpoint
DefaultManagementURL = "https://api.netbird.io:443"
diff --git a/client/internal/profilemanager/profilemanager.go b/client/internal/profilemanager/profilemanager.go
index 4598af33e..fe0afae2b 100644
--- a/client/internal/profilemanager/profilemanager.go
+++ b/client/internal/profilemanager/profilemanager.go
@@ -13,7 +13,8 @@ import (
)
const (
- defaultProfileName = "default"
+ DefaultProfileName = "default"
+ defaultProfileName = DefaultProfileName // Keep for backward compatibility
activeProfileStateFilename = "active_profile.txt"
)
diff --git a/client/internal/profilemanager/service.go b/client/internal/profilemanager/service.go
index 520eef2e9..faccf5f68 100644
--- a/client/internal/profilemanager/service.go
+++ b/client/internal/profilemanager/service.go
@@ -75,7 +75,15 @@ func (a *ActiveProfileState) FilePath() (string, error) {
return filepath.Join(configDir, a.Name+".json"), nil
}
-type ServiceManager struct{}
+type ServiceManager struct {
+}
+
+func NewServiceManager(defaultConfigPath string) *ServiceManager {
+ if defaultConfigPath != "" {
+ DefaultConfigPath = defaultConfigPath
+ }
+ return &ServiceManager{}
+}
func (s *ServiceManager) CopyDefaultProfileIfNotExists() (bool, error) {
diff --git a/client/internal/routemanager/dnsinterceptor/handler.go b/client/internal/routemanager/dnsinterceptor/handler.go
index c7c3aeb0b..ba27df654 100644
--- a/client/internal/routemanager/dnsinterceptor/handler.go
+++ b/client/internal/routemanager/dnsinterceptor/handler.go
@@ -22,7 +22,7 @@ import (
"github.com/netbirdio/netbird/client/internal/routemanager/common"
"github.com/netbirdio/netbird/client/internal/routemanager/fakeip"
"github.com/netbirdio/netbird/client/internal/routemanager/refcounter"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/internal/routemanager/dynamic/route.go b/client/internal/routemanager/dynamic/route.go
index 5d561f0cf..587e05c74 100644
--- a/client/internal/routemanager/dynamic/route.go
+++ b/client/internal/routemanager/dynamic/route.go
@@ -18,7 +18,7 @@ import (
"github.com/netbirdio/netbird/client/internal/routemanager/iface"
"github.com/netbirdio/netbird/client/internal/routemanager/refcounter"
"github.com/netbirdio/netbird/client/internal/routemanager/util"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/internal/routemanager/dynamic/route_generic.go b/client/internal/routemanager/dynamic/route_generic.go
index a618a2392..56fd63fba 100644
--- a/client/internal/routemanager/dynamic/route_generic.go
+++ b/client/internal/routemanager/dynamic/route_generic.go
@@ -5,7 +5,7 @@ package dynamic
import (
"net"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
func (r *Route) getIPsFromResolver(domain domain.Domain) ([]net.IP, error) {
diff --git a/client/internal/routemanager/dynamic/route_ios.go b/client/internal/routemanager/dynamic/route_ios.go
index 34949b626..8fed1c8f9 100644
--- a/client/internal/routemanager/dynamic/route_ios.go
+++ b/client/internal/routemanager/dynamic/route_ios.go
@@ -11,7 +11,7 @@ import (
nbdns "github.com/netbirdio/netbird/client/internal/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
)
const dialTimeout = 10 * time.Second
diff --git a/client/internal/routemanager/manager.go b/client/internal/routemanager/manager.go
index e51778811..da5534902 100644
--- a/client/internal/routemanager/manager.go
+++ b/client/internal/routemanager/manager.go
@@ -36,7 +36,7 @@ import (
"github.com/netbirdio/netbird/client/internal/routemanager/vars"
"github.com/netbirdio/netbird/client/internal/routeselector"
"github.com/netbirdio/netbird/client/internal/statemanager"
- relayClient "github.com/netbirdio/netbird/relay/client"
+ relayClient "github.com/netbirdio/netbird/shared/relay/client"
"github.com/netbirdio/netbird/route"
nbnet "github.com/netbirdio/netbird/util/net"
"github.com/netbirdio/netbird/version"
diff --git a/client/internal/routemanager/systemops/systemops_linux.go b/client/internal/routemanager/systemops/systemops_linux.go
index f50ea572c..c0cef94ba 100644
--- a/client/internal/routemanager/systemops/systemops_linux.go
+++ b/client/internal/routemanager/systemops/systemops_linux.go
@@ -77,8 +77,8 @@ type ruleParams struct {
func getSetupRules() []ruleParams {
return []ruleParams{
- {100, 0, syscall.RT_TABLE_MAIN, netlink.FAMILY_V4, false, 0, "rule with suppress prefixlen v4"},
- {100, 0, syscall.RT_TABLE_MAIN, netlink.FAMILY_V6, false, 0, "rule with suppress prefixlen v6"},
+ {105, 0, syscall.RT_TABLE_MAIN, netlink.FAMILY_V4, false, 0, "rule with suppress prefixlen v4"},
+ {105, 0, syscall.RT_TABLE_MAIN, netlink.FAMILY_V6, false, 0, "rule with suppress prefixlen v6"},
{110, nbnet.ControlPlaneMark, NetbirdVPNTableID, netlink.FAMILY_V4, true, -1, "rule v4 netbird"},
{110, nbnet.ControlPlaneMark, NetbirdVPNTableID, netlink.FAMILY_V6, true, -1, "rule v6 netbird"},
}
diff --git a/client/ios/NetBirdSDK/client.go b/client/ios/NetBirdSDK/client.go
index fe0f6034e..2109d4b15 100644
--- a/client/ios/NetBirdSDK/client.go
+++ b/client/ios/NetBirdSDK/client.go
@@ -20,7 +20,7 @@ import (
"github.com/netbirdio/netbird/client/internal/profilemanager"
"github.com/netbirdio/netbird/client/system"
"github.com/netbirdio/netbird/formatter"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/proto/daemon.pb.go b/client/proto/daemon.pb.go
index f405ffd65..691976971 100644
--- a/client/proto/daemon.pb.go
+++ b/client/proto/daemon.pb.go
@@ -2959,27 +2959,27 @@ func (x *DeleteStateResponse) GetDeletedStates() int32 {
return 0
}
-type SetNetworkMapPersistenceRequest struct {
+type SetSyncResponsePersistenceRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
-func (x *SetNetworkMapPersistenceRequest) Reset() {
- *x = SetNetworkMapPersistenceRequest{}
+func (x *SetSyncResponsePersistenceRequest) Reset() {
+ *x = SetSyncResponsePersistenceRequest{}
mi := &file_daemon_proto_msgTypes[42]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
-func (x *SetNetworkMapPersistenceRequest) String() string {
+func (x *SetSyncResponsePersistenceRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
-func (*SetNetworkMapPersistenceRequest) ProtoMessage() {}
+func (*SetSyncResponsePersistenceRequest) ProtoMessage() {}
-func (x *SetNetworkMapPersistenceRequest) ProtoReflect() protoreflect.Message {
+func (x *SetSyncResponsePersistenceRequest) ProtoReflect() protoreflect.Message {
mi := &file_daemon_proto_msgTypes[42]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
@@ -2991,38 +2991,38 @@ func (x *SetNetworkMapPersistenceRequest) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
-// Deprecated: Use SetNetworkMapPersistenceRequest.ProtoReflect.Descriptor instead.
-func (*SetNetworkMapPersistenceRequest) Descriptor() ([]byte, []int) {
+// Deprecated: Use SetSyncResponsePersistenceRequest.ProtoReflect.Descriptor instead.
+func (*SetSyncResponsePersistenceRequest) Descriptor() ([]byte, []int) {
return file_daemon_proto_rawDescGZIP(), []int{42}
}
-func (x *SetNetworkMapPersistenceRequest) GetEnabled() bool {
+func (x *SetSyncResponsePersistenceRequest) GetEnabled() bool {
if x != nil {
return x.Enabled
}
return false
}
-type SetNetworkMapPersistenceResponse struct {
+type SetSyncResponsePersistenceResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
-func (x *SetNetworkMapPersistenceResponse) Reset() {
- *x = SetNetworkMapPersistenceResponse{}
+func (x *SetSyncResponsePersistenceResponse) Reset() {
+ *x = SetSyncResponsePersistenceResponse{}
mi := &file_daemon_proto_msgTypes[43]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
-func (x *SetNetworkMapPersistenceResponse) String() string {
+func (x *SetSyncResponsePersistenceResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
-func (*SetNetworkMapPersistenceResponse) ProtoMessage() {}
+func (*SetSyncResponsePersistenceResponse) ProtoMessage() {}
-func (x *SetNetworkMapPersistenceResponse) ProtoReflect() protoreflect.Message {
+func (x *SetSyncResponsePersistenceResponse) ProtoReflect() protoreflect.Message {
mi := &file_daemon_proto_msgTypes[43]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
@@ -3034,8 +3034,8 @@ func (x *SetNetworkMapPersistenceResponse) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
-// Deprecated: Use SetNetworkMapPersistenceResponse.ProtoReflect.Descriptor instead.
-func (*SetNetworkMapPersistenceResponse) Descriptor() ([]byte, []int) {
+// Deprecated: Use SetSyncResponsePersistenceResponse.ProtoReflect.Descriptor instead.
+func (*SetSyncResponsePersistenceResponse) Descriptor() ([]byte, []int) {
return file_daemon_proto_rawDescGZIP(), []int{43}
}
@@ -4342,6 +4342,94 @@ func (x *GetActiveProfileResponse) GetUsername() string {
return ""
}
+type LogoutRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ProfileName *string `protobuf:"bytes,1,opt,name=profileName,proto3,oneof" json:"profileName,omitempty"`
+ Username *string `protobuf:"bytes,2,opt,name=username,proto3,oneof" json:"username,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *LogoutRequest) Reset() {
+ *x = LogoutRequest{}
+ mi := &file_daemon_proto_msgTypes[65]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *LogoutRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LogoutRequest) ProtoMessage() {}
+
+func (x *LogoutRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_daemon_proto_msgTypes[65]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use LogoutRequest.ProtoReflect.Descriptor instead.
+func (*LogoutRequest) Descriptor() ([]byte, []int) {
+ return file_daemon_proto_rawDescGZIP(), []int{65}
+}
+
+func (x *LogoutRequest) GetProfileName() string {
+ if x != nil && x.ProfileName != nil {
+ return *x.ProfileName
+ }
+ return ""
+}
+
+func (x *LogoutRequest) GetUsername() string {
+ if x != nil && x.Username != nil {
+ return *x.Username
+ }
+ return ""
+}
+
+type LogoutResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *LogoutResponse) Reset() {
+ *x = LogoutResponse{}
+ mi := &file_daemon_proto_msgTypes[66]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *LogoutResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LogoutResponse) ProtoMessage() {}
+
+func (x *LogoutResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_daemon_proto_msgTypes[66]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use LogoutResponse.ProtoReflect.Descriptor instead.
+func (*LogoutResponse) Descriptor() ([]byte, []int) {
+ return file_daemon_proto_rawDescGZIP(), []int{66}
+}
+
type PortInfo_Range struct {
state protoimpl.MessageState `protogen:"open.v1"`
Start uint32 `protobuf:"varint,1,opt,name=start,proto3" json:"start,omitempty"`
@@ -4352,7 +4440,7 @@ type PortInfo_Range struct {
func (x *PortInfo_Range) Reset() {
*x = PortInfo_Range{}
- mi := &file_daemon_proto_msgTypes[66]
+ mi := &file_daemon_proto_msgTypes[68]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4364,7 +4452,7 @@ func (x *PortInfo_Range) String() string {
func (*PortInfo_Range) ProtoMessage() {}
func (x *PortInfo_Range) ProtoReflect() protoreflect.Message {
- mi := &file_daemon_proto_msgTypes[66]
+ mi := &file_daemon_proto_msgTypes[68]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4639,10 +4727,10 @@ const file_daemon_proto_rawDesc = "" +
"state_name\x18\x01 \x01(\tR\tstateName\x12\x10\n" +
"\x03all\x18\x02 \x01(\bR\x03all\"<\n" +
"\x13DeleteStateResponse\x12%\n" +
- "\x0edeleted_states\x18\x01 \x01(\x05R\rdeletedStates\";\n" +
- "\x1fSetNetworkMapPersistenceRequest\x12\x18\n" +
- "\aenabled\x18\x01 \x01(\bR\aenabled\"\"\n" +
- " SetNetworkMapPersistenceResponse\"v\n" +
+ "\x0edeleted_states\x18\x01 \x01(\x05R\rdeletedStates\"=\n" +
+ "!SetSyncResponsePersistenceRequest\x12\x18\n" +
+ "\aenabled\x18\x01 \x01(\bR\aenabled\"$\n" +
+ "\"SetSyncResponsePersistenceResponse\"v\n" +
"\bTCPFlags\x12\x10\n" +
"\x03syn\x18\x01 \x01(\bR\x03syn\x12\x10\n" +
"\x03ack\x18\x02 \x01(\bR\x03ack\x12\x10\n" +
@@ -4778,7 +4866,13 @@ const file_daemon_proto_rawDesc = "" +
"\x17GetActiveProfileRequest\"X\n" +
"\x18GetActiveProfileResponse\x12 \n" +
"\vprofileName\x18\x01 \x01(\tR\vprofileName\x12\x1a\n" +
- "\busername\x18\x02 \x01(\tR\busername*b\n" +
+ "\busername\x18\x02 \x01(\tR\busername\"t\n" +
+ "\rLogoutRequest\x12%\n" +
+ "\vprofileName\x18\x01 \x01(\tH\x00R\vprofileName\x88\x01\x01\x12\x1f\n" +
+ "\busername\x18\x02 \x01(\tH\x01R\busername\x88\x01\x01B\x0e\n" +
+ "\f_profileNameB\v\n" +
+ "\t_username\"\x10\n" +
+ "\x0eLogoutResponse*b\n" +
"\bLogLevel\x12\v\n" +
"\aUNKNOWN\x10\x00\x12\t\n" +
"\x05PANIC\x10\x01\x12\t\n" +
@@ -4787,7 +4881,7 @@ const file_daemon_proto_rawDesc = "" +
"\x04WARN\x10\x04\x12\b\n" +
"\x04INFO\x10\x05\x12\t\n" +
"\x05DEBUG\x10\x06\x12\t\n" +
- "\x05TRACE\x10\a2\x84\x0f\n" +
+ "\x05TRACE\x10\a2\xc5\x0f\n" +
"\rDaemonService\x126\n" +
"\x05Login\x12\x14.daemon.LoginRequest\x1a\x15.daemon.LoginResponse\"\x00\x12K\n" +
"\fWaitSSOLogin\x12\x1b.daemon.WaitSSOLoginRequest\x1a\x1c.daemon.WaitSSOLoginResponse\"\x00\x12-\n" +
@@ -4806,8 +4900,8 @@ const file_daemon_proto_rawDesc = "" +
"ListStates\x12\x19.daemon.ListStatesRequest\x1a\x1a.daemon.ListStatesResponse\"\x00\x12E\n" +
"\n" +
"CleanState\x12\x19.daemon.CleanStateRequest\x1a\x1a.daemon.CleanStateResponse\"\x00\x12H\n" +
- "\vDeleteState\x12\x1a.daemon.DeleteStateRequest\x1a\x1b.daemon.DeleteStateResponse\"\x00\x12o\n" +
- "\x18SetNetworkMapPersistence\x12'.daemon.SetNetworkMapPersistenceRequest\x1a(.daemon.SetNetworkMapPersistenceResponse\"\x00\x12H\n" +
+ "\vDeleteState\x12\x1a.daemon.DeleteStateRequest\x1a\x1b.daemon.DeleteStateResponse\"\x00\x12u\n" +
+ "\x1aSetSyncResponsePersistence\x12).daemon.SetSyncResponsePersistenceRequest\x1a*.daemon.SetSyncResponsePersistenceResponse\"\x00\x12H\n" +
"\vTracePacket\x12\x1a.daemon.TracePacketRequest\x1a\x1b.daemon.TracePacketResponse\"\x00\x12D\n" +
"\x0fSubscribeEvents\x12\x18.daemon.SubscribeRequest\x1a\x13.daemon.SystemEvent\"\x000\x01\x12B\n" +
"\tGetEvents\x12\x18.daemon.GetEventsRequest\x1a\x19.daemon.GetEventsResponse\"\x00\x12N\n" +
@@ -4817,7 +4911,8 @@ const file_daemon_proto_rawDesc = "" +
"AddProfile\x12\x19.daemon.AddProfileRequest\x1a\x1a.daemon.AddProfileResponse\"\x00\x12N\n" +
"\rRemoveProfile\x12\x1c.daemon.RemoveProfileRequest\x1a\x1d.daemon.RemoveProfileResponse\"\x00\x12K\n" +
"\fListProfiles\x12\x1b.daemon.ListProfilesRequest\x1a\x1c.daemon.ListProfilesResponse\"\x00\x12W\n" +
- "\x10GetActiveProfile\x12\x1f.daemon.GetActiveProfileRequest\x1a .daemon.GetActiveProfileResponse\"\x00B\bZ\x06/protob\x06proto3"
+ "\x10GetActiveProfile\x12\x1f.daemon.GetActiveProfileRequest\x1a .daemon.GetActiveProfileResponse\"\x00\x129\n" +
+ "\x06Logout\x12\x15.daemon.LogoutRequest\x1a\x16.daemon.LogoutResponse\"\x00B\bZ\x06/protob\x06proto3"
var (
file_daemon_proto_rawDescOnce sync.Once
@@ -4832,88 +4927,90 @@ func file_daemon_proto_rawDescGZIP() []byte {
}
var file_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
-var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 68)
+var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 70)
var file_daemon_proto_goTypes = []any{
- (LogLevel)(0), // 0: daemon.LogLevel
- (SystemEvent_Severity)(0), // 1: daemon.SystemEvent.Severity
- (SystemEvent_Category)(0), // 2: daemon.SystemEvent.Category
- (*EmptyRequest)(nil), // 3: daemon.EmptyRequest
- (*LoginRequest)(nil), // 4: daemon.LoginRequest
- (*LoginResponse)(nil), // 5: daemon.LoginResponse
- (*WaitSSOLoginRequest)(nil), // 6: daemon.WaitSSOLoginRequest
- (*WaitSSOLoginResponse)(nil), // 7: daemon.WaitSSOLoginResponse
- (*UpRequest)(nil), // 8: daemon.UpRequest
- (*UpResponse)(nil), // 9: daemon.UpResponse
- (*StatusRequest)(nil), // 10: daemon.StatusRequest
- (*StatusResponse)(nil), // 11: daemon.StatusResponse
- (*DownRequest)(nil), // 12: daemon.DownRequest
- (*DownResponse)(nil), // 13: daemon.DownResponse
- (*GetConfigRequest)(nil), // 14: daemon.GetConfigRequest
- (*GetConfigResponse)(nil), // 15: daemon.GetConfigResponse
- (*PeerState)(nil), // 16: daemon.PeerState
- (*LocalPeerState)(nil), // 17: daemon.LocalPeerState
- (*SignalState)(nil), // 18: daemon.SignalState
- (*ManagementState)(nil), // 19: daemon.ManagementState
- (*RelayState)(nil), // 20: daemon.RelayState
- (*NSGroupState)(nil), // 21: daemon.NSGroupState
- (*FullStatus)(nil), // 22: daemon.FullStatus
- (*ListNetworksRequest)(nil), // 23: daemon.ListNetworksRequest
- (*ListNetworksResponse)(nil), // 24: daemon.ListNetworksResponse
- (*SelectNetworksRequest)(nil), // 25: daemon.SelectNetworksRequest
- (*SelectNetworksResponse)(nil), // 26: daemon.SelectNetworksResponse
- (*IPList)(nil), // 27: daemon.IPList
- (*Network)(nil), // 28: daemon.Network
- (*PortInfo)(nil), // 29: daemon.PortInfo
- (*ForwardingRule)(nil), // 30: daemon.ForwardingRule
- (*ForwardingRulesResponse)(nil), // 31: daemon.ForwardingRulesResponse
- (*DebugBundleRequest)(nil), // 32: daemon.DebugBundleRequest
- (*DebugBundleResponse)(nil), // 33: daemon.DebugBundleResponse
- (*GetLogLevelRequest)(nil), // 34: daemon.GetLogLevelRequest
- (*GetLogLevelResponse)(nil), // 35: daemon.GetLogLevelResponse
- (*SetLogLevelRequest)(nil), // 36: daemon.SetLogLevelRequest
- (*SetLogLevelResponse)(nil), // 37: daemon.SetLogLevelResponse
- (*State)(nil), // 38: daemon.State
- (*ListStatesRequest)(nil), // 39: daemon.ListStatesRequest
- (*ListStatesResponse)(nil), // 40: daemon.ListStatesResponse
- (*CleanStateRequest)(nil), // 41: daemon.CleanStateRequest
- (*CleanStateResponse)(nil), // 42: daemon.CleanStateResponse
- (*DeleteStateRequest)(nil), // 43: daemon.DeleteStateRequest
- (*DeleteStateResponse)(nil), // 44: daemon.DeleteStateResponse
- (*SetNetworkMapPersistenceRequest)(nil), // 45: daemon.SetNetworkMapPersistenceRequest
- (*SetNetworkMapPersistenceResponse)(nil), // 46: daemon.SetNetworkMapPersistenceResponse
- (*TCPFlags)(nil), // 47: daemon.TCPFlags
- (*TracePacketRequest)(nil), // 48: daemon.TracePacketRequest
- (*TraceStage)(nil), // 49: daemon.TraceStage
- (*TracePacketResponse)(nil), // 50: daemon.TracePacketResponse
- (*SubscribeRequest)(nil), // 51: daemon.SubscribeRequest
- (*SystemEvent)(nil), // 52: daemon.SystemEvent
- (*GetEventsRequest)(nil), // 53: daemon.GetEventsRequest
- (*GetEventsResponse)(nil), // 54: daemon.GetEventsResponse
- (*SwitchProfileRequest)(nil), // 55: daemon.SwitchProfileRequest
- (*SwitchProfileResponse)(nil), // 56: daemon.SwitchProfileResponse
- (*SetConfigRequest)(nil), // 57: daemon.SetConfigRequest
- (*SetConfigResponse)(nil), // 58: daemon.SetConfigResponse
- (*AddProfileRequest)(nil), // 59: daemon.AddProfileRequest
- (*AddProfileResponse)(nil), // 60: daemon.AddProfileResponse
- (*RemoveProfileRequest)(nil), // 61: daemon.RemoveProfileRequest
- (*RemoveProfileResponse)(nil), // 62: daemon.RemoveProfileResponse
- (*ListProfilesRequest)(nil), // 63: daemon.ListProfilesRequest
- (*ListProfilesResponse)(nil), // 64: daemon.ListProfilesResponse
- (*Profile)(nil), // 65: daemon.Profile
- (*GetActiveProfileRequest)(nil), // 66: daemon.GetActiveProfileRequest
- (*GetActiveProfileResponse)(nil), // 67: daemon.GetActiveProfileResponse
- nil, // 68: daemon.Network.ResolvedIPsEntry
- (*PortInfo_Range)(nil), // 69: daemon.PortInfo.Range
- nil, // 70: daemon.SystemEvent.MetadataEntry
- (*durationpb.Duration)(nil), // 71: google.protobuf.Duration
- (*timestamppb.Timestamp)(nil), // 72: google.protobuf.Timestamp
+ (LogLevel)(0), // 0: daemon.LogLevel
+ (SystemEvent_Severity)(0), // 1: daemon.SystemEvent.Severity
+ (SystemEvent_Category)(0), // 2: daemon.SystemEvent.Category
+ (*EmptyRequest)(nil), // 3: daemon.EmptyRequest
+ (*LoginRequest)(nil), // 4: daemon.LoginRequest
+ (*LoginResponse)(nil), // 5: daemon.LoginResponse
+ (*WaitSSOLoginRequest)(nil), // 6: daemon.WaitSSOLoginRequest
+ (*WaitSSOLoginResponse)(nil), // 7: daemon.WaitSSOLoginResponse
+ (*UpRequest)(nil), // 8: daemon.UpRequest
+ (*UpResponse)(nil), // 9: daemon.UpResponse
+ (*StatusRequest)(nil), // 10: daemon.StatusRequest
+ (*StatusResponse)(nil), // 11: daemon.StatusResponse
+ (*DownRequest)(nil), // 12: daemon.DownRequest
+ (*DownResponse)(nil), // 13: daemon.DownResponse
+ (*GetConfigRequest)(nil), // 14: daemon.GetConfigRequest
+ (*GetConfigResponse)(nil), // 15: daemon.GetConfigResponse
+ (*PeerState)(nil), // 16: daemon.PeerState
+ (*LocalPeerState)(nil), // 17: daemon.LocalPeerState
+ (*SignalState)(nil), // 18: daemon.SignalState
+ (*ManagementState)(nil), // 19: daemon.ManagementState
+ (*RelayState)(nil), // 20: daemon.RelayState
+ (*NSGroupState)(nil), // 21: daemon.NSGroupState
+ (*FullStatus)(nil), // 22: daemon.FullStatus
+ (*ListNetworksRequest)(nil), // 23: daemon.ListNetworksRequest
+ (*ListNetworksResponse)(nil), // 24: daemon.ListNetworksResponse
+ (*SelectNetworksRequest)(nil), // 25: daemon.SelectNetworksRequest
+ (*SelectNetworksResponse)(nil), // 26: daemon.SelectNetworksResponse
+ (*IPList)(nil), // 27: daemon.IPList
+ (*Network)(nil), // 28: daemon.Network
+ (*PortInfo)(nil), // 29: daemon.PortInfo
+ (*ForwardingRule)(nil), // 30: daemon.ForwardingRule
+ (*ForwardingRulesResponse)(nil), // 31: daemon.ForwardingRulesResponse
+ (*DebugBundleRequest)(nil), // 32: daemon.DebugBundleRequest
+ (*DebugBundleResponse)(nil), // 33: daemon.DebugBundleResponse
+ (*GetLogLevelRequest)(nil), // 34: daemon.GetLogLevelRequest
+ (*GetLogLevelResponse)(nil), // 35: daemon.GetLogLevelResponse
+ (*SetLogLevelRequest)(nil), // 36: daemon.SetLogLevelRequest
+ (*SetLogLevelResponse)(nil), // 37: daemon.SetLogLevelResponse
+ (*State)(nil), // 38: daemon.State
+ (*ListStatesRequest)(nil), // 39: daemon.ListStatesRequest
+ (*ListStatesResponse)(nil), // 40: daemon.ListStatesResponse
+ (*CleanStateRequest)(nil), // 41: daemon.CleanStateRequest
+ (*CleanStateResponse)(nil), // 42: daemon.CleanStateResponse
+ (*DeleteStateRequest)(nil), // 43: daemon.DeleteStateRequest
+ (*DeleteStateResponse)(nil), // 44: daemon.DeleteStateResponse
+ (*SetSyncResponsePersistenceRequest)(nil), // 45: daemon.SetSyncResponsePersistenceRequest
+ (*SetSyncResponsePersistenceResponse)(nil), // 46: daemon.SetSyncResponsePersistenceResponse
+ (*TCPFlags)(nil), // 47: daemon.TCPFlags
+ (*TracePacketRequest)(nil), // 48: daemon.TracePacketRequest
+ (*TraceStage)(nil), // 49: daemon.TraceStage
+ (*TracePacketResponse)(nil), // 50: daemon.TracePacketResponse
+ (*SubscribeRequest)(nil), // 51: daemon.SubscribeRequest
+ (*SystemEvent)(nil), // 52: daemon.SystemEvent
+ (*GetEventsRequest)(nil), // 53: daemon.GetEventsRequest
+ (*GetEventsResponse)(nil), // 54: daemon.GetEventsResponse
+ (*SwitchProfileRequest)(nil), // 55: daemon.SwitchProfileRequest
+ (*SwitchProfileResponse)(nil), // 56: daemon.SwitchProfileResponse
+ (*SetConfigRequest)(nil), // 57: daemon.SetConfigRequest
+ (*SetConfigResponse)(nil), // 58: daemon.SetConfigResponse
+ (*AddProfileRequest)(nil), // 59: daemon.AddProfileRequest
+ (*AddProfileResponse)(nil), // 60: daemon.AddProfileResponse
+ (*RemoveProfileRequest)(nil), // 61: daemon.RemoveProfileRequest
+ (*RemoveProfileResponse)(nil), // 62: daemon.RemoveProfileResponse
+ (*ListProfilesRequest)(nil), // 63: daemon.ListProfilesRequest
+ (*ListProfilesResponse)(nil), // 64: daemon.ListProfilesResponse
+ (*Profile)(nil), // 65: daemon.Profile
+ (*GetActiveProfileRequest)(nil), // 66: daemon.GetActiveProfileRequest
+ (*GetActiveProfileResponse)(nil), // 67: daemon.GetActiveProfileResponse
+ (*LogoutRequest)(nil), // 68: daemon.LogoutRequest
+ (*LogoutResponse)(nil), // 69: daemon.LogoutResponse
+ nil, // 70: daemon.Network.ResolvedIPsEntry
+ (*PortInfo_Range)(nil), // 71: daemon.PortInfo.Range
+ nil, // 72: daemon.SystemEvent.MetadataEntry
+ (*durationpb.Duration)(nil), // 73: google.protobuf.Duration
+ (*timestamppb.Timestamp)(nil), // 74: google.protobuf.Timestamp
}
var file_daemon_proto_depIdxs = []int32{
- 71, // 0: daemon.LoginRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
+ 73, // 0: daemon.LoginRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
22, // 1: daemon.StatusResponse.fullStatus:type_name -> daemon.FullStatus
- 72, // 2: daemon.PeerState.connStatusUpdate:type_name -> google.protobuf.Timestamp
- 72, // 3: daemon.PeerState.lastWireguardHandshake:type_name -> google.protobuf.Timestamp
- 71, // 4: daemon.PeerState.latency:type_name -> google.protobuf.Duration
+ 74, // 2: daemon.PeerState.connStatusUpdate:type_name -> google.protobuf.Timestamp
+ 74, // 3: daemon.PeerState.lastWireguardHandshake:type_name -> google.protobuf.Timestamp
+ 73, // 4: daemon.PeerState.latency:type_name -> google.protobuf.Duration
19, // 5: daemon.FullStatus.managementState:type_name -> daemon.ManagementState
18, // 6: daemon.FullStatus.signalState:type_name -> daemon.SignalState
17, // 7: daemon.FullStatus.localPeerState:type_name -> daemon.LocalPeerState
@@ -4922,8 +5019,8 @@ var file_daemon_proto_depIdxs = []int32{
21, // 10: daemon.FullStatus.dns_servers:type_name -> daemon.NSGroupState
52, // 11: daemon.FullStatus.events:type_name -> daemon.SystemEvent
28, // 12: daemon.ListNetworksResponse.routes:type_name -> daemon.Network
- 68, // 13: daemon.Network.resolvedIPs:type_name -> daemon.Network.ResolvedIPsEntry
- 69, // 14: daemon.PortInfo.range:type_name -> daemon.PortInfo.Range
+ 70, // 13: daemon.Network.resolvedIPs:type_name -> daemon.Network.ResolvedIPsEntry
+ 71, // 14: daemon.PortInfo.range:type_name -> daemon.PortInfo.Range
29, // 15: daemon.ForwardingRule.destinationPort:type_name -> daemon.PortInfo
29, // 16: daemon.ForwardingRule.translatedPort:type_name -> daemon.PortInfo
30, // 17: daemon.ForwardingRulesResponse.rules:type_name -> daemon.ForwardingRule
@@ -4934,10 +5031,10 @@ var file_daemon_proto_depIdxs = []int32{
49, // 22: daemon.TracePacketResponse.stages:type_name -> daemon.TraceStage
1, // 23: daemon.SystemEvent.severity:type_name -> daemon.SystemEvent.Severity
2, // 24: daemon.SystemEvent.category:type_name -> daemon.SystemEvent.Category
- 72, // 25: daemon.SystemEvent.timestamp:type_name -> google.protobuf.Timestamp
- 70, // 26: daemon.SystemEvent.metadata:type_name -> daemon.SystemEvent.MetadataEntry
+ 74, // 25: daemon.SystemEvent.timestamp:type_name -> google.protobuf.Timestamp
+ 72, // 26: daemon.SystemEvent.metadata:type_name -> daemon.SystemEvent.MetadataEntry
52, // 27: daemon.GetEventsResponse.events:type_name -> daemon.SystemEvent
- 71, // 28: daemon.SetConfigRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
+ 73, // 28: daemon.SetConfigRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
65, // 29: daemon.ListProfilesResponse.profiles:type_name -> daemon.Profile
27, // 30: daemon.Network.ResolvedIPsEntry.value:type_name -> daemon.IPList
4, // 31: daemon.DaemonService.Login:input_type -> daemon.LoginRequest
@@ -4956,7 +5053,7 @@ var file_daemon_proto_depIdxs = []int32{
39, // 44: daemon.DaemonService.ListStates:input_type -> daemon.ListStatesRequest
41, // 45: daemon.DaemonService.CleanState:input_type -> daemon.CleanStateRequest
43, // 46: daemon.DaemonService.DeleteState:input_type -> daemon.DeleteStateRequest
- 45, // 47: daemon.DaemonService.SetNetworkMapPersistence:input_type -> daemon.SetNetworkMapPersistenceRequest
+ 45, // 47: daemon.DaemonService.SetSyncResponsePersistence:input_type -> daemon.SetSyncResponsePersistenceRequest
48, // 48: daemon.DaemonService.TracePacket:input_type -> daemon.TracePacketRequest
51, // 49: daemon.DaemonService.SubscribeEvents:input_type -> daemon.SubscribeRequest
53, // 50: daemon.DaemonService.GetEvents:input_type -> daemon.GetEventsRequest
@@ -4966,34 +5063,36 @@ var file_daemon_proto_depIdxs = []int32{
61, // 54: daemon.DaemonService.RemoveProfile:input_type -> daemon.RemoveProfileRequest
63, // 55: daemon.DaemonService.ListProfiles:input_type -> daemon.ListProfilesRequest
66, // 56: daemon.DaemonService.GetActiveProfile:input_type -> daemon.GetActiveProfileRequest
- 5, // 57: daemon.DaemonService.Login:output_type -> daemon.LoginResponse
- 7, // 58: daemon.DaemonService.WaitSSOLogin:output_type -> daemon.WaitSSOLoginResponse
- 9, // 59: daemon.DaemonService.Up:output_type -> daemon.UpResponse
- 11, // 60: daemon.DaemonService.Status:output_type -> daemon.StatusResponse
- 13, // 61: daemon.DaemonService.Down:output_type -> daemon.DownResponse
- 15, // 62: daemon.DaemonService.GetConfig:output_type -> daemon.GetConfigResponse
- 24, // 63: daemon.DaemonService.ListNetworks:output_type -> daemon.ListNetworksResponse
- 26, // 64: daemon.DaemonService.SelectNetworks:output_type -> daemon.SelectNetworksResponse
- 26, // 65: daemon.DaemonService.DeselectNetworks:output_type -> daemon.SelectNetworksResponse
- 31, // 66: daemon.DaemonService.ForwardingRules:output_type -> daemon.ForwardingRulesResponse
- 33, // 67: daemon.DaemonService.DebugBundle:output_type -> daemon.DebugBundleResponse
- 35, // 68: daemon.DaemonService.GetLogLevel:output_type -> daemon.GetLogLevelResponse
- 37, // 69: daemon.DaemonService.SetLogLevel:output_type -> daemon.SetLogLevelResponse
- 40, // 70: daemon.DaemonService.ListStates:output_type -> daemon.ListStatesResponse
- 42, // 71: daemon.DaemonService.CleanState:output_type -> daemon.CleanStateResponse
- 44, // 72: daemon.DaemonService.DeleteState:output_type -> daemon.DeleteStateResponse
- 46, // 73: daemon.DaemonService.SetNetworkMapPersistence:output_type -> daemon.SetNetworkMapPersistenceResponse
- 50, // 74: daemon.DaemonService.TracePacket:output_type -> daemon.TracePacketResponse
- 52, // 75: daemon.DaemonService.SubscribeEvents:output_type -> daemon.SystemEvent
- 54, // 76: daemon.DaemonService.GetEvents:output_type -> daemon.GetEventsResponse
- 56, // 77: daemon.DaemonService.SwitchProfile:output_type -> daemon.SwitchProfileResponse
- 58, // 78: daemon.DaemonService.SetConfig:output_type -> daemon.SetConfigResponse
- 60, // 79: daemon.DaemonService.AddProfile:output_type -> daemon.AddProfileResponse
- 62, // 80: daemon.DaemonService.RemoveProfile:output_type -> daemon.RemoveProfileResponse
- 64, // 81: daemon.DaemonService.ListProfiles:output_type -> daemon.ListProfilesResponse
- 67, // 82: daemon.DaemonService.GetActiveProfile:output_type -> daemon.GetActiveProfileResponse
- 57, // [57:83] is the sub-list for method output_type
- 31, // [31:57] is the sub-list for method input_type
+ 68, // 57: daemon.DaemonService.Logout:input_type -> daemon.LogoutRequest
+ 5, // 58: daemon.DaemonService.Login:output_type -> daemon.LoginResponse
+ 7, // 59: daemon.DaemonService.WaitSSOLogin:output_type -> daemon.WaitSSOLoginResponse
+ 9, // 60: daemon.DaemonService.Up:output_type -> daemon.UpResponse
+ 11, // 61: daemon.DaemonService.Status:output_type -> daemon.StatusResponse
+ 13, // 62: daemon.DaemonService.Down:output_type -> daemon.DownResponse
+ 15, // 63: daemon.DaemonService.GetConfig:output_type -> daemon.GetConfigResponse
+ 24, // 64: daemon.DaemonService.ListNetworks:output_type -> daemon.ListNetworksResponse
+ 26, // 65: daemon.DaemonService.SelectNetworks:output_type -> daemon.SelectNetworksResponse
+ 26, // 66: daemon.DaemonService.DeselectNetworks:output_type -> daemon.SelectNetworksResponse
+ 31, // 67: daemon.DaemonService.ForwardingRules:output_type -> daemon.ForwardingRulesResponse
+ 33, // 68: daemon.DaemonService.DebugBundle:output_type -> daemon.DebugBundleResponse
+ 35, // 69: daemon.DaemonService.GetLogLevel:output_type -> daemon.GetLogLevelResponse
+ 37, // 70: daemon.DaemonService.SetLogLevel:output_type -> daemon.SetLogLevelResponse
+ 40, // 71: daemon.DaemonService.ListStates:output_type -> daemon.ListStatesResponse
+ 42, // 72: daemon.DaemonService.CleanState:output_type -> daemon.CleanStateResponse
+ 44, // 73: daemon.DaemonService.DeleteState:output_type -> daemon.DeleteStateResponse
+ 46, // 74: daemon.DaemonService.SetSyncResponsePersistence:output_type -> daemon.SetSyncResponsePersistenceResponse
+ 50, // 75: daemon.DaemonService.TracePacket:output_type -> daemon.TracePacketResponse
+ 52, // 76: daemon.DaemonService.SubscribeEvents:output_type -> daemon.SystemEvent
+ 54, // 77: daemon.DaemonService.GetEvents:output_type -> daemon.GetEventsResponse
+ 56, // 78: daemon.DaemonService.SwitchProfile:output_type -> daemon.SwitchProfileResponse
+ 58, // 79: daemon.DaemonService.SetConfig:output_type -> daemon.SetConfigResponse
+ 60, // 80: daemon.DaemonService.AddProfile:output_type -> daemon.AddProfileResponse
+ 62, // 81: daemon.DaemonService.RemoveProfile:output_type -> daemon.RemoveProfileResponse
+ 64, // 82: daemon.DaemonService.ListProfiles:output_type -> daemon.ListProfilesResponse
+ 67, // 83: daemon.DaemonService.GetActiveProfile:output_type -> daemon.GetActiveProfileResponse
+ 69, // 84: daemon.DaemonService.Logout:output_type -> daemon.LogoutResponse
+ 58, // [58:85] is the sub-list for method output_type
+ 31, // [31:58] is the sub-list for method input_type
31, // [31:31] is the sub-list for extension type_name
31, // [31:31] is the sub-list for extension extendee
0, // [0:31] is the sub-list for field type_name
@@ -5014,13 +5113,14 @@ func file_daemon_proto_init() {
file_daemon_proto_msgTypes[46].OneofWrappers = []any{}
file_daemon_proto_msgTypes[52].OneofWrappers = []any{}
file_daemon_proto_msgTypes[54].OneofWrappers = []any{}
+ file_daemon_proto_msgTypes[65].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_proto_rawDesc), len(file_daemon_proto_rawDesc)),
NumEnums: 3,
- NumMessages: 68,
+ NumMessages: 70,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/client/proto/daemon.proto b/client/proto/daemon.proto
index c25503df9..76db56459 100644
--- a/client/proto/daemon.proto
+++ b/client/proto/daemon.proto
@@ -59,8 +59,8 @@ service DaemonService {
// Delete specific state or all states
rpc DeleteState(DeleteStateRequest) returns (DeleteStateResponse) {}
- // SetNetworkMapPersistence enables or disables network map persistence
- rpc SetNetworkMapPersistence(SetNetworkMapPersistenceRequest) returns (SetNetworkMapPersistenceResponse) {}
+ // SetSyncResponsePersistence enables or disables sync response persistence
+ rpc SetSyncResponsePersistence(SetSyncResponsePersistenceRequest) returns (SetSyncResponsePersistenceResponse) {}
rpc TracePacket(TracePacketRequest) returns (TracePacketResponse) {}
@@ -79,6 +79,9 @@ service DaemonService {
rpc ListProfiles(ListProfilesRequest) returns (ListProfilesResponse) {}
rpc GetActiveProfile(GetActiveProfileRequest) returns (GetActiveProfileResponse) {}
+
+ // Logout disconnects from the network and deletes the peer from the management server
+ rpc Logout(LogoutRequest) returns (LogoutResponse) {}
}
@@ -449,11 +452,11 @@ message DeleteStateResponse {
}
-message SetNetworkMapPersistenceRequest {
+message SetSyncResponsePersistenceRequest {
bool enabled = 1;
}
-message SetNetworkMapPersistenceResponse {}
+message SetSyncResponsePersistenceResponse {}
message TCPFlags {
bool syn = 1;
@@ -614,4 +617,11 @@ message GetActiveProfileRequest {}
message GetActiveProfileResponse {
string profileName = 1;
string username = 2;
-}
\ No newline at end of file
+}
+
+message LogoutRequest {
+ optional string profileName = 1;
+ optional string username = 2;
+}
+
+message LogoutResponse {}
\ No newline at end of file
diff --git a/client/proto/daemon_grpc.pb.go b/client/proto/daemon_grpc.pb.go
index 669083168..6dfdfa9c3 100644
--- a/client/proto/daemon_grpc.pb.go
+++ b/client/proto/daemon_grpc.pb.go
@@ -50,8 +50,8 @@ type DaemonServiceClient interface {
CleanState(ctx context.Context, in *CleanStateRequest, opts ...grpc.CallOption) (*CleanStateResponse, error)
// Delete specific state or all states
DeleteState(ctx context.Context, in *DeleteStateRequest, opts ...grpc.CallOption) (*DeleteStateResponse, error)
- // SetNetworkMapPersistence enables or disables network map persistence
- SetNetworkMapPersistence(ctx context.Context, in *SetNetworkMapPersistenceRequest, opts ...grpc.CallOption) (*SetNetworkMapPersistenceResponse, error)
+ // SetSyncResponsePersistence enables or disables sync response persistence
+ SetSyncResponsePersistence(ctx context.Context, in *SetSyncResponsePersistenceRequest, opts ...grpc.CallOption) (*SetSyncResponsePersistenceResponse, error)
TracePacket(ctx context.Context, in *TracePacketRequest, opts ...grpc.CallOption) (*TracePacketResponse, error)
SubscribeEvents(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (DaemonService_SubscribeEventsClient, error)
GetEvents(ctx context.Context, in *GetEventsRequest, opts ...grpc.CallOption) (*GetEventsResponse, error)
@@ -61,6 +61,8 @@ type DaemonServiceClient interface {
RemoveProfile(ctx context.Context, in *RemoveProfileRequest, opts ...grpc.CallOption) (*RemoveProfileResponse, error)
ListProfiles(ctx context.Context, in *ListProfilesRequest, opts ...grpc.CallOption) (*ListProfilesResponse, error)
GetActiveProfile(ctx context.Context, in *GetActiveProfileRequest, opts ...grpc.CallOption) (*GetActiveProfileResponse, error)
+ // Logout disconnects from the network and deletes the peer from the management server
+ Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error)
}
type daemonServiceClient struct {
@@ -215,9 +217,9 @@ func (c *daemonServiceClient) DeleteState(ctx context.Context, in *DeleteStateRe
return out, nil
}
-func (c *daemonServiceClient) SetNetworkMapPersistence(ctx context.Context, in *SetNetworkMapPersistenceRequest, opts ...grpc.CallOption) (*SetNetworkMapPersistenceResponse, error) {
- out := new(SetNetworkMapPersistenceResponse)
- err := c.cc.Invoke(ctx, "/daemon.DaemonService/SetNetworkMapPersistence", in, out, opts...)
+func (c *daemonServiceClient) SetSyncResponsePersistence(ctx context.Context, in *SetSyncResponsePersistenceRequest, opts ...grpc.CallOption) (*SetSyncResponsePersistenceResponse, error) {
+ out := new(SetSyncResponsePersistenceResponse)
+ err := c.cc.Invoke(ctx, "/daemon.DaemonService/SetSyncResponsePersistence", in, out, opts...)
if err != nil {
return nil, err
}
@@ -328,6 +330,15 @@ func (c *daemonServiceClient) GetActiveProfile(ctx context.Context, in *GetActiv
return out, nil
}
+func (c *daemonServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) {
+ out := new(LogoutResponse)
+ err := c.cc.Invoke(ctx, "/daemon.DaemonService/Logout", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// DaemonServiceServer is the server API for DaemonService service.
// All implementations must embed UnimplementedDaemonServiceServer
// for forward compatibility
@@ -364,8 +375,8 @@ type DaemonServiceServer interface {
CleanState(context.Context, *CleanStateRequest) (*CleanStateResponse, error)
// Delete specific state or all states
DeleteState(context.Context, *DeleteStateRequest) (*DeleteStateResponse, error)
- // SetNetworkMapPersistence enables or disables network map persistence
- SetNetworkMapPersistence(context.Context, *SetNetworkMapPersistenceRequest) (*SetNetworkMapPersistenceResponse, error)
+ // SetSyncResponsePersistence enables or disables sync response persistence
+ SetSyncResponsePersistence(context.Context, *SetSyncResponsePersistenceRequest) (*SetSyncResponsePersistenceResponse, error)
TracePacket(context.Context, *TracePacketRequest) (*TracePacketResponse, error)
SubscribeEvents(*SubscribeRequest, DaemonService_SubscribeEventsServer) error
GetEvents(context.Context, *GetEventsRequest) (*GetEventsResponse, error)
@@ -375,6 +386,8 @@ type DaemonServiceServer interface {
RemoveProfile(context.Context, *RemoveProfileRequest) (*RemoveProfileResponse, error)
ListProfiles(context.Context, *ListProfilesRequest) (*ListProfilesResponse, error)
GetActiveProfile(context.Context, *GetActiveProfileRequest) (*GetActiveProfileResponse, error)
+ // Logout disconnects from the network and deletes the peer from the management server
+ Logout(context.Context, *LogoutRequest) (*LogoutResponse, error)
mustEmbedUnimplementedDaemonServiceServer()
}
@@ -430,8 +443,8 @@ func (UnimplementedDaemonServiceServer) CleanState(context.Context, *CleanStateR
func (UnimplementedDaemonServiceServer) DeleteState(context.Context, *DeleteStateRequest) (*DeleteStateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method DeleteState not implemented")
}
-func (UnimplementedDaemonServiceServer) SetNetworkMapPersistence(context.Context, *SetNetworkMapPersistenceRequest) (*SetNetworkMapPersistenceResponse, error) {
- return nil, status.Errorf(codes.Unimplemented, "method SetNetworkMapPersistence not implemented")
+func (UnimplementedDaemonServiceServer) SetSyncResponsePersistence(context.Context, *SetSyncResponsePersistenceRequest) (*SetSyncResponsePersistenceResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method SetSyncResponsePersistence not implemented")
}
func (UnimplementedDaemonServiceServer) TracePacket(context.Context, *TracePacketRequest) (*TracePacketResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method TracePacket not implemented")
@@ -460,6 +473,9 @@ func (UnimplementedDaemonServiceServer) ListProfiles(context.Context, *ListProfi
func (UnimplementedDaemonServiceServer) GetActiveProfile(context.Context, *GetActiveProfileRequest) (*GetActiveProfileResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetActiveProfile not implemented")
}
+func (UnimplementedDaemonServiceServer) Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented")
+}
func (UnimplementedDaemonServiceServer) mustEmbedUnimplementedDaemonServiceServer() {}
// UnsafeDaemonServiceServer may be embedded to opt out of forward compatibility for this service.
@@ -761,20 +777,20 @@ func _DaemonService_DeleteState_Handler(srv interface{}, ctx context.Context, de
return interceptor(ctx, in, info, handler)
}
-func _DaemonService_SetNetworkMapPersistence_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(SetNetworkMapPersistenceRequest)
+func _DaemonService_SetSyncResponsePersistence_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SetSyncResponsePersistenceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
- return srv.(DaemonServiceServer).SetNetworkMapPersistence(ctx, in)
+ return srv.(DaemonServiceServer).SetSyncResponsePersistence(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
- FullMethod: "/daemon.DaemonService/SetNetworkMapPersistence",
+ FullMethod: "/daemon.DaemonService/SetSyncResponsePersistence",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(DaemonServiceServer).SetNetworkMapPersistence(ctx, req.(*SetNetworkMapPersistenceRequest))
+ return srv.(DaemonServiceServer).SetSyncResponsePersistence(ctx, req.(*SetSyncResponsePersistenceRequest))
}
return interceptor(ctx, in, info, handler)
}
@@ -944,6 +960,24 @@ func _DaemonService_GetActiveProfile_Handler(srv interface{}, ctx context.Contex
return interceptor(ctx, in, info, handler)
}
+func _DaemonService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(LogoutRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DaemonServiceServer).Logout(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/daemon.DaemonService/Logout",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DaemonServiceServer).Logout(ctx, req.(*LogoutRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// DaemonService_ServiceDesc is the grpc.ServiceDesc for DaemonService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -1016,8 +1050,8 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{
Handler: _DaemonService_DeleteState_Handler,
},
{
- MethodName: "SetNetworkMapPersistence",
- Handler: _DaemonService_SetNetworkMapPersistence_Handler,
+ MethodName: "SetSyncResponsePersistence",
+ Handler: _DaemonService_SetSyncResponsePersistence_Handler,
},
{
MethodName: "TracePacket",
@@ -1051,6 +1085,10 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{
MethodName: "GetActiveProfile",
Handler: _DaemonService_GetActiveProfile_Handler,
},
+ {
+ MethodName: "Logout",
+ Handler: _DaemonService_Logout_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{
diff --git a/client/server/debug.go b/client/server/debug.go
index 412602b00..056d9df21 100644
--- a/client/server/debug.go
+++ b/client/server/debug.go
@@ -16,7 +16,7 @@ import (
"github.com/netbirdio/netbird/client/internal/debug"
"github.com/netbirdio/netbird/client/proto"
- mgmProto "github.com/netbirdio/netbird/management/proto"
+ mgmProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/upload-server/types"
)
@@ -27,15 +27,16 @@ func (s *Server) DebugBundle(_ context.Context, req *proto.DebugBundleRequest) (
s.mutex.Lock()
defer s.mutex.Unlock()
- networkMap, err := s.getLatestNetworkMap()
+ syncResponse, err := s.getLatestSyncResponse()
if err != nil {
- log.Warnf("failed to get latest network map: %v", err)
+ log.Warnf("failed to get latest sync response: %v", err)
}
+
bundleGenerator := debug.NewBundleGenerator(
debug.GeneratorDependencies{
InternalConfig: s.config,
StatusRecorder: s.statusRecorder,
- NetworkMap: networkMap,
+ SyncResponse: syncResponse,
LogFile: s.logFile,
},
debug.BundleConfig{
@@ -192,26 +193,25 @@ func (s *Server) SetLogLevel(_ context.Context, req *proto.SetLogLevelRequest) (
return &proto.SetLogLevelResponse{}, nil
}
-// SetNetworkMapPersistence sets the network map persistence for the server.
-func (s *Server) SetNetworkMapPersistence(_ context.Context, req *proto.SetNetworkMapPersistenceRequest) (*proto.SetNetworkMapPersistenceResponse, error) {
+// SetSyncResponsePersistence sets the sync response persistence for the server.
+func (s *Server) SetSyncResponsePersistence(_ context.Context, req *proto.SetSyncResponsePersistenceRequest) (*proto.SetSyncResponsePersistenceResponse, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
enabled := req.GetEnabled()
- s.persistNetworkMap = enabled
+ s.persistSyncResponse = enabled
if s.connectClient != nil {
- s.connectClient.SetNetworkMapPersistence(enabled)
+ s.connectClient.SetSyncResponsePersistence(enabled)
}
- return &proto.SetNetworkMapPersistenceResponse{}, nil
+ return &proto.SetSyncResponsePersistenceResponse{}, nil
}
-// getLatestNetworkMap returns the latest network map from the engine if network map persistence is enabled
-func (s *Server) getLatestNetworkMap() (*mgmProto.NetworkMap, error) {
+func (s *Server) getLatestSyncResponse() (*mgmProto.SyncResponse, error) {
cClient := s.connectClient
if cClient == nil {
return nil, errors.New("connect client is not initialized")
}
- return cClient.GetLatestNetworkMap()
+ return cClient.GetLatestSyncResponse()
}
diff --git a/client/server/network.go b/client/server/network.go
index 93b7caa46..18b16795d 100644
--- a/client/server/network.go
+++ b/client/server/network.go
@@ -11,7 +11,7 @@ import (
"golang.org/x/exp/maps"
"github.com/netbirdio/netbird/client/proto"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/client/server/server.go b/client/server/server.go
index 3cb173881..fadf2e7fc 100644
--- a/client/server/server.go
+++ b/client/server/server.go
@@ -2,6 +2,7 @@ package server
import (
"context"
+ "errors"
"fmt"
"os"
"os/exec"
@@ -13,6 +14,7 @@ import (
"github.com/cenkalti/backoff/v4"
"golang.org/x/exp/maps"
+ "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"google.golang.org/protobuf/types/known/durationpb"
log "github.com/sirupsen/logrus"
@@ -24,7 +26,8 @@ import (
"github.com/netbirdio/netbird/client/internal/auth"
"github.com/netbirdio/netbird/client/internal/profilemanager"
"github.com/netbirdio/netbird/client/system"
- "github.com/netbirdio/netbird/management/domain"
+ mgm "github.com/netbirdio/netbird/shared/management/client"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/client/internal"
"github.com/netbirdio/netbird/client/internal/peer"
@@ -47,6 +50,8 @@ const (
errProfilesDisabled = "profiles are disabled, you cannot use this feature without profiles enabled"
)
+var ErrServiceNotUp = errors.New("service is not up")
+
// Server for service control.
type Server struct {
rootCtx context.Context
@@ -65,11 +70,11 @@ type Server struct {
statusRecorder *peer.Status
sessionWatcher *internal.SessionWatcher
- lastProbe time.Time
- persistNetworkMap bool
- isSessionActive atomic.Bool
+ lastProbe time.Time
+ persistSyncResponse bool
+ isSessionActive atomic.Bool
- profileManager profilemanager.ServiceManager
+ profileManager *profilemanager.ServiceManager
profilesDisabled bool
}
@@ -81,14 +86,14 @@ type oauthAuthFlow struct {
}
// New server instance constructor.
-func New(ctx context.Context, logFile string, profilesDisabled bool) *Server {
+func New(ctx context.Context, logFile string, configFile string, profilesDisabled bool) *Server {
return &Server{
- rootCtx: ctx,
- logFile: logFile,
- persistNetworkMap: true,
- statusRecorder: peer.NewRecorder(""),
- profileManager: profilemanager.ServiceManager{},
- profilesDisabled: profilesDisabled,
+ rootCtx: ctx,
+ logFile: logFile,
+ persistSyncResponse: true,
+ statusRecorder: peer.NewRecorder(""),
+ profileManager: profilemanager.NewServiceManager(configFile),
+ profilesDisabled: profilesDisabled,
}
}
@@ -131,13 +136,7 @@ func (s *Server) Start() error {
return fmt.Errorf("failed to get active profile state: %w", err)
}
- cfgPath, err := activeProf.FilePath()
- if err != nil {
- log.Errorf("failed to get active profile file path: %v", err)
- return fmt.Errorf("failed to get active profile file path: %w", err)
- }
-
- config, err := profilemanager.GetConfig(cfgPath)
+ config, err := s.getConfig(activeProf)
if err != nil {
log.Errorf("failed to get active profile config: %v", err)
@@ -234,7 +233,7 @@ func (s *Server) connectWithRetryRuns(ctx context.Context, config *profilemanage
runOperation := func() error {
log.Tracef("running client connection")
s.connectClient = internal.NewConnectClient(ctx, config, statusRecorder)
- s.connectClient.SetNetworkMapPersistence(s.persistNetworkMap)
+ s.connectClient.SetSyncResponsePersistence(s.persistSyncResponse)
err := s.connectClient.Run(runningChan)
if err != nil {
@@ -484,13 +483,7 @@ func (s *Server) Login(callerCtx context.Context, msg *proto.LoginRequest) (*pro
}
s.mutex.Unlock()
- cfgPath, err := activeProf.FilePath()
- if err != nil {
- log.Errorf("failed to get active profile file path: %v", err)
- return nil, fmt.Errorf("failed to get active profile file path: %w", err)
- }
-
- config, err := profilemanager.GetConfig(cfgPath)
+ config, err := s.getConfig(activeProf)
if err != nil {
log.Errorf("failed to get active profile config: %v", err)
return nil, fmt.Errorf("failed to get active profile config: %w", err)
@@ -701,13 +694,7 @@ func (s *Server) Up(callerCtx context.Context, msg *proto.UpRequest) (*proto.UpR
log.Infof("active profile: %s for %s", activeProf.Name, activeProf.Username)
- cfgPath, err := activeProf.FilePath()
- if err != nil {
- log.Errorf("failed to get active profile file path: %v", err)
- return nil, fmt.Errorf("failed to get active profile file path: %w", err)
- }
-
- config, err := profilemanager.GetConfig(cfgPath)
+ config, err := s.getConfig(activeProf)
if err != nil {
log.Errorf("failed to get active profile config: %v", err)
return nil, fmt.Errorf("failed to get active profile config: %w", err)
@@ -789,13 +776,7 @@ func (s *Server) SwitchProfile(callerCtx context.Context, msg *proto.SwitchProfi
log.Errorf("failed to get active profile state: %v", err)
return nil, fmt.Errorf("failed to get active profile state: %w", err)
}
- cfgPath, err := activeProf.FilePath()
- if err != nil {
- log.Errorf("failed to get active profile file path: %v", err)
- return nil, fmt.Errorf("failed to get active profile file path: %w", err)
- }
-
- config, err := profilemanager.GetConfig(cfgPath)
+ config, err := s.getConfig(activeProf)
if err != nil {
log.Errorf("failed to get default profile config: %v", err)
return nil, fmt.Errorf("failed to get default profile config: %w", err)
@@ -811,26 +792,201 @@ func (s *Server) Down(ctx context.Context, _ *proto.DownRequest) (*proto.DownRes
s.mutex.Lock()
defer s.mutex.Unlock()
- s.oauthAuthFlow = oauthAuthFlow{}
-
- if s.actCancel == nil {
- return nil, fmt.Errorf("service is not up")
- }
- s.actCancel()
-
- err := s.connectClient.Stop()
- if err != nil {
+ if err := s.cleanupConnection(); err != nil {
log.Errorf("failed to shut down properly: %v", err)
return nil, err
}
- s.isSessionActive.Store(false)
state := internal.CtxGetState(s.rootCtx)
state.Set(internal.StatusIdle)
+ return &proto.DownResponse{}, nil
+}
+
+func (s *Server) cleanupConnection() error {
+ s.oauthAuthFlow = oauthAuthFlow{}
+
+ if s.actCancel == nil {
+ return ErrServiceNotUp
+ }
+ s.actCancel()
+
+ if s.connectClient == nil {
+ return nil
+ }
+
+ if err := s.connectClient.Stop(); err != nil {
+ return err
+ }
+
+ s.connectClient = nil
+ s.isSessionActive.Store(false)
+
log.Infof("service is down")
- return &proto.DownResponse{}, nil
+ return nil
+}
+
+func (s *Server) Logout(ctx context.Context, msg *proto.LogoutRequest) (*proto.LogoutResponse, error) {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ if msg.ProfileName != nil && *msg.ProfileName != "" {
+ return s.handleProfileLogout(ctx, msg)
+ }
+
+ return s.handleActiveProfileLogout(ctx)
+}
+
+func (s *Server) handleProfileLogout(ctx context.Context, msg *proto.LogoutRequest) (*proto.LogoutResponse, error) {
+ if err := s.validateProfileOperation(*msg.ProfileName, true); err != nil {
+ return nil, err
+ }
+
+ if msg.Username == nil || *msg.Username == "" {
+ return nil, gstatus.Errorf(codes.InvalidArgument, "username must be provided when profile name is specified")
+ }
+ username := *msg.Username
+
+ if err := s.logoutFromProfile(ctx, *msg.ProfileName, username); err != nil {
+ log.Errorf("failed to logout from profile %s: %v", *msg.ProfileName, err)
+ return nil, gstatus.Errorf(codes.Internal, "logout: %v", err)
+ }
+
+ activeProf, _ := s.profileManager.GetActiveProfileState()
+ if activeProf != nil && activeProf.Name == *msg.ProfileName {
+ if err := s.cleanupConnection(); err != nil && !errors.Is(err, ErrServiceNotUp) {
+ log.Errorf("failed to cleanup connection: %v", err)
+ }
+ state := internal.CtxGetState(s.rootCtx)
+ state.Set(internal.StatusNeedsLogin)
+ }
+
+ return &proto.LogoutResponse{}, nil
+}
+
+func (s *Server) handleActiveProfileLogout(ctx context.Context) (*proto.LogoutResponse, error) {
+ if s.config == nil {
+ activeProf, err := s.profileManager.GetActiveProfileState()
+ if err != nil {
+ return nil, gstatus.Errorf(codes.FailedPrecondition, "failed to get active profile state: %v", err)
+ }
+
+ config, err := s.getConfig(activeProf)
+ if err != nil {
+ return nil, gstatus.Errorf(codes.FailedPrecondition, "not logged in")
+ }
+ s.config = config
+ }
+
+ if err := s.sendLogoutRequest(ctx); err != nil {
+ log.Errorf("failed to send logout request: %v", err)
+ return nil, err
+ }
+
+ if err := s.cleanupConnection(); err != nil && !errors.Is(err, ErrServiceNotUp) {
+ log.Errorf("failed to cleanup connection: %v", err)
+ return nil, err
+ }
+
+ state := internal.CtxGetState(s.rootCtx)
+ state.Set(internal.StatusNeedsLogin)
+
+ return &proto.LogoutResponse{}, nil
+}
+
+// getConfig loads the config from the active profile
+func (s *Server) getConfig(activeProf *profilemanager.ActiveProfileState) (*profilemanager.Config, error) {
+ cfgPath, err := activeProf.FilePath()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get active profile file path: %w", err)
+ }
+
+ config, err := profilemanager.GetConfig(cfgPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get config: %w", err)
+ }
+
+ return config, nil
+}
+
+func (s *Server) canRemoveProfile(profileName string) error {
+ if profileName == profilemanager.DefaultProfileName {
+ return fmt.Errorf("remove profile with reserved name: %s", profilemanager.DefaultProfileName)
+ }
+
+ activeProf, err := s.profileManager.GetActiveProfileState()
+ if err == nil && activeProf.Name == profileName {
+ return fmt.Errorf("remove active profile: %s", profileName)
+ }
+
+ return nil
+}
+
+func (s *Server) validateProfileOperation(profileName string, allowActiveProfile bool) error {
+ if s.checkProfilesDisabled() {
+ return gstatus.Errorf(codes.Unavailable, errProfilesDisabled)
+ }
+
+ if profileName == "" {
+ return gstatus.Errorf(codes.InvalidArgument, "profile name must be provided")
+ }
+
+ if !allowActiveProfile {
+ if err := s.canRemoveProfile(profileName); err != nil {
+ return gstatus.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ }
+
+ return nil
+}
+
+// logoutFromProfile logs out from a specific profile by loading its config and sending logout request
+func (s *Server) logoutFromProfile(ctx context.Context, profileName, username string) error {
+ activeProf, err := s.profileManager.GetActiveProfileState()
+ if err == nil && activeProf.Name == profileName && s.connectClient != nil {
+ return s.sendLogoutRequest(ctx)
+ }
+
+ profileState := &profilemanager.ActiveProfileState{
+ Name: profileName,
+ Username: username,
+ }
+ profilePath, err := profileState.FilePath()
+ if err != nil {
+ return fmt.Errorf("get profile path: %w", err)
+ }
+
+ config, err := profilemanager.GetConfig(profilePath)
+ if err != nil {
+ return fmt.Errorf("profile '%s' not found", profileName)
+ }
+
+ return s.sendLogoutRequestWithConfig(ctx, config)
+}
+
+func (s *Server) sendLogoutRequest(ctx context.Context) error {
+ return s.sendLogoutRequestWithConfig(ctx, s.config)
+}
+
+func (s *Server) sendLogoutRequestWithConfig(ctx context.Context, config *profilemanager.Config) error {
+ key, err := wgtypes.ParseKey(config.PrivateKey)
+ if err != nil {
+ return fmt.Errorf("parse private key: %w", err)
+ }
+
+ mgmTlsEnabled := config.ManagementURL.Scheme == "https"
+ mgmClient, err := mgm.NewClient(ctx, config.ManagementURL.Host, key, mgmTlsEnabled)
+ if err != nil {
+ return fmt.Errorf("connect to management server: %w", err)
+ }
+ defer func() {
+ if err := mgmClient.Close(); err != nil {
+ log.Errorf("close management client: %v", err)
+ }
+ }()
+
+ return mgmClient.Logout()
}
// Status returns the daemon status
@@ -1107,12 +1263,12 @@ func (s *Server) RemoveProfile(ctx context.Context, msg *proto.RemoveProfileRequ
s.mutex.Lock()
defer s.mutex.Unlock()
- if s.checkProfilesDisabled() {
- return nil, gstatus.Errorf(codes.Unavailable, errProfilesDisabled)
+ if err := s.validateProfileOperation(msg.ProfileName, false); err != nil {
+ return nil, err
}
- if msg.ProfileName == "" {
- return nil, gstatus.Errorf(codes.InvalidArgument, "profile name must be provided")
+ if err := s.logoutFromProfile(ctx, msg.ProfileName, msg.Username); err != nil {
+ log.Warnf("failed to logout from profile %s before removal: %v", msg.ProfileName, err)
}
if err := s.profileManager.RemoveProfile(msg.ProfileName, msg.Username); err != nil {
diff --git a/client/server/server_test.go b/client/server/server_test.go
index afd38b4a4..a88ca5412 100644
--- a/client/server/server_test.go
+++ b/client/server/server_test.go
@@ -24,7 +24,7 @@ import (
"github.com/netbirdio/netbird/client/internal/peer"
"github.com/netbirdio/netbird/client/internal/profilemanager"
daemonProto "github.com/netbirdio/netbird/client/proto"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/integrations/port_forwarding"
@@ -33,7 +33,7 @@ import (
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/types"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/signal/proto"
signalServer "github.com/netbirdio/netbird/signal/server"
)
@@ -94,7 +94,7 @@ func TestConnectWithRetryRuns(t *testing.T) {
t.Fatalf("failed to set active profile state: %v", err)
}
- s := New(ctx, "debug", false)
+ s := New(ctx, "debug", "", false)
s.config = config
@@ -151,7 +151,7 @@ func TestServer_Up(t *testing.T) {
t.Fatalf("failed to set active profile state: %v", err)
}
- s := New(ctx, "console", false)
+ s := New(ctx, "console", "", false)
err = s.Start()
require.NoError(t, err)
@@ -227,7 +227,7 @@ func TestServer_SubcribeEvents(t *testing.T) {
t.Fatalf("failed to set active profile state: %v", err)
}
- s := New(ctx, "console", false)
+ s := New(ctx, "console", "", false)
err = s.Start()
require.NoError(t, err)
diff --git a/client/status/status.go b/client/status/status.go
index 722ee7e7c..db5b7dc0b 100644
--- a/client/status/status.go
+++ b/client/status/status.go
@@ -16,7 +16,7 @@ import (
"github.com/netbirdio/netbird/client/anonymize"
"github.com/netbirdio/netbird/client/internal/peer"
"github.com/netbirdio/netbird/client/proto"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/version"
)
diff --git a/client/system/info.go b/client/system/info.go
index aff10ece3..ea3f6063a 100644
--- a/client/system/info.go
+++ b/client/system/info.go
@@ -8,7 +8,7 @@ import (
"google.golang.org/grpc/metadata"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
)
// DeviceNameCtxKey context key for device name
diff --git a/client/ui/client_ui.go b/client/ui/client_ui.go
index c74412c8b..88cb11eab 100644
--- a/client/ui/client_ui.go
+++ b/client/ui/client_ui.go
@@ -831,6 +831,7 @@ func (s *serviceClient) onTrayReady() {
s.mLazyConnEnabled = s.mSettings.AddSubMenuItemCheckbox("Enable Lazy Connections", lazyConnMenuDescr, false)
s.mBlockInbound = s.mSettings.AddSubMenuItemCheckbox("Block Inbound Connections", blockInboundMenuDescr, false)
s.mNotifications = s.mSettings.AddSubMenuItemCheckbox("Notifications", notificationsMenuDescr, false)
+ s.mSettings.AddSeparator()
s.mAdvancedSettings = s.mSettings.AddSubMenuItem("Advanced Settings", advancedSettingsMenuDescr)
s.mCreateDebugBundle = s.mSettings.AddSubMenuItem("Create Debug Bundle", debugBundleMenuDescr)
s.loadSettings()
diff --git a/client/ui/debug.go b/client/ui/debug.go
index a7f4868ac..76afc7753 100644
--- a/client/ui/debug.go
+++ b/client/ui/debug.go
@@ -395,12 +395,12 @@ func (s *serviceClient) configureServiceForDebug(
time.Sleep(time.Second)
if enablePersistence {
- if _, err := conn.SetNetworkMapPersistence(s.ctx, &proto.SetNetworkMapPersistenceRequest{
+ if _, err := conn.SetSyncResponsePersistence(s.ctx, &proto.SetSyncResponsePersistenceRequest{
Enabled: true,
}); err != nil {
- return fmt.Errorf("enable network map persistence: %v", err)
+ return fmt.Errorf("enable sync response persistence: %v", err)
}
- log.Info("Network map persistence enabled for debug")
+ log.Info("Sync response persistence enabled for debug")
}
if _, err := conn.Up(s.ctx, &proto.UpRequest{}); err != nil {
diff --git a/client/ui/event_handler.go b/client/ui/event_handler.go
index c0bc74a2c..e9b7f4f30 100644
--- a/client/ui/event_handler.go
+++ b/client/ui/event_handler.go
@@ -13,6 +13,7 @@ import (
"fyne.io/systray"
log "github.com/sirupsen/logrus"
+ "github.com/netbirdio/netbird/client/proto"
"github.com/netbirdio/netbird/version"
)
@@ -231,3 +232,19 @@ func (h *eventHandler) runSelfCommand(ctx context.Context, command, arg string)
log.Printf("command '%s %s' completed successfully", command, arg)
}
+
+func (h *eventHandler) logout(ctx context.Context) error {
+ client, err := h.client.getSrvClient(defaultFailTimeout)
+ if err != nil {
+ return fmt.Errorf("failed to get service client: %w", err)
+ }
+
+ _, err = client.Logout(ctx, &proto.LogoutRequest{})
+ if err != nil {
+ return fmt.Errorf("logout failed: %w", err)
+ }
+
+ h.client.getSrvConfig()
+
+ return nil
+}
diff --git a/client/ui/profile.go b/client/ui/profile.go
index 779f60aa4..b0502c1fb 100644
--- a/client/ui/profile.go
+++ b/client/ui/profile.go
@@ -40,12 +40,13 @@ func (s *serviceClient) showProfilesUI() {
list := widget.NewList(
func() int { return len(profiles) },
func() fyne.CanvasObject {
- // Each item: Selected indicator, Name, spacer, Select & Remove buttons
+ // Each item: Selected indicator, Name, spacer, Select, Logout & Remove buttons
return container.NewHBox(
widget.NewLabel(""), // indicator
widget.NewLabel(""), // profile name
layout.NewSpacer(),
widget.NewButton("Select", nil),
+ widget.NewButton("Logout", nil),
widget.NewButton("Remove", nil),
)
},
@@ -55,7 +56,8 @@ func (s *serviceClient) showProfilesUI() {
indicator := row.Objects[0].(*widget.Label)
nameLabel := row.Objects[1].(*widget.Label)
selectBtn := row.Objects[3].(*widget.Button)
- removeBtn := row.Objects[4].(*widget.Button)
+ logoutBtn := row.Objects[4].(*widget.Button)
+ removeBtn := row.Objects[5].(*widget.Button)
profile := profiles[i]
// Show a checkmark if selected
@@ -105,7 +107,7 @@ func (s *serviceClient) showProfilesUI() {
return
}
- status, err := conn.Status(context.Background(), &proto.StatusRequest{})
+ status, err := conn.Status(s.ctx, &proto.StatusRequest{})
if err != nil {
log.Errorf("failed to get status after switching profile: %v", err)
return
@@ -125,6 +127,12 @@ func (s *serviceClient) showProfilesUI() {
)
}
+ logoutBtn.Show()
+ logoutBtn.SetText("Logout")
+ logoutBtn.OnTapped = func() {
+ s.handleProfileLogout(profile.Name, refresh)
+ }
+
// Remove profile
removeBtn.SetText("Remove")
removeBtn.OnTapped = func() {
@@ -135,7 +143,7 @@ func (s *serviceClient) showProfilesUI() {
if !confirm {
return
}
- // remove
+
err = s.removeProfile(profile.Name)
if err != nil {
log.Errorf("failed to remove profile: %v", err)
@@ -230,7 +238,7 @@ func (s *serviceClient) addProfile(profileName string) error {
return fmt.Errorf("get current user: %w", err)
}
- _, err = conn.AddProfile(context.Background(), &proto.AddProfileRequest{
+ _, err = conn.AddProfile(s.ctx, &proto.AddProfileRequest{
ProfileName: profileName,
Username: currUser.Username,
})
@@ -253,7 +261,7 @@ func (s *serviceClient) switchProfile(profileName string) error {
return fmt.Errorf("get current user: %w", err)
}
- if _, err := conn.SwitchProfile(context.Background(), &proto.SwitchProfileRequest{
+ if _, err := conn.SwitchProfile(s.ctx, &proto.SwitchProfileRequest{
ProfileName: &profileName,
Username: &currUser.Username,
}); err != nil {
@@ -279,7 +287,7 @@ func (s *serviceClient) removeProfile(profileName string) error {
return fmt.Errorf("get current user: %w", err)
}
- _, err = conn.RemoveProfile(context.Background(), &proto.RemoveProfileRequest{
+ _, err = conn.RemoveProfile(s.ctx, &proto.RemoveProfileRequest{
ProfileName: profileName,
Username: currUser.Username,
})
@@ -305,7 +313,7 @@ func (s *serviceClient) getProfiles() ([]Profile, error) {
if err != nil {
return nil, fmt.Errorf("get current user: %w", err)
}
- profilesResp, err := conn.ListProfiles(context.Background(), &proto.ListProfilesRequest{
+ profilesResp, err := conn.ListProfiles(s.ctx, &proto.ListProfilesRequest{
Username: currUser.Username,
})
if err != nil {
@@ -324,6 +332,52 @@ func (s *serviceClient) getProfiles() ([]Profile, error) {
return profiles, nil
}
+func (s *serviceClient) handleProfileLogout(profileName string, refreshCallback func()) {
+ dialog.ShowConfirm(
+ "Logout",
+ fmt.Sprintf("Are you sure you want to logout from '%s'?", profileName),
+ func(confirm bool) {
+ if !confirm {
+ return
+ }
+
+ conn, err := s.getSrvClient(defaultFailTimeout)
+ if err != nil {
+ log.Errorf("failed to get service client: %v", err)
+ dialog.ShowError(fmt.Errorf("failed to connect to service"), s.wProfiles)
+ return
+ }
+
+ currUser, err := user.Current()
+ if err != nil {
+ log.Errorf("failed to get current user: %v", err)
+ dialog.ShowError(fmt.Errorf("failed to get current user"), s.wProfiles)
+ return
+ }
+
+ username := currUser.Username
+ _, err = conn.Logout(s.ctx, &proto.LogoutRequest{
+ ProfileName: &profileName,
+ Username: &username,
+ })
+ if err != nil {
+ log.Errorf("logout failed: %v", err)
+ dialog.ShowError(fmt.Errorf("logout failed"), s.wProfiles)
+ return
+ }
+
+ dialog.ShowInformation(
+ "Logged Out",
+ fmt.Sprintf("Successfully logged out from '%s'", profileName),
+ s.wProfiles,
+ )
+
+ refreshCallback()
+ },
+ s.wProfiles,
+ )
+}
+
type subItem struct {
*systray.MenuItem
ctx context.Context
@@ -339,6 +393,7 @@ type profileMenu struct {
emailMenuItem *systray.MenuItem
profileSubItems []*subItem
manageProfilesSubItem *subItem
+ logoutSubItem *subItem
profilesState []Profile
downClickCallback func() error
upClickCallback func() error
@@ -533,12 +588,11 @@ func (p *profileMenu) refresh() {
for {
select {
case <-ctx.Done():
- return // context cancelled
+ return
case _, ok := <-manageItem.ClickedCh:
if !ok {
- return // channel closed
+ return
}
- // Handle manage profiles click
p.eventHandler.runSelfCommand(p.ctx, "profiles", "true")
p.refresh()
p.loadSettingsCallback()
@@ -546,6 +600,30 @@ func (p *profileMenu) refresh() {
}
}()
+ // Add Logout menu item
+ ctx2, cancel2 := context.WithCancel(context.Background())
+ logoutItem := p.profileMenuItem.AddSubMenuItem("Logout", "")
+ p.logoutSubItem = &subItem{logoutItem, ctx2, cancel2}
+
+ go func() {
+ for {
+ select {
+ case <-ctx2.Done():
+ return
+ case _, ok := <-logoutItem.ClickedCh:
+ if !ok {
+ return
+ }
+ if err := p.eventHandler.logout(p.ctx); err != nil {
+ log.Errorf("logout failed: %v", err)
+ p.app.SendNotification(fyne.NewNotification("Error", "Failed to logout"))
+ } else {
+ p.app.SendNotification(fyne.NewNotification("Success", "Logged out successfully"))
+ }
+ }
+ }
+ }()
+
if activeProf.ProfileName == "default" || activeProf.Username == currUser.Username {
p.profileMenuItem.SetTitle(activeProf.ProfileName)
} else {
@@ -556,7 +634,6 @@ func (p *profileMenu) refresh() {
}
func (p *profileMenu) clear(profiles []Profile) {
- // Clear existing profile items
for _, item := range p.profileSubItems {
item.Remove()
item.cancel()
@@ -565,11 +642,16 @@ func (p *profileMenu) clear(profiles []Profile) {
p.profilesState = profiles
if p.manageProfilesSubItem != nil {
- // Remove the manage profiles item if it exists
p.manageProfilesSubItem.Remove()
p.manageProfilesSubItem.cancel()
p.manageProfilesSubItem = nil
}
+
+ if p.logoutSubItem != nil {
+ p.logoutSubItem.Remove()
+ p.logoutSubItem.cancel()
+ p.logoutSubItem = nil
+ }
}
func (p *profileMenu) updateMenu() {
diff --git a/formatter/hook/hook.go b/formatter/hook/hook.go
index 290c3377d..c0d8c4eba 100644
--- a/formatter/hook/hook.go
+++ b/formatter/hook/hook.go
@@ -9,7 +9,7 @@ import (
"github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/management/server/context"
+ "github.com/netbirdio/netbird/shared/context"
)
type ExecutionContext string
diff --git a/go.mod b/go.mod
index 4d9191d04..c6a795424 100644
--- a/go.mod
+++ b/go.mod
@@ -63,8 +63,8 @@ require (
github.com/miekg/dns v1.1.59
github.com/mitchellh/hashstructure/v2 v2.0.2
github.com/nadoo/ipset v0.5.0
- github.com/netbirdio/management-integrations/integrations v0.0.0-20250724151510-c007bc6b392c
- github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250514131221-a464fd5f30cb
+ github.com/netbirdio/management-integrations/integrations v0.0.0-20250805121557-5f225a973d1f
+ github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250805121659-6b4ac470ca45
github.com/okta/okta-sdk-golang/v2 v2.18.0
github.com/oschwald/maxminddb-golang v1.12.0
github.com/patrickmn/go-cache v2.1.0+incompatible
diff --git a/go.sum b/go.sum
index 84dfe2403..db7918e24 100644
--- a/go.sum
+++ b/go.sum
@@ -503,12 +503,12 @@ github.com/netbirdio/go-netroute v0.0.0-20240611143515-f59b0e1d3944 h1:TDtJKmM6S
github.com/netbirdio/go-netroute v0.0.0-20240611143515-f59b0e1d3944/go.mod h1:sHA6TRxjQ6RLbnI+3R4DZo2Eseg/iKiPRfNmcuNySVQ=
github.com/netbirdio/ice/v3 v3.0.0-20240315174635-e72a50fcb64e h1:PURA50S8u4mF6RrkYYCAvvPCixhqqEiEy3Ej6avh04c=
github.com/netbirdio/ice/v3 v3.0.0-20240315174635-e72a50fcb64e/go.mod h1:YMLU7qbKfVjmEv7EoZPIVEI+kNYxWCdPK3VS0BU+U4Q=
-github.com/netbirdio/management-integrations/integrations v0.0.0-20250724151510-c007bc6b392c h1:OtX903X0FKEE+fcsp/P2701md7X/xbi/W/ojWIJNKSk=
-github.com/netbirdio/management-integrations/integrations v0.0.0-20250724151510-c007bc6b392c/go.mod h1:Gi9raplYzCCyh07Olw/DVfCJTFgpr1WCXJ/Q+8TSA9Q=
+github.com/netbirdio/management-integrations/integrations v0.0.0-20250805121557-5f225a973d1f h1:YmqNWdRbeVn1lSpkLzIiFHX2cndRuaVYyynx2ibrOtg=
+github.com/netbirdio/management-integrations/integrations v0.0.0-20250805121557-5f225a973d1f/go.mod h1:Gi9raplYzCCyh07Olw/DVfCJTFgpr1WCXJ/Q+8TSA9Q=
github.com/netbirdio/service v0.0.0-20240911161631-f62744f42502 h1:3tHlFmhTdX9axERMVN63dqyFqnvuD+EMJHzM7mNGON8=
github.com/netbirdio/service v0.0.0-20240911161631-f62744f42502/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM=
-github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250514131221-a464fd5f30cb h1:Cr6age+ePALqlSvtp7wc6lYY97XN7rkD1K4XEDmY+TU=
-github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250514131221-a464fd5f30cb/go.mod h1:5/sjFmLb8O96B5737VCqhHyGRzNFIaN/Bu7ZodXc3qQ=
+github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250805121659-6b4ac470ca45 h1:ujgviVYmx243Ksy7NdSwrdGPSRNE3pb8kEDSpH0QuAQ=
+github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250805121659-6b4ac470ca45/go.mod h1:5/sjFmLb8O96B5737VCqhHyGRzNFIaN/Bu7ZodXc3qQ=
github.com/netbirdio/wireguard-go v0.0.0-20241230120307-6a676aebaaf6 h1:X5h5QgP7uHAv78FWgHV8+WYLjHxK9v3ilkVXT1cpCrQ=
github.com/netbirdio/wireguard-go v0.0.0-20241230120307-6a676aebaaf6/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA=
github.com/nicksnyder/go-i18n/v2 v2.4.0 h1:3IcvPOAvnCKwNm0TB0dLDTuawWEj+ax/RERNC+diLMM=
diff --git a/management/LICENSE b/management/LICENSE
new file mode 100644
index 000000000..be3f7b28e
--- /dev/null
+++ b/management/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ 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
+them 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey 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;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ 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.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+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.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ 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
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/management/cmd/management.go b/management/cmd/management.go
index 24c260e9c..a695767ad 100644
--- a/management/cmd/management.go
+++ b/management/cmd/management.go
@@ -40,7 +40,7 @@ import (
"github.com/netbirdio/netbird/encryption"
"github.com/netbirdio/netbird/formatter/hook"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server"
"github.com/netbirdio/netbird/management/server/auth"
nbContext "github.com/netbirdio/netbird/management/server/context"
@@ -142,7 +142,7 @@ var (
err := handleRebrand(cmd)
if err != nil {
- return fmt.Errorf("failed to migrate files %v", err)
+ return fmt.Errorf("migrate files %v", err)
}
if _, err = os.Stat(config.Datadir); os.IsNotExist(err) {
@@ -184,7 +184,7 @@ var (
}
eventStore, key, err := integrations.InitEventStore(ctx, config.Datadir, config.DataStoreEncryptionKey, integrationMetrics)
if err != nil {
- return fmt.Errorf("failed to initialize database: %s", err)
+ return fmt.Errorf("initialize database: %s", err)
}
if config.DataStoreEncryptionKey != key {
@@ -192,7 +192,7 @@ var (
config.DataStoreEncryptionKey = key
err := updateMgmtConfig(ctx, types.MgmtConfigPath, config)
if err != nil {
- return fmt.Errorf("failed to write out store encryption key: %s", err)
+ return fmt.Errorf("write out store encryption key: %s", err)
}
}
@@ -205,7 +205,7 @@ var (
integratedPeerValidator, err := integrations.NewIntegratedValidator(ctx, eventStore)
if err != nil {
- return fmt.Errorf("failed to initialize integrated peer validator: %v", err)
+ return fmt.Errorf("initialize integrated peer validator: %v", err)
}
permissionsManager := integrations.InitPermissionsManager(store)
@@ -217,7 +217,7 @@ var (
accountManager, err := server.BuildManager(ctx, store, peersUpdateManager, idpManager, mgmtSingleAccModeDomain,
dnsDomain, eventStore, geo, userDeleteFromIDPEnabled, integratedPeerValidator, appMetrics, proxyController, settingsManager, permissionsManager, config.DisableDefaultPolicy)
if err != nil {
- return fmt.Errorf("failed to build default manager: %v", err)
+ return fmt.Errorf("build default manager: %v", err)
}
secretsManager := server.NewTimeBasedAuthSecretsManager(peersUpdateManager, config.TURNConfig, config.Relay, settingsManager)
diff --git a/management/server/account.go b/management/server/account.go
index 52b625da1..49ea38fe1 100644
--- a/management/server/account.go
+++ b/management/server/account.go
@@ -6,6 +6,7 @@ import (
"fmt"
"math/rand"
"net"
+ "net/netip"
"os"
"reflect"
"regexp"
@@ -39,7 +40,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions/operations"
"github.com/netbirdio/netbird/management/server/posture"
"github.com/netbirdio/netbird/management/server/settings"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/types"
@@ -250,8 +251,8 @@ func BuildManager(
}()
}
- am.integratedPeerValidator.SetPeerInvalidationListener(func(accountID string) {
- am.onPeersInvalidated(ctx, accountID)
+ am.integratedPeerValidator.SetPeerInvalidationListener(func(accountID string, peerIDs []string) {
+ am.onPeersInvalidated(ctx, accountID, peerIDs)
})
return am, nil
@@ -324,6 +325,13 @@ func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, acco
return err
}
+ if oldSettings.NetworkRange != newSettings.NetworkRange {
+ if err = am.reallocateAccountPeerIPs(ctx, transaction, accountID, newSettings.NetworkRange); err != nil {
+ return err
+ }
+ updateAccountPeers = true
+ }
+
if oldSettings.RoutingPeerDNSResolutionEnabled != newSettings.RoutingPeerDNSResolutionEnabled ||
oldSettings.LazyConnectionEnabled != newSettings.LazyConnectionEnabled ||
oldSettings.DNSDomain != newSettings.DNSDomain {
@@ -362,7 +370,18 @@ func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, acco
return nil, err
}
if oldSettings.DNSDomain != newSettings.DNSDomain {
- am.StoreEvent(ctx, userID, accountID, accountID, activity.AccountDNSDomainUpdated, nil)
+ eventMeta := map[string]any{
+ "old_dns_domain": oldSettings.DNSDomain,
+ "new_dns_domain": newSettings.DNSDomain,
+ }
+ am.StoreEvent(ctx, userID, accountID, accountID, activity.AccountDNSDomainUpdated, eventMeta)
+ }
+ if oldSettings.NetworkRange != newSettings.NetworkRange {
+ eventMeta := map[string]any{
+ "old_network_range": oldSettings.NetworkRange.String(),
+ "new_network_range": newSettings.NetworkRange.String(),
+ }
+ am.StoreEvent(ctx, userID, accountID, accountID, activity.AccountNetworkRangeUpdated, eventMeta)
}
if updateAccountPeers || extraSettingsChanged || groupChangesAffectPeers {
@@ -1368,7 +1387,7 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth
return nil
}
- if err = transaction.SaveGroups(ctx, store.LockingStrengthUpdate, userAuth.AccountId, newGroupsToCreate); err != nil {
+ if err = transaction.CreateGroups(ctx, store.LockingStrengthUpdate, userAuth.AccountId, newGroupsToCreate); err != nil {
return fmt.Errorf("error saving groups: %w", err)
}
@@ -1382,28 +1401,22 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth
// Propagate changes to peers if group propagation is enabled
if settings.GroupsPropagationEnabled {
- groups, err = transaction.GetAccountGroups(ctx, store.LockingStrengthShare, userAuth.AccountId)
- if err != nil {
- return fmt.Errorf("error getting account groups: %w", err)
- }
-
- groupsMap := make(map[string]*types.Group, len(groups))
- for _, group := range groups {
- groupsMap[group.ID] = group
- }
-
peers, err := transaction.GetUserPeers(ctx, store.LockingStrengthShare, userAuth.AccountId, userAuth.UserId)
if err != nil {
return fmt.Errorf("error getting user peers: %w", err)
}
- updatedGroups, err := updateUserPeersInGroups(groupsMap, peers, addNewGroups, removeOldGroups)
- if err != nil {
- return fmt.Errorf("error modifying user peers in groups: %w", err)
- }
-
- if err = transaction.SaveGroups(ctx, store.LockingStrengthUpdate, userAuth.AccountId, updatedGroups); err != nil {
- return fmt.Errorf("error saving groups: %w", err)
+ for _, peer := range peers {
+ for _, g := range addNewGroups {
+ if err := transaction.AddPeerToGroup(ctx, userAuth.AccountId, peer.ID, g); err != nil {
+ return fmt.Errorf("error adding peer %s to group %s: %w", peer.ID, g, err)
+ }
+ }
+ for _, g := range removeOldGroups {
+ if err := transaction.RemovePeerFromGroup(ctx, peer.ID, g); err != nil {
+ return fmt.Errorf("error removing peer %s from group %s: %w", peer.ID, g, err)
+ }
+ }
}
if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, userAuth.AccountId); err != nil {
@@ -1706,9 +1719,27 @@ func (am *DefaultAccountManager) GetDNSDomain(settings *types.Settings) string {
return settings.DNSDomain
}
-func (am *DefaultAccountManager) onPeersInvalidated(ctx context.Context, accountID string) {
- log.WithContext(ctx).Debugf("validated peers has been invalidated for account %s", accountID)
- am.BufferUpdateAccountPeers(ctx, accountID)
+func (am *DefaultAccountManager) onPeersInvalidated(ctx context.Context, accountID string, peerIDs []string) {
+ peers := []*nbpeer.Peer{}
+ log.WithContext(ctx).Debugf("invalidating peers %v for account %s", peerIDs, accountID)
+ for _, peerID := range peerIDs {
+ peer, err := am.GetPeer(ctx, accountID, peerID, activity.SystemInitiator)
+ if err != nil {
+ log.WithContext(ctx).Errorf("failed to get invalidated peer %s for account %s: %v", peerID, accountID, err)
+ continue
+ }
+ peers = append(peers, peer)
+ }
+ if len(peers) > 0 {
+ err := am.expireAndUpdatePeers(ctx, accountID, peers)
+ if err != nil {
+ log.WithContext(ctx).Errorf("failed to expire and update invalidated peers for account %s: %v", accountID, err)
+ return
+ }
+ } else {
+ log.WithContext(ctx).Debugf("running invalidation with no invalid peers")
+ }
+ log.WithContext(ctx).Debugf("invalidated peers have been expired for account %s", accountID)
}
func (am *DefaultAccountManager) FindExistingPostureCheck(accountID string, checks *posture.ChecksDefinition) (*posture.Checks, error) {
@@ -1971,53 +2002,207 @@ func (am *DefaultAccountManager) UpdateToPrimaryAccount(ctx context.Context, acc
// propagateUserGroupMemberships propagates all account users' group memberships to their peers.
// Returns true if any groups were modified, true if those updates affect peers and an error.
func propagateUserGroupMemberships(ctx context.Context, transaction store.Store, accountID string) (groupsUpdated bool, peersAffected bool, err error) {
- groups, err := transaction.GetAccountGroups(ctx, store.LockingStrengthShare, accountID)
- if err != nil {
- return false, false, err
- }
-
- groupsMap := make(map[string]*types.Group, len(groups))
- for _, group := range groups {
- groupsMap[group.ID] = group
- }
-
users, err := transaction.GetAccountUsers(ctx, store.LockingStrengthShare, accountID)
if err != nil {
return false, false, err
}
- groupsToUpdate := make(map[string]*types.Group)
+ accountGroupPeers, err := transaction.GetAccountGroupPeers(ctx, store.LockingStrengthShare, accountID)
+ if err != nil {
+ return false, false, fmt.Errorf("error getting account group peers: %w", err)
+ }
+ accountGroups, err := transaction.GetAccountGroups(ctx, store.LockingStrengthShare, accountID)
+ if err != nil {
+ return false, false, fmt.Errorf("error getting account groups: %w", err)
+ }
+
+ for _, group := range accountGroups {
+ if _, exists := accountGroupPeers[group.ID]; !exists {
+ accountGroupPeers[group.ID] = make(map[string]struct{})
+ }
+ }
+
+ updatedGroups := []string{}
for _, user := range users {
userPeers, err := transaction.GetUserPeers(ctx, store.LockingStrengthShare, accountID, user.Id)
if err != nil {
return false, false, err
}
- updatedGroups, err := updateUserPeersInGroups(groupsMap, userPeers, user.AutoGroups, nil)
- if err != nil {
- return false, false, err
- }
-
- for _, group := range updatedGroups {
- groupsToUpdate[group.ID] = group
- groupsMap[group.ID] = group
+ for _, peer := range userPeers {
+ for _, groupID := range user.AutoGroups {
+ if _, exists := accountGroupPeers[groupID]; !exists {
+ // we do not wanna create the groups here
+ log.WithContext(ctx).Warnf("group %s does not exist for user group propagation", groupID)
+ continue
+ }
+ if _, exists := accountGroupPeers[groupID][peer.ID]; exists {
+ continue
+ }
+ if err := transaction.AddPeerToGroup(ctx, accountID, peer.ID, groupID); err != nil {
+ return false, false, fmt.Errorf("error adding peer %s to group %s: %w", peer.ID, groupID, err)
+ }
+ updatedGroups = append(updatedGroups, groupID)
+ }
}
}
- if len(groupsToUpdate) == 0 {
- return false, false, nil
- }
-
- peersAffected, err = areGroupChangesAffectPeers(ctx, transaction, accountID, maps.Keys(groupsToUpdate))
+ peersAffected, err = areGroupChangesAffectPeers(ctx, transaction, accountID, updatedGroups)
if err != nil {
- return false, false, err
+ return false, false, fmt.Errorf("error checking if group changes affect peers: %w", err)
}
- err = transaction.SaveGroups(ctx, store.LockingStrengthUpdate, accountID, maps.Values(groupsToUpdate))
- if err != nil {
- return false, false, err
- }
-
- return true, peersAffected, nil
+ return len(updatedGroups) > 0, peersAffected, nil
+}
+
+// reallocateAccountPeerIPs re-allocates all peer IPs when the network range changes
+func (am *DefaultAccountManager) reallocateAccountPeerIPs(ctx context.Context, transaction store.Store, accountID string, newNetworkRange netip.Prefix) error {
+ if !newNetworkRange.IsValid() {
+ return nil
+ }
+
+ newIPNet := net.IPNet{
+ IP: newNetworkRange.Masked().Addr().AsSlice(),
+ Mask: net.CIDRMask(newNetworkRange.Bits(), newNetworkRange.Addr().BitLen()),
+ }
+
+ account, err := transaction.GetAccount(ctx, accountID)
+ if err != nil {
+ return err
+ }
+
+ account.Network.Net = newIPNet
+
+ peers, err := transaction.GetAccountPeers(ctx, store.LockingStrengthShare, accountID, "", "")
+ if err != nil {
+ return err
+ }
+
+ var takenIPs []net.IP
+
+ for _, peer := range peers {
+ newIP, err := types.AllocatePeerIP(newIPNet, takenIPs)
+ if err != nil {
+ return status.Errorf(status.Internal, "allocate IP for peer %s: %v", peer.ID, err)
+ }
+
+ log.WithContext(ctx).Infof("reallocating peer %s IP from %s to %s due to network range change",
+ peer.ID, peer.IP.String(), newIP.String())
+
+ peer.IP = newIP
+ takenIPs = append(takenIPs, newIP)
+ }
+
+ if err = transaction.SaveAccount(ctx, account); err != nil {
+ return err
+ }
+
+ for _, peer := range peers {
+ if err = transaction.SavePeer(ctx, store.LockingStrengthUpdate, accountID, peer); err != nil {
+ return status.Errorf(status.Internal, "save updated peer %s: %v", peer.ID, err)
+ }
+ }
+
+ log.WithContext(ctx).Infof("successfully re-allocated IPs for %d peers in account %s to network range %s",
+ len(peers), accountID, newNetworkRange.String())
+
+ return nil
+}
+
+func (am *DefaultAccountManager) validateIPForUpdate(account *types.Account, peers []*nbpeer.Peer, peerID string, newIP netip.Addr) error {
+ if !account.Network.Net.Contains(newIP.AsSlice()) {
+ return status.Errorf(status.InvalidArgument, "IP %s is not within the account network range %s", newIP.String(), account.Network.Net.String())
+ }
+
+ for _, peer := range peers {
+ if peer.ID != peerID && peer.IP.Equal(newIP.AsSlice()) {
+ return status.Errorf(status.InvalidArgument, "IP %s is already assigned to peer %s", newIP.String(), peer.ID)
+ }
+ }
+ return nil
+}
+
+func (am *DefaultAccountManager) UpdatePeerIP(ctx context.Context, accountID, userID, peerID string, newIP netip.Addr) error {
+ unlock := am.Store.AcquireWriteLockByUID(ctx, accountID)
+ defer unlock()
+
+ allowed, err := am.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Peers, operations.Update)
+ if err != nil {
+ return fmt.Errorf("validate user permissions: %w", err)
+ }
+ if !allowed {
+ return status.NewPermissionDeniedError()
+ }
+
+ updateNetworkMap, err := am.updatePeerIPInTransaction(ctx, accountID, userID, peerID, newIP)
+ if err != nil {
+ return fmt.Errorf("update peer IP transaction: %w", err)
+ }
+
+ if updateNetworkMap {
+ am.BufferUpdateAccountPeers(ctx, accountID)
+ }
+ return nil
+}
+
+func (am *DefaultAccountManager) updatePeerIPInTransaction(ctx context.Context, accountID, userID, peerID string, newIP netip.Addr) (bool, error) {
+ var updateNetworkMap bool
+ err := am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
+ account, err := transaction.GetAccount(ctx, accountID)
+ if err != nil {
+ return fmt.Errorf("get account: %w", err)
+ }
+
+ existingPeer, err := transaction.GetPeerByID(ctx, store.LockingStrengthShare, accountID, peerID)
+ if err != nil {
+ return fmt.Errorf("get peer: %w", err)
+ }
+
+ if existingPeer.IP.Equal(newIP.AsSlice()) {
+ return nil
+ }
+
+ peers, err := transaction.GetAccountPeers(ctx, store.LockingStrengthShare, accountID, "", "")
+ if err != nil {
+ return fmt.Errorf("get account peers: %w", err)
+ }
+
+ if err := am.validateIPForUpdate(account, peers, peerID, newIP); err != nil {
+ return err
+ }
+
+ if err := am.savePeerIPUpdate(ctx, transaction, accountID, userID, existingPeer, newIP); err != nil {
+ return err
+ }
+
+ updateNetworkMap = true
+ return nil
+ })
+ return updateNetworkMap, err
+}
+
+func (am *DefaultAccountManager) savePeerIPUpdate(ctx context.Context, transaction store.Store, accountID, userID string, peer *nbpeer.Peer, newIP netip.Addr) error {
+ log.WithContext(ctx).Infof("updating peer %s IP from %s to %s", peer.ID, peer.IP, newIP)
+
+ settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthShare, accountID)
+ if err != nil {
+ return fmt.Errorf("get account settings: %w", err)
+ }
+ dnsDomain := am.GetDNSDomain(settings)
+
+ eventMeta := peer.EventMeta(dnsDomain)
+ oldIP := peer.IP.String()
+
+ peer.IP = newIP.AsSlice()
+ err = transaction.SavePeer(ctx, store.LockingStrengthUpdate, accountID, peer)
+ if err != nil {
+ return fmt.Errorf("save peer: %w", err)
+ }
+
+ eventMeta["old_ip"] = oldIP
+ eventMeta["ip"] = newIP.String()
+ am.StoreEvent(ctx, userID, peer.ID, accountID, activity.PeerIPUpdated, eventMeta)
+
+ return nil
}
diff --git a/management/server/account/manager.go b/management/server/account/manager.go
index 8c7e95e3d..ee82346f3 100644
--- a/management/server/account/manager.go
+++ b/management/server/account/manager.go
@@ -7,7 +7,7 @@ import (
"time"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/management/server/activity"
nbcache "github.com/netbirdio/netbird/management/server/cache"
nbcontext "github.com/netbirdio/netbird/management/server/context"
@@ -51,6 +51,7 @@ type Manager interface {
MarkPeerConnected(ctx context.Context, peerKey string, connected bool, realIP net.IP, accountID string) error
DeletePeer(ctx context.Context, accountID, peerID, userID string) error
UpdatePeer(ctx context.Context, accountID, userID string, peer *nbpeer.Peer) (*nbpeer.Peer, error)
+ UpdatePeerIP(ctx context.Context, accountID, userID, peerID string, newIP netip.Addr) error
GetNetworkMap(ctx context.Context, peerID string) (*types.NetworkMap, error)
GetPeerNetwork(ctx context.Context, peerID string) (*types.Network, error)
AddPeer(ctx context.Context, setupKey, userID string, peer *nbpeer.Peer) (*nbpeer.Peer, *types.NetworkMap, []*posture.Checks, error)
@@ -62,8 +63,10 @@ type Manager interface {
GetGroup(ctx context.Context, accountId, groupID, userID string) (*types.Group, error)
GetAllGroups(ctx context.Context, accountID, userID string) ([]*types.Group, error)
GetGroupByName(ctx context.Context, groupName, accountID string) (*types.Group, error)
- SaveGroup(ctx context.Context, accountID, userID string, group *types.Group, create bool) error
- SaveGroups(ctx context.Context, accountID, userID string, newGroups []*types.Group, create bool) error
+ CreateGroup(ctx context.Context, accountID, userID string, group *types.Group) error
+ UpdateGroup(ctx context.Context, accountID, userID string, group *types.Group) error
+ CreateGroups(ctx context.Context, accountID, userID string, newGroups []*types.Group) error
+ UpdateGroups(ctx context.Context, accountID, userID string, newGroups []*types.Group) error
DeleteGroup(ctx context.Context, accountId, userId, groupID string) error
DeleteGroups(ctx context.Context, accountId, userId string, groupIDs []string) error
GroupAddPeer(ctx context.Context, accountId, groupID, peerID string) error
diff --git a/management/server/account_test.go b/management/server/account_test.go
index b65dffe6c..77014855f 100644
--- a/management/server/account_test.go
+++ b/management/server/account_test.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net"
+ "net/netip"
"os"
"reflect"
"strconv"
@@ -1159,7 +1160,7 @@ func TestAccountManager_NetworkUpdates_SaveGroup(t *testing.T) {
Name: "GroupA",
Peers: []string{},
}
- if err := manager.SaveGroup(context.Background(), account.Id, userID, &group, true); err != nil {
+ if err := manager.CreateGroup(context.Background(), account.Id, userID, &group); err != nil {
t.Errorf("save group: %v", err)
return
}
@@ -1194,7 +1195,7 @@ func TestAccountManager_NetworkUpdates_SaveGroup(t *testing.T) {
}()
group.Peers = []string{peer1.ID, peer2.ID, peer3.ID}
- if err := manager.SaveGroup(context.Background(), account.Id, userID, &group, true); err != nil {
+ if err := manager.UpdateGroup(context.Background(), account.Id, userID, &group); err != nil {
t.Errorf("save group: %v", err)
return
}
@@ -1240,11 +1241,12 @@ func TestAccountManager_NetworkUpdates_SavePolicy(t *testing.T) {
manager, account, peer1, peer2, _ := setupNetworkMapTest(t)
group := types.Group{
- ID: "groupA",
- Name: "GroupA",
- Peers: []string{peer1.ID, peer2.ID},
+ AccountID: account.Id,
+ ID: "groupA",
+ Name: "GroupA",
+ Peers: []string{peer1.ID, peer2.ID},
}
- if err := manager.SaveGroup(context.Background(), account.Id, userID, &group, true); err != nil {
+ if err := manager.CreateGroup(context.Background(), account.Id, userID, &group); err != nil {
t.Errorf("save group: %v", err)
return
}
@@ -1292,7 +1294,7 @@ func TestAccountManager_NetworkUpdates_DeletePeer(t *testing.T) {
Name: "GroupA",
Peers: []string{peer1.ID, peer3.ID},
}
- if err := manager.SaveGroup(context.Background(), account.Id, userID, &group, true); err != nil {
+ if err := manager.CreateGroup(context.Background(), account.Id, userID, &group); err != nil {
t.Errorf("save group: %v", err)
return
}
@@ -1343,11 +1345,11 @@ func TestAccountManager_NetworkUpdates_DeleteGroup(t *testing.T) {
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1.ID)
defer manager.peersUpdateManager.CloseChannel(context.Background(), peer1.ID)
- err := manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err := manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupA",
Name: "GroupA",
Peers: []string{peer1.ID, peer2.ID, peer3.ID},
- }, true)
+ })
require.NoError(t, err, "failed to save group")
@@ -1672,9 +1674,10 @@ func TestAccount_Copy(t *testing.T) {
},
Groups: map[string]*types.Group{
"group1": {
- ID: "group1",
- Peers: []string{"peer1"},
- Resources: []types.Resource{},
+ ID: "group1",
+ Peers: []string{"peer1"},
+ Resources: []types.Resource{},
+ GroupPeers: []types.GroupPeer{},
},
},
Policies: []*types.Policy{
@@ -2616,6 +2619,7 @@ func TestAccount_GetNextInactivePeerExpiration(t *testing.T) {
}
func TestAccount_SetJWTGroups(t *testing.T) {
+ t.Setenv("NETBIRD_STORE_ENGINE", "postgres")
manager, err := createManager(t)
require.NoError(t, err, "unable to create account manager")
@@ -3360,7 +3364,7 @@ func TestPropagateUserGroupMemberships(t *testing.T) {
t.Run("should update membership but no account peers update for unused groups", func(t *testing.T) {
group1 := &types.Group{ID: "group1", Name: "Group 1", AccountID: account.Id}
- require.NoError(t, manager.Store.SaveGroup(ctx, store.LockingStrengthUpdate, group1))
+ require.NoError(t, manager.Store.CreateGroup(ctx, store.LockingStrengthUpdate, group1))
user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorId)
require.NoError(t, err)
@@ -3382,7 +3386,7 @@ func TestPropagateUserGroupMemberships(t *testing.T) {
t.Run("should update membership and account peers for used groups", func(t *testing.T) {
group2 := &types.Group{ID: "group2", Name: "Group 2", AccountID: account.Id}
- require.NoError(t, manager.Store.SaveGroup(ctx, store.LockingStrengthUpdate, group2))
+ require.NoError(t, manager.Store.CreateGroup(ctx, store.LockingStrengthUpdate, group2))
user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorId)
require.NoError(t, err)
@@ -3519,3 +3523,70 @@ func TestDefaultAccountManager_UpdateAccountOnboarding(t *testing.T) {
require.NoError(t, err)
})
}
+
+func TestDefaultAccountManager_UpdatePeerIP(t *testing.T) {
+ manager, err := createManager(t)
+ require.NoError(t, err, "unable to create account manager")
+
+ accountID, err := manager.GetAccountIDByUserID(context.Background(), userID, "")
+ require.NoError(t, err, "unable to create an account")
+
+ key1, err := wgtypes.GenerateKey()
+ require.NoError(t, err, "unable to generate WireGuard key")
+ key2, err := wgtypes.GenerateKey()
+ require.NoError(t, err, "unable to generate WireGuard key")
+
+ peer1, _, _, err := manager.AddPeer(context.Background(), "", userID, &nbpeer.Peer{
+ Key: key1.PublicKey().String(),
+ Meta: nbpeer.PeerSystemMeta{Hostname: "test-peer-1"},
+ })
+ require.NoError(t, err, "unable to add peer1")
+
+ peer2, _, _, err := manager.AddPeer(context.Background(), "", userID, &nbpeer.Peer{
+ Key: key2.PublicKey().String(),
+ Meta: nbpeer.PeerSystemMeta{Hostname: "test-peer-2"},
+ })
+ require.NoError(t, err, "unable to add peer2")
+
+ t.Run("update peer IP successfully", func(t *testing.T) {
+ account, err := manager.Store.GetAccount(context.Background(), accountID)
+ require.NoError(t, err, "unable to get account")
+
+ newIP, err := types.AllocatePeerIP(account.Network.Net, []net.IP{peer1.IP, peer2.IP})
+ require.NoError(t, err, "unable to allocate new IP")
+
+ newAddr := netip.MustParseAddr(newIP.String())
+ err = manager.UpdatePeerIP(context.Background(), accountID, userID, peer1.ID, newAddr)
+ require.NoError(t, err, "unable to update peer IP")
+
+ updatedPeer, err := manager.GetPeer(context.Background(), accountID, peer1.ID, userID)
+ require.NoError(t, err, "unable to get updated peer")
+ assert.Equal(t, newIP.String(), updatedPeer.IP.String(), "peer IP should be updated")
+ })
+
+ t.Run("update peer IP with same IP should be no-op", func(t *testing.T) {
+ currentAddr := netip.MustParseAddr(peer1.IP.String())
+ err := manager.UpdatePeerIP(context.Background(), accountID, userID, peer1.ID, currentAddr)
+ require.NoError(t, err, "updating with same IP should not error")
+ })
+
+ t.Run("update peer IP with collision should fail", func(t *testing.T) {
+ peer2Addr := netip.MustParseAddr(peer2.IP.String())
+ err := manager.UpdatePeerIP(context.Background(), accountID, userID, peer1.ID, peer2Addr)
+ require.Error(t, err, "should fail when IP is already assigned")
+ assert.Contains(t, err.Error(), "already assigned", "error should mention IP collision")
+ })
+
+ t.Run("update peer IP outside network range should fail", func(t *testing.T) {
+ invalidAddr := netip.MustParseAddr("192.168.1.100")
+ err := manager.UpdatePeerIP(context.Background(), accountID, userID, peer1.ID, invalidAddr)
+ require.Error(t, err, "should fail when IP is outside network range")
+ assert.Contains(t, err.Error(), "not within the account network range", "error should mention network range")
+ })
+
+ t.Run("update peer IP with invalid peer ID should fail", func(t *testing.T) {
+ newAddr := netip.MustParseAddr("100.64.0.101")
+ err := manager.UpdatePeerIP(context.Background(), accountID, userID, "invalid-peer-id", newAddr)
+ require.Error(t, err, "should fail with invalid peer ID")
+ })
+}
diff --git a/management/server/activity/codes.go b/management/server/activity/codes.go
index 23ddd1dd5..6f9619597 100644
--- a/management/server/activity/codes.go
+++ b/management/server/activity/codes.go
@@ -175,6 +175,9 @@ const (
AccountLazyConnectionEnabled Activity = 85
AccountLazyConnectionDisabled Activity = 86
+ AccountNetworkRangeUpdated Activity = 87
+ PeerIPUpdated Activity = 88
+
AccountDeleted Activity = 99999
)
@@ -277,6 +280,10 @@ var activityMap = map[Activity]Code{
AccountLazyConnectionEnabled: {"Account lazy connection enabled", "account.setting.lazy.connection.enable"},
AccountLazyConnectionDisabled: {"Account lazy connection disabled", "account.setting.lazy.connection.disable"},
+
+ AccountNetworkRangeUpdated: {"Account network range updated", "account.network.range.update"},
+
+ PeerIPUpdated: {"Peer IP updated", "peer.ip.update"},
}
// StringCode returns a string code of the activity
diff --git a/management/server/context/keys.go b/management/server/context/keys.go
index c5b5da044..9697997a8 100644
--- a/management/server/context/keys.go
+++ b/management/server/context/keys.go
@@ -1,8 +1,10 @@
package context
+import "github.com/netbirdio/netbird/shared/context"
+
const (
- RequestIDKey = "requestID"
- AccountIDKey = "accountID"
- UserIDKey = "userID"
- PeerIDKey = "peerID"
+ RequestIDKey = context.RequestIDKey
+ AccountIDKey = context.AccountIDKey
+ UserIDKey = context.UserIDKey
+ PeerIDKey = context.PeerIDKey
)
diff --git a/management/server/dns.go b/management/server/dns.go
index a3f32c2a9..489618c17 100644
--- a/management/server/dns.go
+++ b/management/server/dns.go
@@ -8,11 +8,11 @@ import (
log "github.com/sirupsen/logrus"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/util"
diff --git a/management/server/dns_test.go b/management/server/dns_test.go
index f2295450f..d58689544 100644
--- a/management/server/dns_test.go
+++ b/management/server/dns_test.go
@@ -24,7 +24,7 @@ import (
"github.com/netbirdio/netbird/dns"
"github.com/netbirdio/netbird/management/server/activity"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
const (
@@ -495,7 +495,7 @@ func TestToProtocolDNSConfigWithCache(t *testing.T) {
func TestDNSAccountPeersUpdate(t *testing.T) {
manager, account, peer1, peer2, peer3 := setupNetworkMapTest(t)
- err := manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ err := manager.CreateGroups(context.Background(), account.Id, userID, []*types.Group{
{
ID: "groupA",
Name: "GroupA",
@@ -506,7 +506,7 @@ func TestDNSAccountPeersUpdate(t *testing.T) {
Name: "GroupB",
Peers: []string{},
},
- }, true)
+ })
assert.NoError(t, err)
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1.ID)
@@ -562,11 +562,11 @@ func TestDNSAccountPeersUpdate(t *testing.T) {
// Creating DNS settings with groups that have peers should update account peers and send peer update
t.Run("creating dns setting with used groups", func(t *testing.T) {
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupA",
Name: "GroupA",
Peers: []string{peer1.ID, peer2.ID, peer3.ID},
- }, true)
+ })
assert.NoError(t, err)
done := make(chan struct{})
diff --git a/management/server/ephemeral_test.go b/management/server/ephemeral_test.go
index f71d48c58..d07b9a422 100644
--- a/management/server/ephemeral_test.go
+++ b/management/server/ephemeral_test.go
@@ -43,10 +43,10 @@ func (a *MockAccountManager) DeletePeer(_ context.Context, accountID, peerID, us
a.mu.Lock()
defer a.mu.Unlock()
a.deletePeerCalls++
+ delete(a.store.account.Peers, peerID)
if a.wg != nil {
a.wg.Done()
}
- delete(a.store.account.Peers, peerID)
return nil
}
diff --git a/management/server/event.go b/management/server/event.go
index d94714e2c..3144c52ea 100644
--- a/management/server/event.go
+++ b/management/server/event.go
@@ -11,7 +11,7 @@ import (
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/geolocation/store.go b/management/server/geolocation/store.go
index 5af8276b5..4b9a6b2d9 100644
--- a/management/server/geolocation/store.go
+++ b/management/server/geolocation/store.go
@@ -13,7 +13,7 @@ import (
"gorm.io/gorm"
"gorm.io/gorm/logger"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
type GeoNames struct {
diff --git a/management/server/group.go b/management/server/group.go
index 130a67145..2b804b5f6 100644
--- a/management/server/group.go
+++ b/management/server/group.go
@@ -14,7 +14,7 @@ import (
routerTypes "github.com/netbirdio/netbird/management/server/networks/routers/types"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/util"
@@ -65,22 +65,144 @@ func (am *DefaultAccountManager) GetGroupByName(ctx context.Context, groupName,
return am.Store.GetGroupByName(ctx, store.LockingStrengthShare, accountID, groupName)
}
-// SaveGroup object of the peers
-func (am *DefaultAccountManager) SaveGroup(ctx context.Context, accountID, userID string, newGroup *types.Group, create bool) error {
+// CreateGroup object of the peers
+func (am *DefaultAccountManager) CreateGroup(ctx context.Context, accountID, userID string, newGroup *types.Group) error {
unlock := am.Store.AcquireWriteLockByUID(ctx, accountID)
defer unlock()
- return am.SaveGroups(ctx, accountID, userID, []*types.Group{newGroup}, create)
+
+ allowed, err := am.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Groups, operations.Create)
+ if err != nil {
+ return status.NewPermissionValidationError(err)
+ }
+ if !allowed {
+ return status.NewPermissionDeniedError()
+ }
+
+ var eventsToStore []func()
+ var updateAccountPeers bool
+
+ err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
+ if err = validateNewGroup(ctx, transaction, accountID, newGroup); err != nil {
+ return err
+ }
+
+ newGroup.AccountID = accountID
+
+ events := am.prepareGroupEvents(ctx, transaction, accountID, userID, newGroup)
+ eventsToStore = append(eventsToStore, events...)
+
+ updateAccountPeers, err = areGroupChangesAffectPeers(ctx, transaction, accountID, []string{newGroup.ID})
+ if err != nil {
+ return err
+ }
+
+ if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil {
+ return err
+ }
+
+ if err := transaction.CreateGroup(ctx, store.LockingStrengthUpdate, newGroup); err != nil {
+ return status.Errorf(status.Internal, "failed to create group: %v", err)
+ }
+
+ for _, peerID := range newGroup.Peers {
+ if err := transaction.AddPeerToGroup(ctx, accountID, peerID, newGroup.ID); err != nil {
+ return status.Errorf(status.Internal, "failed to add peer %s to group %s: %v", peerID, newGroup.ID, err)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ for _, storeEvent := range eventsToStore {
+ storeEvent()
+ }
+
+ if updateAccountPeers {
+ am.UpdateAccountPeers(ctx, accountID)
+ }
+
+ return nil
}
-// SaveGroups adds new groups to the account.
+// UpdateGroup object of the peers
+func (am *DefaultAccountManager) UpdateGroup(ctx context.Context, accountID, userID string, newGroup *types.Group) error {
+ unlock := am.Store.AcquireWriteLockByUID(ctx, accountID)
+ defer unlock()
+
+ allowed, err := am.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Groups, operations.Update)
+ if err != nil {
+ return status.NewPermissionValidationError(err)
+ }
+ if !allowed {
+ return status.NewPermissionDeniedError()
+ }
+
+ var eventsToStore []func()
+ var updateAccountPeers bool
+
+ err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
+ if err = validateNewGroup(ctx, transaction, accountID, newGroup); err != nil {
+ return err
+ }
+
+ oldGroup, err := transaction.GetGroupByID(ctx, store.LockingStrengthShare, accountID, newGroup.ID)
+ if err != nil {
+ return status.Errorf(status.NotFound, "group with ID %s not found", newGroup.ID)
+ }
+
+ peersToAdd := util.Difference(newGroup.Peers, oldGroup.Peers)
+ peersToRemove := util.Difference(oldGroup.Peers, newGroup.Peers)
+
+ for _, peerID := range peersToAdd {
+ if err := transaction.AddPeerToGroup(ctx, accountID, peerID, newGroup.ID); err != nil {
+ return status.Errorf(status.Internal, "failed to add peer %s to group %s: %v", peerID, newGroup.ID, err)
+ }
+ }
+ for _, peerID := range peersToRemove {
+ if err := transaction.RemovePeerFromGroup(ctx, peerID, newGroup.ID); err != nil {
+ return status.Errorf(status.Internal, "failed to remove peer %s from group %s: %v", peerID, newGroup.ID, err)
+ }
+ }
+
+ newGroup.AccountID = accountID
+
+ events := am.prepareGroupEvents(ctx, transaction, accountID, userID, newGroup)
+ eventsToStore = append(eventsToStore, events...)
+
+ updateAccountPeers, err = areGroupChangesAffectPeers(ctx, transaction, accountID, []string{newGroup.ID})
+ if err != nil {
+ return err
+ }
+
+ if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil {
+ return err
+ }
+
+ return transaction.UpdateGroup(ctx, store.LockingStrengthUpdate, newGroup)
+ })
+ if err != nil {
+ return err
+ }
+
+ for _, storeEvent := range eventsToStore {
+ storeEvent()
+ }
+
+ if updateAccountPeers {
+ am.UpdateAccountPeers(ctx, accountID)
+ }
+
+ return nil
+}
+
+// CreateGroups adds new groups to the account.
// Note: This function does not acquire the global lock.
// It is the caller's responsibility to ensure proper locking is in place before invoking this method.
-func (am *DefaultAccountManager) SaveGroups(ctx context.Context, accountID, userID string, groups []*types.Group, create bool) error {
- operation := operations.Create
- if !create {
- operation = operations.Update
- }
- allowed, err := am.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Groups, operation)
+// This method will not create group peer membership relations. Use AddPeerToGroup or RemovePeerFromGroup methods for that.
+func (am *DefaultAccountManager) CreateGroups(ctx context.Context, accountID, userID string, groups []*types.Group) error {
+ allowed, err := am.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Groups, operations.Create)
if err != nil {
return status.NewPermissionValidationError(err)
}
@@ -116,7 +238,65 @@ func (am *DefaultAccountManager) SaveGroups(ctx context.Context, accountID, user
return err
}
- return transaction.SaveGroups(ctx, store.LockingStrengthUpdate, accountID, groupsToSave)
+ return transaction.CreateGroups(ctx, store.LockingStrengthUpdate, accountID, groupsToSave)
+ })
+ if err != nil {
+ return err
+ }
+
+ for _, storeEvent := range eventsToStore {
+ storeEvent()
+ }
+
+ if updateAccountPeers {
+ am.UpdateAccountPeers(ctx, accountID)
+ }
+
+ return nil
+}
+
+// UpdateGroups updates groups in the account.
+// Note: This function does not acquire the global lock.
+// It is the caller's responsibility to ensure proper locking is in place before invoking this method.
+// This method will not create group peer membership relations. Use AddPeerToGroup or RemovePeerFromGroup methods for that.
+func (am *DefaultAccountManager) UpdateGroups(ctx context.Context, accountID, userID string, groups []*types.Group) error {
+ allowed, err := am.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Groups, operations.Update)
+ if err != nil {
+ return status.NewPermissionValidationError(err)
+ }
+ if !allowed {
+ return status.NewPermissionDeniedError()
+ }
+
+ var eventsToStore []func()
+ var groupsToSave []*types.Group
+ var updateAccountPeers bool
+
+ err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
+ groupIDs := make([]string, 0, len(groups))
+ for _, newGroup := range groups {
+ if err = validateNewGroup(ctx, transaction, accountID, newGroup); err != nil {
+ return err
+ }
+
+ newGroup.AccountID = accountID
+ groupsToSave = append(groupsToSave, newGroup)
+ groupIDs = append(groupIDs, newGroup.ID)
+
+ events := am.prepareGroupEvents(ctx, transaction, accountID, userID, newGroup)
+ eventsToStore = append(eventsToStore, events...)
+ }
+
+ updateAccountPeers, err = areGroupChangesAffectPeers(ctx, transaction, accountID, groupIDs)
+ if err != nil {
+ return err
+ }
+
+ if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil {
+ return err
+ }
+
+ return transaction.UpdateGroups(ctx, store.LockingStrengthUpdate, accountID, groupsToSave)
})
if err != nil {
return err
@@ -265,20 +445,10 @@ func (am *DefaultAccountManager) GroupAddPeer(ctx context.Context, accountID, gr
unlock := am.Store.AcquireWriteLockByUID(ctx, accountID)
defer unlock()
- var group *types.Group
var updateAccountPeers bool
var err error
err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
- group, err = transaction.GetGroupByID(context.Background(), store.LockingStrengthUpdate, accountID, groupID)
- if err != nil {
- return err
- }
-
- if updated := group.AddPeer(peerID); !updated {
- return nil
- }
-
updateAccountPeers, err = areGroupChangesAffectPeers(ctx, transaction, accountID, []string{groupID})
if err != nil {
return err
@@ -288,7 +458,7 @@ func (am *DefaultAccountManager) GroupAddPeer(ctx context.Context, accountID, gr
return err
}
- return transaction.SaveGroup(ctx, store.LockingStrengthUpdate, group)
+ return transaction.AddPeerToGroup(ctx, accountID, peerID, groupID)
})
if err != nil {
return err
@@ -329,7 +499,7 @@ func (am *DefaultAccountManager) GroupAddResource(ctx context.Context, accountID
return err
}
- return transaction.SaveGroup(ctx, store.LockingStrengthUpdate, group)
+ return transaction.UpdateGroup(ctx, store.LockingStrengthUpdate, group)
})
if err != nil {
return err
@@ -347,20 +517,10 @@ func (am *DefaultAccountManager) GroupDeletePeer(ctx context.Context, accountID,
unlock := am.Store.AcquireWriteLockByUID(ctx, accountID)
defer unlock()
- var group *types.Group
var updateAccountPeers bool
var err error
err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
- group, err = transaction.GetGroupByID(context.Background(), store.LockingStrengthUpdate, accountID, groupID)
- if err != nil {
- return err
- }
-
- if updated := group.RemovePeer(peerID); !updated {
- return nil
- }
-
updateAccountPeers, err = areGroupChangesAffectPeers(ctx, transaction, accountID, []string{groupID})
if err != nil {
return err
@@ -370,7 +530,7 @@ func (am *DefaultAccountManager) GroupDeletePeer(ctx context.Context, accountID,
return err
}
- return transaction.SaveGroup(ctx, store.LockingStrengthUpdate, group)
+ return transaction.RemovePeerFromGroup(ctx, peerID, groupID)
})
if err != nil {
return err
@@ -411,7 +571,7 @@ func (am *DefaultAccountManager) GroupDeleteResource(ctx context.Context, accoun
return err
}
- return transaction.SaveGroup(ctx, store.LockingStrengthUpdate, group)
+ return transaction.UpdateGroup(ctx, store.LockingStrengthUpdate, group)
})
if err != nil {
return err
diff --git a/management/server/group_test.go b/management/server/group_test.go
index 631fe3a71..c31280156 100644
--- a/management/server/group_test.go
+++ b/management/server/group_test.go
@@ -2,14 +2,20 @@ package server
import (
"context"
+ "encoding/binary"
"errors"
"fmt"
+ "net"
"net/netip"
+ "strconv"
+ "sync"
"testing"
"time"
+ "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "golang.org/x/exp/maps"
nbdns "github.com/netbirdio/netbird/dns"
"github.com/netbirdio/netbird/management/server/groups"
@@ -18,8 +24,10 @@ import (
"github.com/netbirdio/netbird/management/server/networks/routers"
routerTypes "github.com/netbirdio/netbird/management/server/networks/routers/types"
networkTypes "github.com/netbirdio/netbird/management/server/networks/types"
+ peer2 "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/permissions"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
+ "github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/route"
)
@@ -40,7 +48,8 @@ func TestDefaultAccountManager_CreateGroup(t *testing.T) {
}
for _, group := range account.Groups {
group.Issued = types.GroupIssuedIntegration
- err = am.SaveGroup(context.Background(), account.Id, groupAdminUserID, group, true)
+ group.ID = uuid.New().String()
+ err = am.CreateGroup(context.Background(), account.Id, groupAdminUserID, group)
if err != nil {
t.Errorf("should allow to create %s groups", types.GroupIssuedIntegration)
}
@@ -48,7 +57,8 @@ func TestDefaultAccountManager_CreateGroup(t *testing.T) {
for _, group := range account.Groups {
group.Issued = types.GroupIssuedJWT
- err = am.SaveGroup(context.Background(), account.Id, groupAdminUserID, group, true)
+ group.ID = uuid.New().String()
+ err = am.CreateGroup(context.Background(), account.Id, groupAdminUserID, group)
if err != nil {
t.Errorf("should allow to create %s groups", types.GroupIssuedJWT)
}
@@ -56,7 +66,7 @@ func TestDefaultAccountManager_CreateGroup(t *testing.T) {
for _, group := range account.Groups {
group.Issued = types.GroupIssuedAPI
group.ID = ""
- err = am.SaveGroup(context.Background(), account.Id, groupAdminUserID, group, true)
+ err = am.CreateGroup(context.Background(), account.Id, groupAdminUserID, group)
if err == nil {
t.Errorf("should not create api group with the same name, %s", group.Name)
}
@@ -162,7 +172,7 @@ func TestDefaultAccountManager_DeleteGroups(t *testing.T) {
}
}
- err = manager.SaveGroups(context.Background(), account.Id, groupAdminUserID, groups, true)
+ err = manager.CreateGroups(context.Background(), account.Id, groupAdminUserID, groups)
assert.NoError(t, err, "Failed to save test groups")
testCases := []struct {
@@ -382,13 +392,13 @@ func initTestGroupAccount(am *DefaultAccountManager) (*DefaultAccountManager, *t
return nil, nil, err
}
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForRoute, true)
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForRoute2, true)
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForNameServerGroups, true)
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForPolicies, true)
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForSetupKeys, true)
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForUsers, true)
- _ = am.SaveGroup(context.Background(), accountID, groupAdminUserID, groupForIntegration, true)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForRoute)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForRoute2)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForNameServerGroups)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForPolicies)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForSetupKeys)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForUsers)
+ _ = am.CreateGroup(context.Background(), accountID, groupAdminUserID, groupForIntegration)
acc, err := am.Store.GetAccount(context.Background(), account.Id)
if err != nil {
@@ -400,7 +410,7 @@ func initTestGroupAccount(am *DefaultAccountManager) (*DefaultAccountManager, *t
func TestGroupAccountPeersUpdate(t *testing.T) {
manager, account, peer1, peer2, peer3 := setupNetworkMapTest(t)
- err := manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ g := []*types.Group{
{
ID: "groupA",
Name: "GroupA",
@@ -426,8 +436,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
Name: "GroupE",
Peers: []string{peer2.ID},
},
- }, true)
- assert.NoError(t, err)
+ }
+ for _, group := range g {
+ err := manager.CreateGroup(context.Background(), account.Id, userID, group)
+ assert.NoError(t, err)
+ }
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1.ID)
t.Cleanup(func() {
@@ -442,11 +455,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err := manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err := manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupB",
Name: "GroupB",
Peers: []string{peer1.ID, peer2.ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -513,7 +526,7 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
})
// adding a group to policy
- _, err = manager.SavePolicy(context.Background(), account.Id, userID, &types.Policy{
+ _, err := manager.SavePolicy(context.Background(), account.Id, userID, &types.Policy{
Enabled: true,
Rules: []*types.PolicyRule{
{
@@ -535,11 +548,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err := manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err := manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupA",
Name: "GroupA",
Peers: []string{peer1.ID, peer2.ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -604,11 +617,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err := manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err := manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupC",
Name: "GroupC",
Peers: []string{peer1.ID, peer3.ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -645,11 +658,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupA",
Name: "GroupA",
Peers: []string{peer1.ID, peer2.ID, peer3.ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -672,11 +685,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupD",
Name: "GroupD",
Peers: []string{peer1.ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -719,11 +732,11 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupE",
Name: "GroupE",
Peers: []string{peer2.ID, peer3.ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -733,3 +746,259 @@ func TestGroupAccountPeersUpdate(t *testing.T) {
}
})
}
+
+func Test_AddPeerToGroup(t *testing.T) {
+ manager, err := createManager(t)
+ if err != nil {
+ t.Fatal(err)
+ return
+ }
+
+ accountID := "testaccount"
+ userID := "testuser"
+
+ acc, err := createAccount(manager, accountID, userID, "domain.com")
+ if err != nil {
+ t.Fatal("error creating account")
+ return
+ }
+
+ const totalPeers = 1000
+
+ var wg sync.WaitGroup
+ errs := make(chan error, totalPeers)
+ start := make(chan struct{})
+ for i := 0; i < totalPeers; i++ {
+ wg.Add(1)
+
+ go func(i int) {
+ defer wg.Done()
+
+ <-start
+
+ err = manager.Store.AddPeerToGroup(context.Background(), accountID, strconv.Itoa(i), acc.GroupsG[0].ID)
+ if err != nil {
+ errs <- fmt.Errorf("AddPeer failed for peer %d: %w", i, err)
+ return
+ }
+
+ }(i)
+ }
+ startTime := time.Now()
+
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ t.Logf("time since start: %s", time.Since(startTime))
+
+ for err := range errs {
+ t.Fatal(err)
+ }
+
+ account, err := manager.Store.GetAccount(context.Background(), accountID)
+ if err != nil {
+ t.Fatalf("Failed to get account %s: %v", accountID, err)
+ }
+
+ assert.Equal(t, totalPeers, len(maps.Values(account.Groups)[0].Peers), "Expected %d peers in group %s in account %s, got %d", totalPeers, maps.Values(account.Groups)[0].Name, accountID, len(account.Peers))
+}
+
+func Test_AddPeerToAll(t *testing.T) {
+ manager, err := createManager(t)
+ if err != nil {
+ t.Fatal(err)
+ return
+ }
+
+ accountID := "testaccount"
+ userID := "testuser"
+
+ _, err = createAccount(manager, accountID, userID, "domain.com")
+ if err != nil {
+ t.Fatal("error creating account")
+ return
+ }
+
+ const totalPeers = 1000
+
+ var wg sync.WaitGroup
+ errs := make(chan error, totalPeers)
+ start := make(chan struct{})
+ for i := 0; i < totalPeers; i++ {
+ wg.Add(1)
+
+ go func(i int) {
+ defer wg.Done()
+
+ <-start
+
+ err = manager.Store.AddPeerToAllGroup(context.Background(), accountID, strconv.Itoa(i))
+ if err != nil {
+ errs <- fmt.Errorf("AddPeer failed for peer %d: %w", i, err)
+ return
+ }
+
+ }(i)
+ }
+ startTime := time.Now()
+
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ t.Logf("time since start: %s", time.Since(startTime))
+
+ for err := range errs {
+ t.Fatal(err)
+ }
+
+ account, err := manager.Store.GetAccount(context.Background(), accountID)
+ if err != nil {
+ t.Fatalf("Failed to get account %s: %v", accountID, err)
+ }
+
+ assert.Equal(t, totalPeers, len(maps.Values(account.Groups)[0].Peers), "Expected %d peers in group %s account %s, got %d", totalPeers, maps.Values(account.Groups)[0].Name, accountID, len(account.Peers))
+}
+
+func Test_AddPeerAndAddToAll(t *testing.T) {
+ manager, err := createManager(t)
+ if err != nil {
+ t.Fatal(err)
+ return
+ }
+
+ accountID := "testaccount"
+ userID := "testuser"
+
+ _, err = createAccount(manager, accountID, userID, "domain.com")
+ if err != nil {
+ t.Fatal("error creating account")
+ return
+ }
+
+ const totalPeers = 1000
+
+ var wg sync.WaitGroup
+ errs := make(chan error, totalPeers)
+ start := make(chan struct{})
+ for i := 0; i < totalPeers; i++ {
+ wg.Add(1)
+
+ go func(i int) {
+ defer wg.Done()
+
+ <-start
+
+ peer := &peer2.Peer{
+ ID: strconv.Itoa(i),
+ AccountID: accountID,
+ DNSLabel: "peer" + strconv.Itoa(i),
+ IP: uint32ToIP(uint32(i)),
+ }
+
+ err = manager.Store.ExecuteInTransaction(context.Background(), func(transaction store.Store) error {
+ err = transaction.AddPeerToAccount(context.Background(), store.LockingStrengthUpdate, peer)
+ if err != nil {
+ return fmt.Errorf("AddPeer failed for peer %d: %w", i, err)
+ }
+ err = transaction.AddPeerToAllGroup(context.Background(), accountID, peer.ID)
+ if err != nil {
+ return fmt.Errorf("AddPeer failed for peer %d: %w", i, err)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Errorf("AddPeer failed for peer %d: %v", i, err)
+ return
+ }
+ }(i)
+ }
+ startTime := time.Now()
+
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ t.Logf("time since start: %s", time.Since(startTime))
+
+ for err := range errs {
+ t.Fatal(err)
+ }
+
+ account, err := manager.Store.GetAccount(context.Background(), accountID)
+ if err != nil {
+ t.Fatalf("Failed to get account %s: %v", accountID, err)
+ }
+
+ assert.Equal(t, totalPeers, len(maps.Values(account.Groups)[0].Peers), "Expected %d peers in group %s in account %s, got %d", totalPeers, maps.Values(account.Groups)[0].Name, accountID, len(account.Peers))
+ assert.Equal(t, totalPeers, len(account.Peers), "Expected %d peers in account %s, got %d", totalPeers, accountID, len(account.Peers))
+}
+
+func uint32ToIP(n uint32) net.IP {
+ ip := make(net.IP, 4)
+ binary.BigEndian.PutUint32(ip, n)
+ return ip
+}
+
+func Test_IncrementNetworkSerial(t *testing.T) {
+ manager, err := createManager(t)
+ if err != nil {
+ t.Fatal(err)
+ return
+ }
+
+ accountID := "testaccount"
+ userID := "testuser"
+
+ _, err = createAccount(manager, accountID, userID, "domain.com")
+ if err != nil {
+ t.Fatal("error creating account")
+ return
+ }
+
+ const totalPeers = 1000
+
+ var wg sync.WaitGroup
+ errs := make(chan error, totalPeers)
+ start := make(chan struct{})
+ for i := 0; i < totalPeers; i++ {
+ wg.Add(1)
+
+ go func(i int) {
+ defer wg.Done()
+
+ <-start
+
+ err = manager.Store.ExecuteInTransaction(context.Background(), func(transaction store.Store) error {
+ err = transaction.IncrementNetworkSerial(context.Background(), store.LockingStrengthNone, accountID)
+ if err != nil {
+ return fmt.Errorf("failed to get account %s: %v", accountID, err)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Errorf("AddPeer failed for peer %d: %v", i, err)
+ return
+ }
+ }(i)
+ }
+ startTime := time.Now()
+
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ t.Logf("time since start: %s", time.Since(startTime))
+
+ for err := range errs {
+ t.Fatal(err)
+ }
+
+ account, err := manager.Store.GetAccount(context.Background(), accountID)
+ if err != nil {
+ t.Fatalf("Failed to get account %s: %v", accountID, err)
+ }
+
+ assert.Equal(t, totalPeers, int(account.Network.Serial), "Expected %d serial increases in account %s, got %d", totalPeers, accountID, account.Network.Serial)
+}
diff --git a/management/server/groups/manager.go b/management/server/groups/manager.go
index df4b6c3d6..8647eeb68 100644
--- a/management/server/groups/manager.go
+++ b/management/server/groups/manager.go
@@ -6,7 +6,7 @@ import (
"github.com/netbirdio/netbird/management/server/account"
"github.com/netbirdio/netbird/management/server/activity"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
diff --git a/management/server/grpcserver.go b/management/server/grpcserver.go
index 2f1bc3673..f5d9c250b 100644
--- a/management/server/grpcserver.go
+++ b/management/server/grpcserver.go
@@ -19,10 +19,12 @@ import (
"google.golang.org/grpc/status"
integrationsConfig "github.com/netbirdio/management-integrations/integrations/config"
+
"github.com/netbirdio/netbird/management/server/integrations/integrated_validator"
+ "github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/encryption"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/account"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/auth"
@@ -30,7 +32,7 @@ import (
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/posture"
"github.com/netbirdio/netbird/management/server/settings"
- internalStatus "github.com/netbirdio/netbird/management/server/status"
+ internalStatus "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/types"
)
@@ -909,6 +911,44 @@ func (s *GRPCServer) SyncMeta(ctx context.Context, req *proto.EncryptedMessage)
return &proto.Empty{}, nil
}
+func (s *GRPCServer) Logout(ctx context.Context, req *proto.EncryptedMessage) (*proto.Empty, error) {
+ log.WithContext(ctx).Debugf("Logout request from peer [%s]", req.WgPubKey)
+
+ empty := &proto.Empty{}
+ peerKey, err := s.parseRequest(ctx, req, empty)
+ if err != nil {
+ return nil, err
+ }
+
+ peer, err := s.accountManager.GetStore().GetPeerByPeerPubKey(ctx, store.LockingStrengthShare, peerKey.String())
+ if err != nil {
+ log.WithContext(ctx).Debugf("peer %s is not registered for logout", peerKey.String())
+ // TODO: consider idempotency
+ return nil, mapError(ctx, err)
+ }
+
+ // nolint:staticcheck
+ ctx = context.WithValue(ctx, nbContext.PeerIDKey, peer.ID)
+ // nolint:staticcheck
+ ctx = context.WithValue(ctx, nbContext.AccountIDKey, peer.AccountID)
+
+ userID := peer.UserID
+ if userID == "" {
+ userID = activity.SystemInitiator
+ }
+
+ if err = s.accountManager.DeletePeer(ctx, peer.AccountID, peer.ID, userID); err != nil {
+ log.WithContext(ctx).Errorf("failed to logout peer %s: %v", peerKey.String(), err)
+ return nil, mapError(ctx, err)
+ }
+
+ s.accountManager.BufferUpdateAccountPeers(ctx, peer.AccountID)
+
+ log.WithContext(ctx).Infof("peer %s logged out successfully", peerKey.String())
+
+ return &proto.Empty{}, nil
+}
+
// toProtocolChecks converts posture checks to protocol checks.
func toProtocolChecks(ctx context.Context, postureChecks []*posture.Checks) []*proto.Checks {
protoChecks := make([]*proto.Checks, 0, len(postureChecks))
diff --git a/management/server/http/handlers/accounts/accounts_handler.go b/management/server/http/handlers/accounts/accounts_handler.go
index ab59434d1..aeda61184 100644
--- a/management/server/http/handlers/accounts/accounts_handler.go
+++ b/management/server/http/handlers/accounts/accounts_handler.go
@@ -1,21 +1,34 @@
package accounts
import (
+ "context"
"encoding/json"
"net/http"
+ "net/netip"
"time"
"github.com/gorilla/mux"
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/settings"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
+const (
+ // PeerBufferPercentage is the percentage of peers to add as buffer for network range calculations
+ PeerBufferPercentage = 0.5
+ // MinRequiredAddresses is the minimum number of addresses required in a network range
+ MinRequiredAddresses = 10
+ // MinNetworkBits is the minimum prefix length for IPv4 network ranges (e.g., /29 gives 8 addresses, /28 gives 16)
+ MinNetworkBitsIPv4 = 28
+ // MinNetworkBitsIPv6 is the minimum prefix length for IPv6 network ranges
+ MinNetworkBitsIPv6 = 120
+)
+
// handler is a handler that handles the server.Account HTTP endpoints
type handler struct {
accountManager account.Manager
@@ -37,6 +50,86 @@ func newHandler(accountManager account.Manager, settingsManager settings.Manager
}
}
+func validateIPAddress(addr netip.Addr) error {
+ if addr.IsLoopback() {
+ return status.Errorf(status.InvalidArgument, "loopback address range not allowed")
+ }
+
+ if addr.IsMulticast() {
+ return status.Errorf(status.InvalidArgument, "multicast address range not allowed")
+ }
+
+ if addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() {
+ return status.Errorf(status.InvalidArgument, "link-local address range not allowed")
+ }
+
+ return nil
+}
+
+func validateMinimumSize(prefix netip.Prefix) error {
+ addr := prefix.Addr()
+ if addr.Is4() && prefix.Bits() > MinNetworkBitsIPv4 {
+ return status.Errorf(status.InvalidArgument, "network range too small: minimum size is /%d for IPv4", MinNetworkBitsIPv4)
+ }
+ if addr.Is6() && prefix.Bits() > MinNetworkBitsIPv6 {
+ return status.Errorf(status.InvalidArgument, "network range too small: minimum size is /%d for IPv6", MinNetworkBitsIPv6)
+ }
+ return nil
+}
+
+func (h *handler) validateNetworkRange(ctx context.Context, accountID, userID string, networkRange netip.Prefix) error {
+ if !networkRange.IsValid() {
+ return nil
+ }
+
+ if err := validateIPAddress(networkRange.Addr()); err != nil {
+ return err
+ }
+
+ if err := validateMinimumSize(networkRange); err != nil {
+ return err
+ }
+
+ return h.validateCapacity(ctx, accountID, userID, networkRange)
+}
+
+func (h *handler) validateCapacity(ctx context.Context, accountID, userID string, prefix netip.Prefix) error {
+ peers, err := h.accountManager.GetPeers(ctx, accountID, userID, "", "")
+ if err != nil {
+ return status.Errorf(status.Internal, "get peer count: %v", err)
+ }
+
+ maxHosts := calculateMaxHosts(prefix)
+ requiredAddresses := calculateRequiredAddresses(len(peers))
+
+ if maxHosts < requiredAddresses {
+ return status.Errorf(status.InvalidArgument,
+ "network range too small: need at least %d addresses for %d peers + buffer, but range provides %d",
+ requiredAddresses, len(peers), maxHosts)
+ }
+
+ return nil
+}
+
+func calculateMaxHosts(prefix netip.Prefix) int64 {
+ availableAddresses := prefix.Addr().BitLen() - prefix.Bits()
+ maxHosts := int64(1) << availableAddresses
+
+ if prefix.Addr().Is4() {
+ maxHosts -= 2 // network and broadcast addresses
+ }
+
+ return maxHosts
+}
+
+func calculateRequiredAddresses(peerCount int) int64 {
+ requiredAddresses := int64(peerCount) + int64(float64(peerCount)*PeerBufferPercentage)
+ if requiredAddresses < MinRequiredAddresses {
+ requiredAddresses = MinRequiredAddresses
+ }
+ return requiredAddresses
+}
+
// getAllAccounts is HTTP GET handler that returns a list of accounts. Effectively returns just a single account.
func (h *handler) getAllAccounts(w http.ResponseWriter, r *http.Request) {
userAuth, err := nbcontext.GetUserAuthFromContext(r.Context())
@@ -131,6 +224,18 @@ func (h *handler) updateAccount(w http.ResponseWriter, r *http.Request) {
if req.Settings.LazyConnectionEnabled != nil {
settings.LazyConnectionEnabled = *req.Settings.LazyConnectionEnabled
}
+ if req.Settings.NetworkRange != nil && *req.Settings.NetworkRange != "" {
+ prefix, err := netip.ParsePrefix(*req.Settings.NetworkRange)
+ if err != nil {
+ util.WriteError(r.Context(), status.Errorf(status.InvalidArgument, "invalid CIDR format: %v", err), w)
+ return
+ }
+ if err := h.validateNetworkRange(r.Context(), accountID, userID, prefix); err != nil {
+ util.WriteError(r.Context(), err, w)
+ return
+ }
+ settings.NetworkRange = prefix
+ }
var onboarding *types.AccountOnboarding
if req.Onboarding != nil {
@@ -208,6 +313,11 @@ func toAccountResponse(accountID string, settings *types.Settings, meta *types.A
DnsDomain: &settings.DNSDomain,
}
+ if settings.NetworkRange.IsValid() {
+ networkRangeStr := settings.NetworkRange.String()
+ apiSettings.NetworkRange = &networkRangeStr
+ }
+
apiOnboarding := api.AccountOnboarding{
OnboardingFlowPending: onboarding.OnboardingFlowPending,
SignupFormPending: onboarding.SignupFormPending,
diff --git a/management/server/http/handlers/accounts/accounts_handler_test.go b/management/server/http/handlers/accounts/accounts_handler_test.go
index dbf0c22bc..1dad33a6f 100644
--- a/management/server/http/handlers/accounts/accounts_handler_test.go
+++ b/management/server/http/handlers/accounts/accounts_handler_test.go
@@ -15,10 +15,10 @@ import (
"github.com/stretchr/testify/assert"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/settings"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/dns/dns_settings_handler.go b/management/server/http/handlers/dns/dns_settings_handler.go
index 60822c883..08a0b2afd 100644
--- a/management/server/http/handlers/dns/dns_settings_handler.go
+++ b/management/server/http/handlers/dns/dns_settings_handler.go
@@ -9,8 +9,8 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/dns/dns_settings_handler_test.go b/management/server/http/handlers/dns/dns_settings_handler_test.go
index ca81adf43..42b519c29 100644
--- a/management/server/http/handlers/dns/dns_settings_handler_test.go
+++ b/management/server/http/handlers/dns/dns_settings_handler_test.go
@@ -11,8 +11,8 @@ import (
"github.com/stretchr/testify/assert"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
"github.com/gorilla/mux"
diff --git a/management/server/http/handlers/dns/nameservers_handler.go b/management/server/http/handlers/dns/nameservers_handler.go
index 970be6d8a..bce1c4b78 100644
--- a/management/server/http/handlers/dns/nameservers_handler.go
+++ b/management/server/http/handlers/dns/nameservers_handler.go
@@ -11,9 +11,9 @@ import (
nbdns "github.com/netbirdio/netbird/dns"
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
)
// nameserversHandler is the nameserver group handler of the account
diff --git a/management/server/http/handlers/dns/nameservers_handler_test.go b/management/server/http/handlers/dns/nameservers_handler_test.go
index 45283bc37..d49b6c7e0 100644
--- a/management/server/http/handlers/dns/nameservers_handler_test.go
+++ b/management/server/http/handlers/dns/nameservers_handler_test.go
@@ -13,8 +13,8 @@ import (
"github.com/stretchr/testify/assert"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/gorilla/mux"
diff --git a/management/server/http/handlers/events/events_handler.go b/management/server/http/handlers/events/events_handler.go
index eee5d8aa7..ae1e64e5c 100644
--- a/management/server/http/handlers/events/events_handler.go
+++ b/management/server/http/handlers/events/events_handler.go
@@ -10,8 +10,8 @@ import (
"github.com/netbirdio/netbird/management/server/account"
"github.com/netbirdio/netbird/management/server/activity"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
// handler HTTP handler
diff --git a/management/server/http/handlers/events/events_handler_test.go b/management/server/http/handlers/events/events_handler_test.go
index 3a643fe90..a0695fa3f 100644
--- a/management/server/http/handlers/events/events_handler_test.go
+++ b/management/server/http/handlers/events/events_handler_test.go
@@ -16,7 +16,7 @@ import (
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/activity"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/groups/groups_handler.go b/management/server/http/handlers/groups/groups_handler.go
index 3ae833dc0..e861e873c 100644
--- a/management/server/http/handlers/groups/groups_handler.go
+++ b/management/server/http/handlers/groups/groups_handler.go
@@ -11,9 +11,9 @@ import (
nbcontext "github.com/netbirdio/netbird/management/server/context"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
@@ -143,7 +143,7 @@ func (h *handler) updateGroup(w http.ResponseWriter, r *http.Request) {
IntegrationReference: existingGroup.IntegrationReference,
}
- if err := h.accountManager.SaveGroup(r.Context(), accountID, userID, &group, false); err != nil {
+ if err := h.accountManager.UpdateGroup(r.Context(), accountID, userID, &group); err != nil {
log.WithContext(r.Context()).Errorf("failed updating group %s under account %s %v", groupID, accountID, err)
util.WriteError(r.Context(), err, w)
return
@@ -203,7 +203,7 @@ func (h *handler) createGroup(w http.ResponseWriter, r *http.Request) {
Issued: types.GroupIssuedAPI,
}
- err = h.accountManager.SaveGroup(r.Context(), accountID, userID, &group, true)
+ err = h.accountManager.CreateGroup(r.Context(), accountID, userID, &group)
if err != nil {
util.WriteError(r.Context(), err, w)
return
diff --git a/management/server/http/handlers/groups/groups_handler_test.go b/management/server/http/handlers/groups/groups_handler_test.go
index 2caa2f5bf..34694ec8c 100644
--- a/management/server/http/handlers/groups/groups_handler_test.go
+++ b/management/server/http/handlers/groups/groups_handler_test.go
@@ -19,11 +19,11 @@ import (
"github.com/netbirdio/netbird/management/server"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/mock_server"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/networks/handler.go b/management/server/http/handlers/networks/handler.go
index 1809019a6..d7b598a5d 100644
--- a/management/server/http/handlers/networks/handler.go
+++ b/management/server/http/handlers/networks/handler.go
@@ -12,14 +12,14 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/groups"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/networks"
"github.com/netbirdio/netbird/management/server/networks/resources"
"github.com/netbirdio/netbird/management/server/networks/routers"
routerTypes "github.com/netbirdio/netbird/management/server/networks/routers/types"
"github.com/netbirdio/netbird/management/server/networks/types"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
nbtypes "github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/networks/resources_handler.go b/management/server/http/handlers/networks/resources_handler.go
index 616083302..59396dceb 100644
--- a/management/server/http/handlers/networks/resources_handler.go
+++ b/management/server/http/handlers/networks/resources_handler.go
@@ -8,8 +8,8 @@ import (
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/groups"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/networks/resources"
"github.com/netbirdio/netbird/management/server/networks/resources/types"
)
diff --git a/management/server/http/handlers/networks/routers_handler.go b/management/server/http/handlers/networks/routers_handler.go
index 6b00534fc..2e64c637f 100644
--- a/management/server/http/handlers/networks/routers_handler.go
+++ b/management/server/http/handlers/networks/routers_handler.go
@@ -7,8 +7,8 @@ import (
"github.com/gorilla/mux"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/networks/routers"
"github.com/netbirdio/netbird/management/server/networks/routers/types"
)
diff --git a/management/server/http/handlers/peers/peers_handler.go b/management/server/http/handlers/peers/peers_handler.go
index 8c20ed65f..eed07e95d 100644
--- a/management/server/http/handlers/peers/peers_handler.go
+++ b/management/server/http/handlers/peers/peers_handler.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"net/http"
+ "net/netip"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
@@ -13,10 +14,10 @@ import (
"github.com/netbirdio/netbird/management/server/activity"
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/groups"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
@@ -111,6 +112,19 @@ func (h *Handler) updatePeer(ctx context.Context, accountID, userID, peerID stri
}
}
+ if req.Ip != nil {
+ addr, err := netip.ParseAddr(*req.Ip)
+ if err != nil {
+ util.WriteError(ctx, status.Errorf(status.InvalidArgument, "invalid IP address %s: %v", *req.Ip, err), w)
+ return
+ }
+
+ if err = h.accountManager.UpdatePeerIP(ctx, accountID, userID, peerID, addr); err != nil {
+ util.WriteError(ctx, err, w)
+ return
+ }
+ }
+
peer, err := h.accountManager.UpdatePeer(ctx, accountID, userID, update)
if err != nil {
util.WriteError(ctx, err, w)
diff --git a/management/server/http/handlers/peers/peers_handler_test.go b/management/server/http/handlers/peers/peers_handler_test.go
index a1fc13dd3..94564113f 100644
--- a/management/server/http/handlers/peers/peers_handler_test.go
+++ b/management/server/http/handlers/peers/peers_handler_test.go
@@ -9,6 +9,7 @@ import (
"net"
"net/http"
"net/http/httptest"
+ "net/netip"
"testing"
"time"
@@ -16,11 +17,12 @@ import (
"golang.org/x/exp/maps"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/types"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
"github.com/netbirdio/netbird/management/server/mock_server"
)
@@ -112,6 +114,15 @@ func initTestMetaData(peers ...*nbpeer.Peer) *Handler {
p.Name = update.Name
return p, nil
},
+ UpdatePeerIPFunc: func(_ context.Context, accountID, userID, peerID string, newIP netip.Addr) error {
+ for _, peer := range peers {
+ if peer.ID == peerID {
+ peer.IP = net.IP(newIP.AsSlice())
+ return nil
+ }
+ }
+ return fmt.Errorf("peer not found")
+ },
GetPeerFunc: func(_ context.Context, accountID, peerID, userID string) (*nbpeer.Peer, error) {
var p *nbpeer.Peer
for _, peer := range peers {
@@ -450,3 +461,73 @@ func TestGetAccessiblePeers(t *testing.T) {
})
}
}
+
+func TestPeersHandlerUpdatePeerIP(t *testing.T) {
+ testPeer := &nbpeer.Peer{
+ ID: testPeerID,
+ Key: "key",
+ IP: net.ParseIP("100.64.0.1"),
+ Status: &nbpeer.PeerStatus{Connected: false, LastSeen: time.Now()},
+ Name: "test-host@netbird.io",
+ LoginExpirationEnabled: false,
+ UserID: regularUser,
+ Meta: nbpeer.PeerSystemMeta{
+ Hostname: "test-host@netbird.io",
+ Core: "22.04",
+ },
+ }
+
+ p := initTestMetaData(testPeer)
+
+ tt := []struct {
+ name string
+ peerID string
+ requestBody string
+ callerUserID string
+ expectedStatus int
+ expectedIP string
+ }{
+ {
+ name: "update peer IP successfully",
+ peerID: testPeerID,
+ requestBody: `{"ip": "100.64.0.100"}`,
+ callerUserID: adminUser,
+ expectedStatus: http.StatusOK,
+ expectedIP: "100.64.0.100",
+ },
+ {
+ name: "update peer IP with invalid IP",
+ peerID: testPeerID,
+ requestBody: `{"ip": "invalid-ip"}`,
+ callerUserID: adminUser,
+ expectedStatus: http.StatusUnprocessableEntity,
+ },
+ }
+
+ for _, tc := range tt {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPut, fmt.Sprintf("/peers/%s", tc.peerID), bytes.NewBuffer([]byte(tc.requestBody)))
+ req.Header.Set("Content-Type", "application/json")
+ req = nbcontext.SetUserAuthInRequest(req, nbcontext.UserAuth{
+ UserId: tc.callerUserID,
+ Domain: "hotmail.com",
+ AccountId: "test_id",
+ })
+
+ rr := httptest.NewRecorder()
+ router := mux.NewRouter()
+ router.HandleFunc("/peers/{peerId}", p.HandlePeer).Methods("PUT")
+
+ router.ServeHTTP(rr, req)
+
+ assert.Equal(t, tc.expectedStatus, rr.Code)
+
+ if tc.expectedStatus == http.StatusOK && tc.expectedIP != "" {
+ var updatedPeer api.Peer
+ err := json.Unmarshal(rr.Body.Bytes(), &updatedPeer)
+ require.NoError(t, err)
+ assert.Equal(t, tc.expectedIP, updatedPeer.Ip)
+ }
+ })
+ }
+}
diff --git a/management/server/http/handlers/policies/geolocation_handler_test.go b/management/server/http/handlers/policies/geolocation_handler_test.go
index b7b53f53f..cedd5ac88 100644
--- a/management/server/http/handlers/policies/geolocation_handler_test.go
+++ b/management/server/http/handlers/policies/geolocation_handler_test.go
@@ -16,7 +16,7 @@ import (
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/geolocation"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
diff --git a/management/server/http/handlers/policies/geolocations_handler.go b/management/server/http/handlers/policies/geolocations_handler.go
index 84c8ea0aa..cb6995793 100644
--- a/management/server/http/handlers/policies/geolocations_handler.go
+++ b/management/server/http/handlers/policies/geolocations_handler.go
@@ -9,12 +9,12 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/geolocation"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
var (
diff --git a/management/server/http/handlers/policies/policies_handler.go b/management/server/http/handlers/policies/policies_handler.go
index 267d5744f..4d6bad5e3 100644
--- a/management/server/http/handlers/policies/policies_handler.go
+++ b/management/server/http/handlers/policies/policies_handler.go
@@ -10,9 +10,9 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/geolocation"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/policies/policies_handler_test.go b/management/server/http/handlers/policies/policies_handler_test.go
index 6f3dbc792..fd39ae2a3 100644
--- a/management/server/http/handlers/policies/policies_handler_test.go
+++ b/management/server/http/handlers/policies/policies_handler_test.go
@@ -14,9 +14,9 @@ import (
"github.com/stretchr/testify/assert"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/policies/posture_checks_handler.go b/management/server/http/handlers/policies/posture_checks_handler.go
index 2925f96ef..3ebc4d1e1 100644
--- a/management/server/http/handlers/policies/posture_checks_handler.go
+++ b/management/server/http/handlers/policies/posture_checks_handler.go
@@ -9,10 +9,10 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/geolocation"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
// postureChecksHandler is a handler that returns posture checks of the account.
diff --git a/management/server/http/handlers/policies/posture_checks_handler_test.go b/management/server/http/handlers/policies/posture_checks_handler_test.go
index e875b3738..c644b533a 100644
--- a/management/server/http/handlers/policies/posture_checks_handler_test.go
+++ b/management/server/http/handlers/policies/posture_checks_handler_test.go
@@ -16,10 +16,10 @@ import (
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/geolocation"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
var berlin = "Berlin"
diff --git a/management/server/http/handlers/routes/routes_handler.go b/management/server/http/handlers/routes/routes_handler.go
index ea731d9d8..7950db1e8 100644
--- a/management/server/http/handlers/routes/routes_handler.go
+++ b/management/server/http/handlers/routes/routes_handler.go
@@ -8,12 +8,12 @@ import (
"github.com/gorilla/mux"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/route"
)
diff --git a/management/server/http/handlers/routes/routes_handler_test.go b/management/server/http/handlers/routes/routes_handler_test.go
index ad1f8912d..fc0e112f7 100644
--- a/management/server/http/handlers/routes/routes_handler_test.go
+++ b/management/server/http/handlers/routes/routes_handler_test.go
@@ -15,11 +15,11 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/util"
"github.com/netbirdio/netbird/route"
)
diff --git a/management/server/http/handlers/setup_keys/setupkeys_handler.go b/management/server/http/handlers/setup_keys/setupkeys_handler.go
index 38ba86fb1..2287dadfe 100644
--- a/management/server/http/handlers/setup_keys/setupkeys_handler.go
+++ b/management/server/http/handlers/setup_keys/setupkeys_handler.go
@@ -10,9 +10,9 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/setup_keys/setupkeys_handler_test.go b/management/server/http/handlers/setup_keys/setupkeys_handler_test.go
index e9135469f..7b46b486b 100644
--- a/management/server/http/handlers/setup_keys/setupkeys_handler_test.go
+++ b/management/server/http/handlers/setup_keys/setupkeys_handler_test.go
@@ -15,9 +15,9 @@ import (
"github.com/stretchr/testify/assert"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/users/pat_handler.go b/management/server/http/handlers/users/pat_handler.go
index 90913eac1..bae07af4a 100644
--- a/management/server/http/handlers/users/pat_handler.go
+++ b/management/server/http/handlers/users/pat_handler.go
@@ -8,9 +8,9 @@ import (
"github.com/netbirdio/netbird/management/server/account"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/users/pat_handler_test.go b/management/server/http/handlers/users/pat_handler_test.go
index 6593de64a..92544c56d 100644
--- a/management/server/http/handlers/users/pat_handler_test.go
+++ b/management/server/http/handlers/users/pat_handler_test.go
@@ -17,9 +17,9 @@ import (
"github.com/netbirdio/netbird/management/server/util"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/handlers/users/users_handler.go b/management/server/http/handlers/users/users_handler.go
index ac04b8e35..bcd637db4 100644
--- a/management/server/http/handlers/users/users_handler.go
+++ b/management/server/http/handlers/users/users_handler.go
@@ -9,9 +9,9 @@ import (
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/server/account"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/users"
diff --git a/management/server/http/handlers/users/users_handler_test.go b/management/server/http/handlers/users/users_handler_test.go
index 58e33a6d5..f7dc81919 100644
--- a/management/server/http/handlers/users/users_handler_test.go
+++ b/management/server/http/handlers/users/users_handler_test.go
@@ -16,11 +16,11 @@ import (
"github.com/stretchr/testify/require"
nbcontext "github.com/netbirdio/netbird/management/server/context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/roles"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/users"
)
diff --git a/management/server/http/middleware/auth_middleware.go b/management/server/http/middleware/auth_middleware.go
index f2732fbf8..f221e64a9 100644
--- a/management/server/http/middleware/auth_middleware.go
+++ b/management/server/http/middleware/auth_middleware.go
@@ -13,8 +13,8 @@ import (
"github.com/netbirdio/netbird/management/server/auth"
nbcontext "github.com/netbirdio/netbird/management/server/context"
"github.com/netbirdio/netbird/management/server/http/middleware/bypass"
- "github.com/netbirdio/netbird/management/server/http/util"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/http/util"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/http/testing/benchmarks/peers_handler_benchmark_test.go b/management/server/http/testing/benchmarks/peers_handler_benchmark_test.go
index d82e08be9..52737e4eb 100644
--- a/management/server/http/testing/benchmarks/peers_handler_benchmark_test.go
+++ b/management/server/http/testing/benchmarks/peers_handler_benchmark_test.go
@@ -17,7 +17,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/http/testing/testing_tools"
)
diff --git a/management/server/http/testing/benchmarks/setupkeys_handler_benchmark_test.go b/management/server/http/testing/benchmarks/setupkeys_handler_benchmark_test.go
index f99b541f8..9404c4ee4 100644
--- a/management/server/http/testing/benchmarks/setupkeys_handler_benchmark_test.go
+++ b/management/server/http/testing/benchmarks/setupkeys_handler_benchmark_test.go
@@ -17,7 +17,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/http/testing/testing_tools"
)
diff --git a/management/server/http/testing/benchmarks/users_handler_benchmark_test.go b/management/server/http/testing/benchmarks/users_handler_benchmark_test.go
index c0b641a70..844b3e7a6 100644
--- a/management/server/http/testing/benchmarks/users_handler_benchmark_test.go
+++ b/management/server/http/testing/benchmarks/users_handler_benchmark_test.go
@@ -18,7 +18,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/http/testing/testing_tools"
)
diff --git a/management/server/http/testing/integration/setupkeys_handler_integration_test.go b/management/server/http/testing/integration/setupkeys_handler_integration_test.go
index ed6e642a2..9f04e3c24 100644
--- a/management/server/http/testing/integration/setupkeys_handler_integration_test.go
+++ b/management/server/http/testing/integration/setupkeys_handler_integration_test.go
@@ -15,7 +15,7 @@ import (
"github.com/stretchr/testify/assert"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/http/handlers/setup_keys"
"github.com/netbirdio/netbird/management/server/http/testing/testing_tools"
)
diff --git a/management/server/integrated_validator.go b/management/server/integrated_validator.go
index b89739be9..1e92e0c50 100644
--- a/management/server/integrated_validator.go
+++ b/management/server/integrated_validator.go
@@ -151,7 +151,7 @@ func (MockIntegratedValidator) PeerDeleted(_ context.Context, _, _ string, extra
return nil
}
-func (MockIntegratedValidator) SetPeerInvalidationListener(func(accountID string)) {
+func (MockIntegratedValidator) SetPeerInvalidationListener(func(accountID string, peerIDs []string)) {
// just a dummy
}
diff --git a/management/server/integrations/integrated_validator/interface.go b/management/server/integrations/integrated_validator/interface.go
index 4d4a8cdf6..ce632d567 100644
--- a/management/server/integrations/integrated_validator/interface.go
+++ b/management/server/integrations/integrated_validator/interface.go
@@ -3,7 +3,7 @@ package integrated_validator
import (
"context"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/types"
)
@@ -16,7 +16,7 @@ type IntegratedValidator interface {
IsNotValidPeer(ctx context.Context, accountID string, peer *nbpeer.Peer, peersGroup []string, extraSettings *types.ExtraSettings) (bool, bool, error)
GetValidatedPeers(ctx context.Context, accountID string, groups []*types.Group, peers []*nbpeer.Peer, extraSettings *types.ExtraSettings) (map[string]struct{}, error)
PeerDeleted(ctx context.Context, accountID, peerID string, extraSettings *types.ExtraSettings) error
- SetPeerInvalidationListener(fn func(accountID string))
+ SetPeerInvalidationListener(fn func(accountID string, peerIDs []string))
Stop(ctx context.Context)
ValidateFlowResponse(ctx context.Context, peerKey string, flowResponse *proto.PKCEAuthorizationFlow) *proto.PKCEAuthorizationFlow
}
diff --git a/management/server/management_proto_test.go b/management/server/management_proto_test.go
index 0d61b3a10..b896c52da 100644
--- a/management/server/management_proto_test.go
+++ b/management/server/management_proto_test.go
@@ -22,7 +22,7 @@ import (
"github.com/netbirdio/netbird/encryption"
"github.com/netbirdio/netbird/formatter/hook"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/integrations/port_forwarding"
"github.com/netbirdio/netbird/management/server/permissions"
diff --git a/management/server/management_test.go b/management/server/management_test.go
index ab6f0095b..1be6b377d 100644
--- a/management/server/management_test.go
+++ b/management/server/management_test.go
@@ -20,7 +20,7 @@ import (
"google.golang.org/grpc/keepalive"
"github.com/netbirdio/netbird/encryption"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/integrations/port_forwarding"
diff --git a/management/server/migration/migration.go b/management/server/migration/migration.go
index c2f1a5abf..88af9a58f 100644
--- a/management/server/migration/migration.go
+++ b/management/server/migration/migration.go
@@ -39,6 +39,11 @@ func MigrateFieldFromGobToJSON[T any, S any](ctx context.Context, db *gorm.DB, f
return nil
}
+ if !db.Migrator().HasColumn(&model, fieldName) {
+ log.WithContext(ctx).Debugf("Table for %T does not have column %s, no migration needed", model, fieldName)
+ return nil
+ }
+
stmt := &gorm.Statement{DB: db}
err := stmt.Parse(model)
if err != nil {
@@ -422,3 +427,62 @@ func CreateIndexIfNotExists[T any](ctx context.Context, db *gorm.DB, indexName s
log.WithContext(ctx).Infof("successfully created index %s on table %s", indexName, tableName)
return nil
}
+
+func MigrateJsonToTable[T any](ctx context.Context, db *gorm.DB, columnName string, mapperFunc func(accountID string, id string, value string) any) error {
+ var model T
+
+ if !db.Migrator().HasTable(&model) {
+ log.WithContext(ctx).Debugf("table for %T does not exist, no migration needed", model)
+ return nil
+ }
+
+ stmt := &gorm.Statement{DB: db}
+ err := stmt.Parse(&model)
+ if err != nil {
+ return fmt.Errorf("parse model: %w", err)
+ }
+ tableName := stmt.Schema.Table
+
+ if !db.Migrator().HasColumn(&model, columnName) {
+ log.WithContext(ctx).Debugf("column %s does not exist in table %s, no migration needed", columnName, tableName)
+ return nil
+ }
+
+ if err := db.Transaction(func(tx *gorm.DB) error {
+ var rows []map[string]any
+ if err := tx.Table(tableName).Select("id", "account_id", columnName).Find(&rows).Error; err != nil {
+ return fmt.Errorf("find rows: %w", err)
+ }
+
+ for _, row := range rows {
+ jsonValue, ok := row[columnName].(string)
+ if !ok || jsonValue == "" {
+ continue
+ }
+
+ var data []string
+ if err := json.Unmarshal([]byte(jsonValue), &data); err != nil {
+ return fmt.Errorf("unmarshal json: %w", err)
+ }
+
+ for _, value := range data {
+ if err := tx.Create(
+ mapperFunc(row["account_id"].(string), row["id"].(string), value),
+ ).Error; err != nil {
+ return fmt.Errorf("failed to insert id %v: %w", row["id"], err)
+ }
+ }
+ }
+
+ if err := tx.Migrator().DropColumn(&model, columnName); err != nil {
+ return fmt.Errorf("drop column %s: %w", columnName, err)
+ }
+
+ return nil
+ }); err != nil {
+ return err
+ }
+
+ log.WithContext(ctx).Infof("Migration of JSON field %s from table %s into separate table completed", columnName, tableName)
+ return nil
+}
diff --git a/management/server/mock_server/account_mock.go b/management/server/mock_server/account_mock.go
index a16e3652c..1ae432412 100644
--- a/management/server/mock_server/account_mock.go
+++ b/management/server/mock_server/account_mock.go
@@ -10,7 +10,7 @@ import (
"google.golang.org/grpc/status"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/management/server/account"
"github.com/netbirdio/netbird/management/server/activity"
nbcontext "github.com/netbirdio/netbird/management/server/context"
@@ -60,6 +60,7 @@ type MockAccountManager struct {
GetUsersFromAccountFunc func(ctx context.Context, accountID, userID string) (map[string]*types.UserInfo, error)
UpdatePeerMetaFunc func(ctx context.Context, peerID string, meta nbpeer.PeerSystemMeta) error
UpdatePeerFunc func(ctx context.Context, accountID, userID string, peer *nbpeer.Peer) (*nbpeer.Peer, error)
+ UpdatePeerIPFunc func(ctx context.Context, accountID, userID, peerID string, newIP netip.Addr) error
CreateRouteFunc func(ctx context.Context, accountID string, prefix netip.Prefix, networkType route.NetworkType, domains domain.List, peer string, peerGroups []string, description string, netID route.NetID, masquerade bool, metric int, groups, accessControlGroupIDs []string, enabled bool, userID string, keepRoute bool) (*route.Route, error)
GetRouteFunc func(ctx context.Context, accountID string, routeID route.ID, userID string) (*route.Route, error)
SaveRouteFunc func(ctx context.Context, accountID string, userID string, route *route.Route) error
@@ -124,6 +125,34 @@ type MockAccountManager struct {
BufferUpdateAccountPeersFunc func(ctx context.Context, accountID string)
}
+func (am *MockAccountManager) CreateGroup(ctx context.Context, accountID, userID string, group *types.Group) error {
+ if am.SaveGroupFunc != nil {
+ return am.SaveGroupFunc(ctx, accountID, userID, group, true)
+ }
+ return status.Errorf(codes.Unimplemented, "method CreateGroup is not implemented")
+}
+
+func (am *MockAccountManager) UpdateGroup(ctx context.Context, accountID, userID string, group *types.Group) error {
+ if am.SaveGroupFunc != nil {
+ return am.SaveGroupFunc(ctx, accountID, userID, group, false)
+ }
+ return status.Errorf(codes.Unimplemented, "method UpdateGroup is not implemented")
+}
+
+func (am *MockAccountManager) CreateGroups(ctx context.Context, accountID, userID string, newGroups []*types.Group) error {
+ if am.SaveGroupsFunc != nil {
+ return am.SaveGroupsFunc(ctx, accountID, userID, newGroups, true)
+ }
+ return status.Errorf(codes.Unimplemented, "method CreateGroups is not implemented")
+}
+
+func (am *MockAccountManager) UpdateGroups(ctx context.Context, accountID, userID string, newGroups []*types.Group) error {
+ if am.SaveGroupsFunc != nil {
+ return am.SaveGroupsFunc(ctx, accountID, userID, newGroups, false)
+ }
+ return status.Errorf(codes.Unimplemented, "method UpdateGroups is not implemented")
+}
+
func (am *MockAccountManager) UpdateAccountPeers(ctx context.Context, accountID string) {
if am.UpdateAccountPeersFunc != nil {
am.UpdateAccountPeersFunc(ctx, accountID)
@@ -455,6 +484,13 @@ func (am *MockAccountManager) UpdatePeer(ctx context.Context, accountID, userID
return nil, status.Errorf(codes.Unimplemented, "method UpdatePeer is not implemented")
}
+func (am *MockAccountManager) UpdatePeerIP(ctx context.Context, accountID, userID, peerID string, newIP netip.Addr) error {
+ if am.UpdatePeerIPFunc != nil {
+ return am.UpdatePeerIPFunc(ctx, accountID, userID, peerID, newIP)
+ }
+ return status.Errorf(codes.Unimplemented, "method UpdatePeerIP is not implemented")
+}
+
// CreateRoute mock implementation of CreateRoute from server.AccountManager interface
func (am *MockAccountManager) CreateRoute(ctx context.Context, accountID string, prefix netip.Prefix, networkType route.NetworkType, domains domain.List, peerID string, peerGroupIDs []string, description string, netID route.NetID, masquerade bool, metric int, groups, accessControlGroupID []string, enabled bool, userID string, keepRoute bool) (*route.Route, error) {
if am.CreateRouteFunc != nil {
diff --git a/management/server/mock_server/management_server_mock.go b/management/server/mock_server/management_server_mock.go
index d79fbd4e9..45049f1fe 100644
--- a/management/server/mock_server/management_server_mock.go
+++ b/management/server/mock_server/management_server_mock.go
@@ -6,7 +6,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
)
type ManagementServiceServerMock struct {
diff --git a/management/server/nameserver.go b/management/server/nameserver.go
index 18339335d..ef62d0eaf 100644
--- a/management/server/nameserver.go
+++ b/management/server/nameserver.go
@@ -13,7 +13,7 @@ import (
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/nameserver_test.go b/management/server/nameserver_test.go
index 25eb03b83..959e7856a 100644
--- a/management/server/nameserver_test.go
+++ b/management/server/nameserver_test.go
@@ -980,18 +980,18 @@ func TestNameServerAccountPeersUpdate(t *testing.T) {
var newNameServerGroupA *nbdns.NameServerGroup
var newNameServerGroupB *nbdns.NameServerGroup
- err := manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
- {
- ID: "groupA",
- Name: "GroupA",
- Peers: []string{},
- },
- {
- ID: "groupB",
- Name: "GroupB",
- Peers: []string{peer1.ID, peer2.ID, peer3.ID},
- },
- }, true)
+ err := manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
+ ID: "groupA",
+ Name: "GroupA",
+ Peers: []string{},
+ })
+ assert.NoError(t, err)
+
+ err = manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
+ ID: "groupB",
+ Name: "GroupB",
+ Peers: []string{peer1.ID, peer2.ID, peer3.ID},
+ })
assert.NoError(t, err)
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1.ID)
diff --git a/management/server/networks/manager.go b/management/server/networks/manager.go
index 1c46e9281..cb1116b0e 100644
--- a/management/server/networks/manager.go
+++ b/management/server/networks/manager.go
@@ -14,7 +14,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
)
diff --git a/management/server/networks/resources/manager.go b/management/server/networks/resources/manager.go
index 21d1e54de..7c8c68e32 100644
--- a/management/server/networks/resources/manager.go
+++ b/management/server/networks/resources/manager.go
@@ -12,7 +12,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
nbtypes "github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/util"
diff --git a/management/server/networks/resources/manager_test.go b/management/server/networks/resources/manager_test.go
index 3a91b4af8..c6cec6f7e 100644
--- a/management/server/networks/resources/manager_test.go
+++ b/management/server/networks/resources/manager_test.go
@@ -10,7 +10,7 @@ import (
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/networks/resources/types"
"github.com/netbirdio/netbird/management/server/permissions"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
)
diff --git a/management/server/networks/resources/types/resource.go b/management/server/networks/resources/types/resource.go
index 04c63608d..7874be858 100644
--- a/management/server/networks/resources/types/resource.go
+++ b/management/server/networks/resources/types/resource.go
@@ -8,13 +8,13 @@ import (
"github.com/rs/xid"
- nbDomain "github.com/netbirdio/netbird/management/domain"
+ nbDomain "github.com/netbirdio/netbird/shared/management/domain"
routerTypes "github.com/netbirdio/netbird/management/server/networks/routers/types"
networkTypes "github.com/netbirdio/netbird/management/server/networks/types"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/route"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
type NetworkResourceType string
diff --git a/management/server/networks/routers/manager.go b/management/server/networks/routers/manager.go
index 7b488b361..ff5a771d6 100644
--- a/management/server/networks/routers/manager.go
+++ b/management/server/networks/routers/manager.go
@@ -14,7 +14,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
)
diff --git a/management/server/networks/routers/manager_test.go b/management/server/networks/routers/manager_test.go
index 541643222..8054d05c6 100644
--- a/management/server/networks/routers/manager_test.go
+++ b/management/server/networks/routers/manager_test.go
@@ -9,7 +9,7 @@ import (
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/networks/routers/types"
"github.com/netbirdio/netbird/management/server/permissions"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
)
diff --git a/management/server/networks/routers/types/router.go b/management/server/networks/routers/types/router.go
index 71465868f..72b15fd9a 100644
--- a/management/server/networks/routers/types/router.go
+++ b/management/server/networks/routers/types/router.go
@@ -5,7 +5,7 @@ import (
"github.com/rs/xid"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
"github.com/netbirdio/netbird/management/server/networks/types"
)
diff --git a/management/server/networks/types/network.go b/management/server/networks/types/network.go
index d1c7f2b33..69d596f8b 100644
--- a/management/server/networks/types/network.go
+++ b/management/server/networks/types/network.go
@@ -3,7 +3,7 @@ package types
import (
"github.com/rs/xid"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
type Network struct {
diff --git a/management/server/peer.go b/management/server/peer.go
index 3c40c6bb6..6cd519f27 100644
--- a/management/server/peer.go
+++ b/management/server/peer.go
@@ -17,7 +17,7 @@ import (
"golang.org/x/exp/maps"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/management/server/geolocation"
"github.com/netbirdio/netbird/management/server/idp"
routerTypes "github.com/netbirdio/netbird/management/server/networks/routers/types"
@@ -29,10 +29,10 @@ import (
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/activity"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
// GetPeers returns a list of peers under the given account filtering out peers that do not belong to a user if
@@ -374,12 +374,20 @@ func (am *DefaultAccountManager) DeletePeer(ctx context.Context, accountID, peer
return err
}
- if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil {
- return err
+ if err = transaction.RemovePeerFromAllGroups(ctx, peer.ID); err != nil {
+ return fmt.Errorf("failed to remove peer from groups: %w", err)
}
eventsToStore, err = deletePeers(ctx, am, transaction, accountID, userID, []*nbpeer.Peer{peer})
- return err
+ if err != nil {
+ return fmt.Errorf("failed to delete peer: %w", err)
+ }
+
+ if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil {
+ return fmt.Errorf("failed to increment network serial: %w", err)
+ }
+
+ return nil
})
if err != nil {
return err
@@ -478,7 +486,6 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s
}
var newPeer *nbpeer.Peer
- var updateAccountPeers bool
var setupKeyID string
var setupKeyName string
@@ -615,20 +622,20 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s
return err
}
- err = transaction.AddPeerToAllGroup(ctx, store.LockingStrengthUpdate, accountID, newPeer.ID)
- if err != nil {
- return fmt.Errorf("failed adding peer to All group: %w", err)
- }
-
if len(groupsToAdd) > 0 {
for _, g := range groupsToAdd {
- err = transaction.AddPeerToGroup(ctx, store.LockingStrengthUpdate, accountID, newPeer.ID, g)
+ err = transaction.AddPeerToGroup(ctx, newPeer.AccountID, newPeer.ID, g)
if err != nil {
return err
}
}
}
+ err = transaction.AddPeerToAllGroup(ctx, accountID, newPeer.ID)
+ if err != nil {
+ return fmt.Errorf("failed adding peer to All group: %w", err)
+ }
+
if addedByUser {
err := transaction.SaveUserLastLogin(ctx, accountID, userID, newPeer.GetLastLogin())
if err != nil {
@@ -678,7 +685,7 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s
return nil, nil, nil, fmt.Errorf("failed to add peer to database after %d attempts: %w", maxAttempts, err)
}
- updateAccountPeers, err = isPeerInActiveGroup(ctx, am.Store, accountID, newPeer.ID)
+ updateAccountPeers, err := isPeerInActiveGroup(ctx, am.Store, accountID, newPeer.ID)
if err != nil {
updateAccountPeers = true
}
@@ -1021,7 +1028,7 @@ func (am *DefaultAccountManager) getValidatedPeerWithMap(ctx context.Context, is
}()
if isRequiresApproval {
- network, err := am.Store.GetAccountNetwork(ctx, store.LockingStrengthShare, accountID)
+ network, err := am.Store.GetAccountNetwork(ctx, store.LockingStrengthNone, accountID)
if err != nil {
return nil, nil, nil, err
}
@@ -1518,22 +1525,12 @@ func (am *DefaultAccountManager) getInactivePeers(ctx context.Context, accountID
// GetPeerGroups returns groups that the peer is part of.
func (am *DefaultAccountManager) GetPeerGroups(ctx context.Context, accountID, peerID string) ([]*types.Group, error) {
- return am.Store.GetPeerGroups(ctx, store.LockingStrengthShare, accountID, peerID)
+ return am.Store.GetPeerGroups(ctx, store.LockingStrengthNone, accountID, peerID)
}
// getPeerGroupIDs returns the IDs of the groups that the peer is part of.
func getPeerGroupIDs(ctx context.Context, transaction store.Store, accountID string, peerID string) ([]string, error) {
- groups, err := transaction.GetPeerGroups(ctx, store.LockingStrengthShare, accountID, peerID)
- if err != nil {
- return nil, err
- }
-
- groupIDs := make([]string, 0, len(groups))
- for _, group := range groups {
- groupIDs = append(groupIDs, group.ID)
- }
-
- return groupIDs, err
+ return transaction.GetPeerGroupIDs(ctx, store.LockingStrengthShare, accountID, peerID)
}
// IsPeerInActiveGroup checks if the given peer is part of a group that is used
@@ -1563,17 +1560,8 @@ func deletePeers(ctx context.Context, am *DefaultAccountManager, transaction sto
}
for _, peer := range peers {
- groups, err := transaction.GetPeerGroups(ctx, store.LockingStrengthUpdate, accountID, peer.ID)
- if err != nil {
- return nil, fmt.Errorf("failed to get peer groups: %w", err)
- }
-
- for _, group := range groups {
- group.RemovePeer(peer.ID)
- err = transaction.SaveGroup(ctx, store.LockingStrengthUpdate, group)
- if err != nil {
- return nil, fmt.Errorf("failed to save group: %w", err)
- }
+ if err := transaction.RemovePeerFromAllGroups(ctx, peer.ID); err != nil {
+ return nil, fmt.Errorf("failed to remove peer %s from groups", peer.ID)
}
if err := am.integratedPeerValidator.PeerDeleted(ctx, accountID, peer.ID, settings.Extra); err != nil {
diff --git a/management/server/peer_test.go b/management/server/peer_test.go
index 4f6ae500e..a78f220d3 100644
--- a/management/server/peer_test.go
+++ b/management/server/peer_test.go
@@ -29,7 +29,7 @@ import (
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/settings"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/util"
@@ -38,8 +38,8 @@ import (
networkTypes "github.com/netbirdio/netbird/management/server/networks/types"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/activity"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/posture"
@@ -310,12 +310,12 @@ func TestAccountManager_GetNetworkMapWithPolicy(t *testing.T) {
group1.Peers = append(group1.Peers, peer1.ID)
group2.Peers = append(group2.Peers, peer2.ID)
- err = manager.SaveGroup(context.Background(), account.Id, userID, &group1, true)
+ err = manager.CreateGroup(context.Background(), account.Id, userID, &group1)
if err != nil {
t.Errorf("expecting group1 to be added, got failure %v", err)
return
}
- err = manager.SaveGroup(context.Background(), account.Id, userID, &group2, true)
+ err = manager.CreateGroup(context.Background(), account.Id, userID, &group2)
if err != nil {
t.Errorf("expecting group2 to be added, got failure %v", err)
return
@@ -1475,6 +1475,10 @@ func Test_RegisterPeerBySetupKey(t *testing.T) {
}
func Test_RegisterPeerRollbackOnFailure(t *testing.T) {
+ engine := os.Getenv("NETBIRD_STORE_ENGINE")
+ if engine == "sqlite" || engine == "" {
+ t.Skip("Skipping test because sqlite test store is not respecting foreign keys")
+ }
if runtime.GOOS == "windows" {
t.Skip("The SQLite store is not properly supported by Windows yet")
}
@@ -1709,7 +1713,7 @@ func TestPeerAccountPeersUpdate(t *testing.T) {
err := manager.DeletePolicy(context.Background(), account.Id, account.Policies[0].ID, userID)
require.NoError(t, err)
- err = manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ g := []*types.Group{
{
ID: "groupA",
Name: "GroupA",
@@ -1725,8 +1729,11 @@ func TestPeerAccountPeersUpdate(t *testing.T) {
Name: "GroupC",
Peers: []string{},
},
- }, true)
- require.NoError(t, err)
+ }
+ for _, group := range g {
+ err = manager.CreateGroup(context.Background(), account.Id, userID, group)
+ require.NoError(t, err)
+ }
// create a user with auto groups
_, err = manager.SaveOrAddUsers(context.Background(), account.Id, userID, []*types.User{
@@ -1785,7 +1792,7 @@ func TestPeerAccountPeersUpdate(t *testing.T) {
t.Run("adding peer to unlinked group", func(t *testing.T) {
done := make(chan struct{})
go func() {
- peerShouldNotReceiveUpdate(t, updMsg)
+ peerShouldNotReceiveUpdate(t, updMsg) //
close(done)
}()
@@ -2164,7 +2171,6 @@ func Test_IsUniqueConstraintError(t *testing.T) {
}
func Test_AddPeer(t *testing.T) {
- t.Setenv("NETBIRD_STORE_ENGINE", string(types.PostgresStoreEngine))
manager, err := createManager(t)
if err != nil {
t.Fatal(err)
@@ -2176,7 +2182,7 @@ func Test_AddPeer(t *testing.T) {
_, err = createAccount(manager, accountID, userID, "domain.com")
if err != nil {
- t.Fatal("error creating account")
+ t.Fatalf("error creating account: %v", err)
return
}
@@ -2186,22 +2192,21 @@ func Test_AddPeer(t *testing.T) {
return
}
- const totalPeers = 300 // totalPeers / differentHostnames should be less than 10 (due to concurrent retries)
- const differentHostnames = 50
+ const totalPeers = 300
var wg sync.WaitGroup
- errs := make(chan error, totalPeers+differentHostnames)
+ errs := make(chan error, totalPeers)
start := make(chan struct{})
for i := 0; i < totalPeers; i++ {
wg.Add(1)
- hostNameID := i % differentHostnames
go func(i int) {
defer wg.Done()
newPeer := &nbpeer.Peer{
- Key: "key" + strconv.Itoa(i),
- Meta: nbpeer.PeerSystemMeta{Hostname: "peer" + strconv.Itoa(hostNameID), GoOS: "linux"},
+ AccountID: accountID,
+ Key: "key" + strconv.Itoa(i),
+ Meta: nbpeer.PeerSystemMeta{Hostname: "peer" + strconv.Itoa(i), GoOS: "linux"},
}
<-start
diff --git a/management/server/peers/manager.go b/management/server/peers/manager.go
index fe48bf576..7e0262ef9 100644
--- a/management/server/peers/manager.go
+++ b/management/server/peers/manager.go
@@ -10,7 +10,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
)
diff --git a/management/server/permissions/manager.go b/management/server/permissions/manager.go
index ebbce5d4a..4b2d91c3b 100644
--- a/management/server/permissions/manager.go
+++ b/management/server/permissions/manager.go
@@ -11,7 +11,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
"github.com/netbirdio/netbird/management/server/permissions/roles"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/policy.go b/management/server/policy.go
index 1e9331d43..b19f99960 100644
--- a/management/server/policy.go
+++ b/management/server/policy.go
@@ -6,7 +6,7 @@ import (
"github.com/rs/xid"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
"github.com/netbirdio/netbird/management/server/store"
@@ -14,7 +14,7 @@ import (
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
// GetPolicy from the store
diff --git a/management/server/policy_test.go b/management/server/policy_test.go
index 4352f3cff..4a08f4c33 100644
--- a/management/server/policy_test.go
+++ b/management/server/policy_test.go
@@ -993,7 +993,7 @@ func sortFunc() func(a *types.FirewallRule, b *types.FirewallRule) int {
func TestPolicyAccountPeersUpdate(t *testing.T) {
manager, account, peer1, peer2, peer3 := setupNetworkMapTest(t)
- err := manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ g := []*types.Group{
{
ID: "groupA",
Name: "GroupA",
@@ -1014,8 +1014,11 @@ func TestPolicyAccountPeersUpdate(t *testing.T) {
Name: "GroupD",
Peers: []string{peer1.ID, peer2.ID},
},
- }, true)
- assert.NoError(t, err)
+ }
+ for _, group := range g {
+ err := manager.CreateGroup(context.Background(), account.Id, userID, group)
+ assert.NoError(t, err)
+ }
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1.ID)
t.Cleanup(func() {
@@ -1025,6 +1028,7 @@ func TestPolicyAccountPeersUpdate(t *testing.T) {
var policyWithGroupRulesNoPeers *types.Policy
var policyWithDestinationPeersOnly *types.Policy
var policyWithSourceAndDestinationPeers *types.Policy
+ var err error
// Saving policy with rule groups with no peers should not update account's peers and not send peer update
t.Run("saving policy with rule groups with no peers", func(t *testing.T) {
diff --git a/management/server/posture/checks.go b/management/server/posture/checks.go
index b2f308d76..d65dc5045 100644
--- a/management/server/posture/checks.go
+++ b/management/server/posture/checks.go
@@ -7,9 +7,9 @@ import (
"regexp"
"github.com/hashicorp/go-version"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
const (
diff --git a/management/server/posture/network.go b/management/server/posture/network.go
index 0fa6f6e71..f78744143 100644
--- a/management/server/posture/network.go
+++ b/management/server/posture/network.go
@@ -7,7 +7,7 @@ import (
"slices"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
type PeerNetworkRangeCheck struct {
diff --git a/management/server/posture_checks.go b/management/server/posture_checks.go
index f91e89b45..50f7e4776 100644
--- a/management/server/posture_checks.go
+++ b/management/server/posture_checks.go
@@ -13,7 +13,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/posture_checks_test.go b/management/server/posture_checks_test.go
index f93467375..67760d55a 100644
--- a/management/server/posture_checks_test.go
+++ b/management/server/posture_checks_test.go
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/server/store"
+ "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/posture"
@@ -105,10 +105,14 @@ func initTestPostureChecksAccount(am *DefaultAccountManager) (*types.Account, er
Id: regularUserID,
Role: types.UserRoleUser,
}
+ peer1 := &peer.Peer{
+ ID: "peer1",
+ }
account := newAccountWithId(context.Background(), accountID, groupAdminUserID, domain, false)
account.Users[admin.Id] = admin
account.Users[user.Id] = user
+ account.Peers["peer1"] = peer1
err := am.Store.SaveAccount(context.Background(), account)
if err != nil {
@@ -121,7 +125,7 @@ func initTestPostureChecksAccount(am *DefaultAccountManager) (*types.Account, er
func TestPostureCheckAccountPeersUpdate(t *testing.T) {
manager, account, peer1, peer2, peer3 := setupNetworkMapTest(t)
- err := manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ g := []*types.Group{
{
ID: "groupA",
Name: "GroupA",
@@ -137,8 +141,11 @@ func TestPostureCheckAccountPeersUpdate(t *testing.T) {
Name: "GroupC",
Peers: []string{},
},
- }, true)
- assert.NoError(t, err)
+ }
+ for _, group := range g {
+ err := manager.CreateGroup(context.Background(), account.Id, userID, group)
+ assert.NoError(t, err)
+ }
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1.ID)
t.Cleanup(func() {
@@ -156,7 +163,7 @@ func TestPostureCheckAccountPeersUpdate(t *testing.T) {
},
},
}
- postureCheckA, err = manager.SavePostureChecks(context.Background(), account.Id, userID, postureCheckA, true)
+ postureCheckA, err := manager.SavePostureChecks(context.Background(), account.Id, userID, postureCheckA, true)
require.NoError(t, err)
postureCheckB := &posture.Checks{
@@ -449,14 +456,16 @@ func TestArePostureCheckChangesAffectPeers(t *testing.T) {
AccountID: account.Id,
Peers: []string{"peer1"},
}
+ err = manager.CreateGroup(context.Background(), account.Id, adminUserID, groupA)
+ require.NoError(t, err, "failed to create groupA")
groupB := &types.Group{
ID: "groupB",
AccountID: account.Id,
Peers: []string{},
}
- err = manager.Store.SaveGroups(context.Background(), store.LockingStrengthUpdate, account.Id, []*types.Group{groupA, groupB})
- require.NoError(t, err, "failed to save groups")
+ err = manager.CreateGroup(context.Background(), account.Id, adminUserID, groupB)
+ require.NoError(t, err, "failed to create groupB")
postureCheckA := &posture.Checks{
Name: "checkA",
@@ -535,7 +544,7 @@ func TestArePostureCheckChangesAffectPeers(t *testing.T) {
t.Run("posture check is linked to policy but no peers in groups", func(t *testing.T) {
groupA.Peers = []string{}
- err = manager.Store.SaveGroup(context.Background(), store.LockingStrengthUpdate, groupA)
+ err = manager.UpdateGroup(context.Background(), account.Id, adminUserID, groupA)
require.NoError(t, err, "failed to save groups")
result, err := arePostureCheckChangesAffectPeers(context.Background(), manager.Store, account.Id, postureCheckA.ID)
diff --git a/management/server/route.go b/management/server/route.go
index 32ff39977..50c4bdc4a 100644
--- a/management/server/route.go
+++ b/management/server/route.go
@@ -9,12 +9,12 @@ import (
"github.com/rs/xid"
- "github.com/netbirdio/netbird/management/domain"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/route"
diff --git a/management/server/route_test.go b/management/server/route_test.go
index 37c37f624..ac51c25fd 100644
--- a/management/server/route_test.go
+++ b/management/server/route_test.go
@@ -14,7 +14,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/integrations/port_forwarding"
resourceTypes "github.com/netbirdio/netbird/management/server/networks/resources/types"
@@ -1215,7 +1215,7 @@ func TestGetNetworkMap_RouteSync(t *testing.T) {
Name: "peer1 group",
Peers: []string{peer1ID},
}
- err = am.SaveGroup(context.Background(), account.Id, userID, newGroup, true)
+ err = am.CreateGroup(context.Background(), account.Id, userID, newGroup)
require.NoError(t, err)
rules, err := am.ListPolicies(context.Background(), account.Id, "testingUser")
@@ -1505,7 +1505,7 @@ func initTestRouteAccount(t *testing.T, am *DefaultAccountManager) (*types.Accou
}
for _, group := range newGroup {
- err = am.SaveGroup(context.Background(), accountID, userID, group, true)
+ err = am.CreateGroup(context.Background(), accountID, userID, group)
if err != nil {
return nil, err
}
@@ -1953,7 +1953,7 @@ func TestRouteAccountPeersUpdate(t *testing.T) {
account, err := initTestRouteAccount(t, manager)
require.NoError(t, err, "failed to init testing account")
- err = manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ g := []*types.Group{
{
ID: "groupA",
Name: "GroupA",
@@ -1969,8 +1969,11 @@ func TestRouteAccountPeersUpdate(t *testing.T) {
Name: "GroupC",
Peers: []string{},
},
- }, true)
- assert.NoError(t, err)
+ }
+ for _, group := range g {
+ err = manager.CreateGroup(context.Background(), account.Id, userID, group)
+ require.NoError(t, err, "failed to create group %s", group.Name)
+ }
updMsg := manager.peersUpdateManager.CreateChannel(context.Background(), peer1ID)
t.Cleanup(func() {
@@ -2149,11 +2152,11 @@ func TestRouteAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupB",
Name: "GroupB",
Peers: []string{peer1ID},
- }, true)
+ })
assert.NoError(t, err)
select {
@@ -2189,11 +2192,11 @@ func TestRouteAccountPeersUpdate(t *testing.T) {
close(done)
}()
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.UpdateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupC",
Name: "GroupC",
Peers: []string{peer1ID},
- }, true)
+ })
assert.NoError(t, err)
select {
diff --git a/management/server/settings/manager.go b/management/server/settings/manager.go
index 94392ebf7..9cb142938 100644
--- a/management/server/settings/manager.go
+++ b/management/server/settings/manager.go
@@ -11,7 +11,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/users"
diff --git a/management/server/setupkey.go b/management/server/setupkey.go
index b0903c8d0..e3647f6df 100644
--- a/management/server/setupkey.go
+++ b/management/server/setupkey.go
@@ -10,7 +10,7 @@ import (
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/util"
diff --git a/management/server/setupkey_test.go b/management/server/setupkey_test.go
index cecf55200..e55b33c94 100644
--- a/management/server/setupkey_test.go
+++ b/management/server/setupkey_test.go
@@ -29,7 +29,7 @@ func TestDefaultAccountManager_SaveSetupKey(t *testing.T) {
t.Fatal(err)
}
- err = manager.SaveGroups(context.Background(), account.Id, userID, []*types.Group{
+ err = manager.CreateGroups(context.Background(), account.Id, userID, []*types.Group{
{
ID: "group_1",
Name: "group_name_1",
@@ -40,7 +40,7 @@ func TestDefaultAccountManager_SaveSetupKey(t *testing.T) {
Name: "group_name_2",
Peers: []string{},
},
- }, true)
+ })
if err != nil {
t.Fatal(err)
}
@@ -104,20 +104,20 @@ func TestDefaultAccountManager_CreateSetupKey(t *testing.T) {
t.Fatal(err)
}
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "group_1",
Name: "group_name_1",
Peers: []string{},
- }, true)
+ })
if err != nil {
t.Fatal(err)
}
- err = manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err = manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "group_2",
Name: "group_name_2",
Peers: []string{},
- }, true)
+ })
if err != nil {
t.Fatal(err)
}
@@ -398,11 +398,11 @@ func TestSetupKey_Copy(t *testing.T) {
func TestSetupKeyAccountPeersUpdate(t *testing.T) {
manager, account, peer1, peer2, peer3 := setupNetworkMapTest(t)
- err := manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err := manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupA",
Name: "GroupA",
Peers: []string{peer1.ID, peer2.ID, peer3.ID},
- }, true)
+ })
assert.NoError(t, err)
policy := &types.Policy{
diff --git a/management/server/store/sql_store.go b/management/server/store/sql_store.go
index e380a7da7..c0f683124 100644
--- a/management/server/store/sql_store.go
+++ b/management/server/store/sql_store.go
@@ -29,7 +29,7 @@ import (
networkTypes "github.com/netbirdio/netbird/management/server/networks/types"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/util"
@@ -96,7 +96,7 @@ func NewSqlStore(ctx context.Context, db *gorm.DB, storeEngine types.Engine, met
return nil, fmt.Errorf("migratePreAuto: %w", err)
}
err = db.AutoMigrate(
- &types.SetupKey{}, &nbpeer.Peer{}, &types.User{}, &types.PersonalAccessToken{}, &types.Group{},
+ &types.SetupKey{}, &nbpeer.Peer{}, &types.User{}, &types.PersonalAccessToken{}, &types.Group{}, &types.GroupPeer{},
&types.Account{}, &types.Policy{}, &types.PolicyRule{}, &route.Route{}, &nbdns.NameServerGroup{},
&installation{}, &types.ExtraSettings{}, &posture.Checks{}, &nbpeer.NetworkAddress{},
&networkTypes.Network{}, &routerTypes.NetworkRouter{}, &resourceTypes.NetworkResource{}, &types.AccountOnboarding{},
@@ -186,6 +186,10 @@ func (s *SqlStore) SaveAccount(ctx context.Context, account *types.Account) erro
generateAccountSQLTypes(account)
+ for _, group := range account.GroupsG {
+ group.StoreGroupPeers()
+ }
+
err := s.db.Transaction(func(tx *gorm.DB) error {
result := tx.Select(clause.Associations).Delete(account.Policies, "account_id = ?", account.Id)
if result.Error != nil {
@@ -247,7 +251,8 @@ func generateAccountSQLTypes(account *types.Account) {
for id, group := range account.Groups {
group.ID = id
- account.GroupsG = append(account.GroupsG, *group)
+ group.AccountID = account.Id
+ account.GroupsG = append(account.GroupsG, group)
}
for id, route := range account.Routes {
@@ -449,25 +454,56 @@ func (s *SqlStore) SaveUser(ctx context.Context, lockStrength LockingStrength, u
return nil
}
-// SaveGroups saves the given list of groups to the database.
-func (s *SqlStore) SaveGroups(ctx context.Context, lockStrength LockingStrength, accountID string, groups []*types.Group) error {
+// CreateGroups creates the given list of groups to the database.
+func (s *SqlStore) CreateGroups(ctx context.Context, lockStrength LockingStrength, accountID string, groups []*types.Group) error {
if len(groups) == 0 {
return nil
}
- result := s.db.
- Clauses(
- clause.Locking{Strength: string(lockStrength)},
- clause.OnConflict{
- Where: clause.Where{Exprs: []clause.Expression{clause.Eq{Column: "groups.account_id", Value: accountID}}},
- UpdateAll: true,
- },
- ).
- Create(&groups)
- if result.Error != nil {
- return status.Errorf(status.Internal, "failed to save groups to store: %v", result.Error)
+ return s.db.Transaction(func(tx *gorm.DB) error {
+ result := tx.
+ Clauses(
+ clause.Locking{Strength: string(lockStrength)},
+ clause.OnConflict{
+ Where: clause.Where{Exprs: []clause.Expression{clause.Eq{Column: "groups.account_id", Value: accountID}}},
+ UpdateAll: true,
+ },
+ ).
+ Omit(clause.Associations).
+ Create(&groups)
+ if result.Error != nil {
+ log.WithContext(ctx).Errorf("failed to save groups to store: %v", result.Error)
+ return status.Errorf(status.Internal, "failed to save groups to store")
+ }
+
+ return nil
+ })
+}
+
+// UpdateGroups updates the given list of groups to the database.
+func (s *SqlStore) UpdateGroups(ctx context.Context, lockStrength LockingStrength, accountID string, groups []*types.Group) error {
+ if len(groups) == 0 {
+ return nil
}
- return nil
+
+ return s.db.Transaction(func(tx *gorm.DB) error {
+ result := tx.
+ Clauses(
+ clause.Locking{Strength: string(lockStrength)},
+ clause.OnConflict{
+ Where: clause.Where{Exprs: []clause.Expression{clause.Eq{Column: "groups.account_id", Value: accountID}}},
+ UpdateAll: true,
+ },
+ ).
+ Omit(clause.Associations).
+ Create(&groups)
+ if result.Error != nil {
+ log.WithContext(ctx).Errorf("failed to save groups to store: %v", result.Error)
+ return status.Errorf(status.Internal, "failed to save groups to store")
+ }
+
+ return nil
+ })
}
// DeleteHashedPAT2TokenIDIndex is noop in SqlStore
@@ -646,7 +682,7 @@ func (s *SqlStore) GetAccountGroups(ctx context.Context, lockStrength LockingStr
}
var groups []*types.Group
- result := tx.Find(&groups, accountIDCondition, accountID)
+ result := tx.Preload(clause.Associations).Find(&groups, accountIDCondition, accountID)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, status.Errorf(status.NotFound, "accountID not found: index lookup failed")
@@ -655,6 +691,10 @@ func (s *SqlStore) GetAccountGroups(ctx context.Context, lockStrength LockingStr
return nil, status.Errorf(status.Internal, "failed to get account groups from the store")
}
+ for _, g := range groups {
+ g.LoadGroupPeers()
+ }
+
return groups, nil
}
@@ -669,6 +709,7 @@ func (s *SqlStore) GetResourceGroups(ctx context.Context, lockStrength LockingSt
likePattern := `%"ID":"` + resourceID + `"%`
result := tx.
+ Preload(clause.Associations).
Where("resources LIKE ?", likePattern).
Find(&groups)
@@ -679,6 +720,10 @@ func (s *SqlStore) GetResourceGroups(ctx context.Context, lockStrength LockingSt
return nil, result.Error
}
+ for _, g := range groups {
+ g.LoadGroupPeers()
+ }
+
return groups, nil
}
@@ -765,6 +810,7 @@ func (s *SqlStore) GetAccount(ctx context.Context, accountID string) (*types.Acc
var account types.Account
result := s.db.Model(&account).
+ Omit("GroupsG").
Preload("UsersG.PATsG"). // have to be specifies as this is nester reference
Preload(clause.Associations).
First(&account, idQueryCondition, accountID)
@@ -814,6 +860,17 @@ func (s *SqlStore) GetAccount(ctx context.Context, accountID string) (*types.Acc
}
account.GroupsG = nil
+ var groupPeers []types.GroupPeer
+ s.db.Model(&types.GroupPeer{}).Where("account_id = ?", accountID).
+ Find(&groupPeers)
+ for _, groupPeer := range groupPeers {
+ if group, ok := account.Groups[groupPeer.GroupID]; ok {
+ group.Peers = append(group.Peers, groupPeer.PeerID)
+ } else {
+ log.WithContext(ctx).Warnf("group %s not found for group peer %s in account %s", groupPeer.GroupID, groupPeer.PeerID, accountID)
+ }
+ }
+
account.Routes = make(map[route.ID]*route.Route, len(account.RoutesG))
for _, route := range account.RoutesG {
account.Routes[route.ID] = route.Copy()
@@ -1311,55 +1368,76 @@ func (s *SqlStore) IncrementSetupKeyUsage(ctx context.Context, setupKeyID string
}
// AddPeerToAllGroup adds a peer to the 'All' group. Method always needs to run in a transaction
-func (s *SqlStore) AddPeerToAllGroup(ctx context.Context, lockStrength LockingStrength, accountID string, peerID string) error {
- var group types.Group
- result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).
- First(&group, "account_id = ? AND name = ?", accountID, "All")
- if result.Error != nil {
- if errors.Is(result.Error, gorm.ErrRecordNotFound) {
- return status.Errorf(status.NotFound, "group 'All' not found for account")
- }
- return status.Errorf(status.Internal, "issue finding group 'All': %s", result.Error)
+func (s *SqlStore) AddPeerToAllGroup(ctx context.Context, accountID string, peerID string) error {
+ var groupID string
+ _ = s.db.Model(types.Group{}).
+ Select("id").
+ Where("account_id = ? AND name = ?", accountID, "All").
+ Limit(1).
+ Scan(&groupID)
+
+ if groupID == "" {
+ return status.Errorf(status.NotFound, "group 'All' not found for account %s", accountID)
}
- for _, existingPeerID := range group.Peers {
- if existingPeerID == peerID {
- return nil
- }
- }
+ err := s.db.Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "group_id"}, {Name: "peer_id"}},
+ DoNothing: true,
+ }).Create(&types.GroupPeer{
+ AccountID: accountID,
+ GroupID: groupID,
+ PeerID: peerID,
+ }).Error
- group.Peers = append(group.Peers, peerID)
-
- if err := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(&group).Error; err != nil {
- return status.Errorf(status.Internal, "issue updating group 'All': %s", err)
+ if err != nil {
+ return status.Errorf(status.Internal, "error adding peer to group 'All': %v", err)
}
return nil
}
-// AddPeerToGroup adds a peer to a group. Method always needs to run in a transaction
-func (s *SqlStore) AddPeerToGroup(ctx context.Context, lockStrength LockingStrength, accountId string, peerId string, groupID string) error {
- var group types.Group
- result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Where(accountAndIDQueryCondition, accountId, groupID).
- First(&group)
- if result.Error != nil {
- if errors.Is(result.Error, gorm.ErrRecordNotFound) {
- return status.NewGroupNotFoundError(groupID)
- }
-
- return status.Errorf(status.Internal, "issue finding group: %s", result.Error)
+// AddPeerToGroup adds a peer to a group
+func (s *SqlStore) AddPeerToGroup(ctx context.Context, accountID, peerID, groupID string) error {
+ peer := &types.GroupPeer{
+ AccountID: accountID,
+ GroupID: groupID,
+ PeerID: peerID,
}
- for _, existingPeerID := range group.Peers {
- if existingPeerID == peerId {
- return nil
- }
+ err := s.db.Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "group_id"}, {Name: "peer_id"}},
+ DoNothing: true,
+ }).Create(peer).Error
+
+ if err != nil {
+ log.WithContext(ctx).Errorf("failed to add peer %s to group %s for account %s: %v", peerID, groupID, accountID, err)
+ return status.Errorf(status.Internal, "failed to add peer to group")
}
- group.Peers = append(group.Peers, peerId)
+ return nil
+}
- if err := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(&group).Error; err != nil {
- return status.Errorf(status.Internal, "issue updating group: %s", err)
+// RemovePeerFromGroup removes a peer from a group
+func (s *SqlStore) RemovePeerFromGroup(ctx context.Context, peerID string, groupID string) error {
+ err := s.db.WithContext(ctx).
+ Delete(&types.GroupPeer{}, "group_id = ? AND peer_id = ?", groupID, peerID).Error
+
+ if err != nil {
+ log.WithContext(ctx).Errorf("failed to remove peer %s from group %s: %v", peerID, groupID, err)
+ return status.Errorf(status.Internal, "failed to remove peer from group")
+ }
+
+ return nil
+}
+
+// RemovePeerFromAllGroups removes a peer from all groups
+func (s *SqlStore) RemovePeerFromAllGroups(ctx context.Context, peerID string) error {
+ err := s.db.WithContext(ctx).
+ Delete(&types.GroupPeer{}, "peer_id = ?", peerID).Error
+
+ if err != nil {
+ log.WithContext(ctx).Errorf("failed to remove peer %s from all groups: %v", peerID, err)
+ return status.Errorf(status.Internal, "failed to remove peer from all groups")
}
return nil
@@ -1427,15 +1505,46 @@ func (s *SqlStore) GetPeerGroups(ctx context.Context, lockStrength LockingStreng
var groups []*types.Group
query := tx.
- Find(&groups, "account_id = ? AND peers LIKE ?", accountId, fmt.Sprintf(`%%"%s"%%`, peerId))
+ Joins("JOIN group_peers ON group_peers.group_id = groups.id").
+ Where("group_peers.peer_id = ?", peerId).
+ Preload(clause.Associations).
+ Find(&groups)
if query.Error != nil {
return nil, query.Error
}
+ for _, group := range groups {
+ group.LoadGroupPeers()
+ }
+
return groups, nil
}
+// GetPeerGroupIDs retrieves all group IDs assigned to a specific peer in a given account.
+func (s *SqlStore) GetPeerGroupIDs(ctx context.Context, lockStrength LockingStrength, accountId string, peerId string) ([]string, error) {
+ tx := s.db
+ if lockStrength != LockingStrengthNone {
+ tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)})
+ }
+
+ var groupIDs []string
+ query := tx.
+ Model(&types.GroupPeer{}).
+ Where("account_id = ? AND peer_id = ?", accountId, peerId).
+ Pluck("group_id", &groupIDs)
+
+ if query.Error != nil {
+ if errors.Is(query.Error, gorm.ErrRecordNotFound) {
+ return nil, status.Errorf(status.NotFound, "no groups found for peer %s in account %s", peerId, accountId)
+ }
+ log.WithContext(ctx).Errorf("failed to get group IDs for peer %s in account %s: %v", peerId, accountId, query.Error)
+ return nil, status.Errorf(status.Internal, "failed to get group IDs for peer from store")
+ }
+
+ return groupIDs, nil
+}
+
// GetAccountPeers retrieves peers for an account.
func (s *SqlStore) GetAccountPeers(ctx context.Context, lockStrength LockingStrength, accountID, nameFilter, ipFilter string) ([]*nbpeer.Peer, error) {
var peers []*nbpeer.Peer
@@ -1485,7 +1594,7 @@ func (s *SqlStore) GetUserPeers(ctx context.Context, lockStrength LockingStrengt
}
func (s *SqlStore) AddPeerToAccount(ctx context.Context, lockStrength LockingStrength, peer *nbpeer.Peer) error {
- if err := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Create(peer).Error; err != nil {
+ if err := s.db.Create(peer).Error; err != nil {
return status.Errorf(status.Internal, "issue adding peer to account: %s", err)
}
@@ -1722,7 +1831,7 @@ func (s *SqlStore) GetGroupByID(ctx context.Context, lockStrength LockingStrengt
}
var group *types.Group
- result := tx.First(&group, accountAndIDQueryCondition, accountID, groupID)
+ result := tx.Preload(clause.Associations).First(&group, accountAndIDQueryCondition, accountID, groupID)
if err := result.Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, status.NewGroupNotFoundError(groupID)
@@ -1731,15 +1840,14 @@ func (s *SqlStore) GetGroupByID(ctx context.Context, lockStrength LockingStrengt
return nil, status.Errorf(status.Internal, "failed to get group from store")
}
+ group.LoadGroupPeers()
+
return group, nil
}
// GetGroupByName retrieves a group by name and account ID.
func (s *SqlStore) GetGroupByName(ctx context.Context, lockStrength LockingStrength, accountID, groupName string) (*types.Group, error) {
tx := s.db
- if lockStrength != LockingStrengthNone {
- tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)})
- }
var group types.Group
@@ -1747,16 +1855,14 @@ func (s *SqlStore) GetGroupByName(ctx context.Context, lockStrength LockingStren
// we may need to reconsider changing the types.
query := tx.Preload(clause.Associations)
- switch s.storeEngine {
- case types.PostgresStoreEngine:
- query = query.Order("json_array_length(peers::json) DESC")
- case types.MysqlStoreEngine:
- query = query.Order("JSON_LENGTH(JSON_EXTRACT(peers, \"$\")) DESC")
- default:
- query = query.Order("json_array_length(peers) DESC")
- }
-
- result := query.First(&group, "account_id = ? AND name = ?", accountID, groupName)
+ result := query.
+ Model(&types.Group{}).
+ Joins("LEFT JOIN group_peers ON group_peers.group_id = groups.id").
+ Where("groups.account_id = ? AND groups.name = ?", accountID, groupName).
+ Group("groups.id").
+ Order("COUNT(group_peers.peer_id) DESC").
+ Limit(1).
+ First(&group)
if err := result.Error; err != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, status.NewGroupNotFoundError(groupName)
@@ -1764,6 +1870,9 @@ func (s *SqlStore) GetGroupByName(ctx context.Context, lockStrength LockingStren
log.WithContext(ctx).Errorf("failed to get group by name from store: %v", result.Error)
return nil, status.Errorf(status.Internal, "failed to get group by name from store")
}
+
+ group.LoadGroupPeers()
+
return &group, nil
}
@@ -1775,7 +1884,7 @@ func (s *SqlStore) GetGroupsByIDs(ctx context.Context, lockStrength LockingStren
}
var groups []*types.Group
- result := tx.Find(&groups, accountAndIDsQueryCondition, accountID, groupIDs)
+ result := tx.Preload(clause.Associations).Find(&groups, accountAndIDsQueryCondition, accountID, groupIDs)
if result.Error != nil {
log.WithContext(ctx).Errorf("failed to get groups by ID's from store: %s", result.Error)
return nil, status.Errorf(status.Internal, "failed to get groups by ID's from store")
@@ -1783,25 +1892,45 @@ func (s *SqlStore) GetGroupsByIDs(ctx context.Context, lockStrength LockingStren
groupsMap := make(map[string]*types.Group)
for _, group := range groups {
+ group.LoadGroupPeers()
groupsMap[group.ID] = group
}
return groupsMap, nil
}
-// SaveGroup saves a group to the store.
-func (s *SqlStore) SaveGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error {
- result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(group)
- if result.Error != nil {
- log.WithContext(ctx).Errorf("failed to save group to store: %v", result.Error)
+// CreateGroup creates a group in the store.
+func (s *SqlStore) CreateGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error {
+ if group == nil {
+ return status.Errorf(status.InvalidArgument, "group is nil")
+ }
+
+ if err := s.db.Omit(clause.Associations).Create(group).Error; err != nil {
+ log.WithContext(ctx).Errorf("failed to save group to store: %v", err)
return status.Errorf(status.Internal, "failed to save group to store")
}
+
+ return nil
+}
+
+// UpdateGroup updates a group in the store.
+func (s *SqlStore) UpdateGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error {
+ if group == nil {
+ return status.Errorf(status.InvalidArgument, "group is nil")
+ }
+
+ if err := s.db.Omit(clause.Associations).Save(group).Error; err != nil {
+ log.WithContext(ctx).Errorf("failed to save group to store: %v", err)
+ return status.Errorf(status.Internal, "failed to save group to store")
+ }
+
return nil
}
// DeleteGroup deletes a group from the database.
func (s *SqlStore) DeleteGroup(ctx context.Context, lockStrength LockingStrength, accountID, groupID string) error {
result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).
+ Select(clause.Associations).
Delete(&types.Group{}, accountAndIDQueryCondition, accountID, groupID)
if err := result.Error; err != nil {
log.WithContext(ctx).Errorf("failed to delete group from store: %s", result.Error)
@@ -1818,6 +1947,7 @@ func (s *SqlStore) DeleteGroup(ctx context.Context, lockStrength LockingStrength
// DeleteGroups deletes groups from the database.
func (s *SqlStore) DeleteGroups(ctx context.Context, strength LockingStrength, accountID string, groupIDs []string) error {
result := s.db.Clauses(clause.Locking{Strength: string(strength)}).
+ Select(clause.Associations).
Delete(&types.Group{}, accountAndIDsQueryCondition, accountID, groupIDs)
if result.Error != nil {
log.WithContext(ctx).Errorf("failed to delete groups from store: %v", result.Error)
@@ -2613,3 +2743,27 @@ func (s *SqlStore) CountAccountsByPrivateDomain(ctx context.Context, domain stri
return count, nil
}
+
+func (s *SqlStore) GetAccountGroupPeers(ctx context.Context, lockStrength LockingStrength, accountID string) (map[string]map[string]struct{}, error) {
+ tx := s.db
+ if lockStrength != LockingStrengthNone {
+ tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)})
+ }
+
+ var peers []types.GroupPeer
+ result := tx.Find(&peers, accountIDCondition, accountID)
+ if result.Error != nil {
+ log.WithContext(ctx).Errorf("failed to get account group peers from store: %s", result.Error)
+ return nil, status.Errorf(status.Internal, "failed to get account group peers from store")
+ }
+
+ groupPeers := make(map[string]map[string]struct{})
+ for _, peer := range peers {
+ if _, exists := groupPeers[peer.GroupID]; !exists {
+ groupPeers[peer.GroupID] = make(map[string]struct{})
+ }
+ groupPeers[peer.GroupID][peer.PeerID] = struct{}{}
+ }
+
+ return groupPeers, nil
+}
diff --git a/management/server/store/sql_store_test.go b/management/server/store/sql_store_test.go
index 738c5a28c..fdce9d735 100644
--- a/management/server/store/sql_store_test.go
+++ b/management/server/store/sql_store_test.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
b64 "encoding/base64"
+ "encoding/binary"
"fmt"
"math/rand"
"net"
@@ -26,7 +27,7 @@ import (
networkTypes "github.com/netbirdio/netbird/management/server/networks/types"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/util"
nbroute "github.com/netbirdio/netbird/route"
@@ -1187,7 +1188,7 @@ func TestSqlite_CreateAndGetObjectInTransaction(t *testing.T) {
Peers: nil,
}
err = store.ExecuteInTransaction(context.Background(), func(transaction Store) error {
- err := transaction.SaveGroup(context.Background(), LockingStrengthUpdate, group)
+ err := transaction.CreateGroup(context.Background(), LockingStrengthUpdate, group)
if err != nil {
t.Fatal("failed to save group")
return err
@@ -1348,7 +1349,8 @@ func TestSqlStore_GetGroupsByIDs(t *testing.T) {
}
}
-func TestSqlStore_SaveGroup(t *testing.T) {
+func TestSqlStore_CreateGroup(t *testing.T) {
+ t.Setenv("NETBIRD_STORE_ENGINE", string(types.MysqlStoreEngine))
store, cleanup, err := NewTestStoreFromSQL(context.Background(), "../testdata/extended-store.sql", t.TempDir())
t.Cleanup(cleanup)
require.NoError(t, err)
@@ -1356,12 +1358,14 @@ func TestSqlStore_SaveGroup(t *testing.T) {
accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b"
group := &types.Group{
- ID: "group-id",
- AccountID: accountID,
- Issued: "api",
- Peers: []string{"peer1", "peer2"},
+ ID: "group-id",
+ AccountID: accountID,
+ Issued: "api",
+ Peers: []string{},
+ Resources: []types.Resource{},
+ GroupPeers: []types.GroupPeer{},
}
- err = store.SaveGroup(context.Background(), LockingStrengthUpdate, group)
+ err = store.CreateGroup(context.Background(), LockingStrengthUpdate, group)
require.NoError(t, err)
savedGroup, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, "group-id")
@@ -1369,7 +1373,7 @@ func TestSqlStore_SaveGroup(t *testing.T) {
require.Equal(t, savedGroup, group)
}
-func TestSqlStore_SaveGroups(t *testing.T) {
+func TestSqlStore_CreateUpdateGroups(t *testing.T) {
store, cleanup, err := NewTestStoreFromSQL(context.Background(), "../testdata/extended-store.sql", t.TempDir())
t.Cleanup(cleanup)
require.NoError(t, err)
@@ -1378,23 +1382,27 @@ func TestSqlStore_SaveGroups(t *testing.T) {
groups := []*types.Group{
{
- ID: "group-1",
- AccountID: accountID,
- Issued: "api",
- Peers: []string{"peer1", "peer2"},
+ ID: "group-1",
+ AccountID: accountID,
+ Issued: "api",
+ Peers: []string{},
+ Resources: []types.Resource{},
+ GroupPeers: []types.GroupPeer{},
},
{
- ID: "group-2",
- AccountID: accountID,
- Issued: "integration",
- Peers: []string{"peer3", "peer4"},
+ ID: "group-2",
+ AccountID: accountID,
+ Issued: "integration",
+ Peers: []string{},
+ Resources: []types.Resource{},
+ GroupPeers: []types.GroupPeer{},
},
}
- err = store.SaveGroups(context.Background(), LockingStrengthUpdate, accountID, groups)
+ err = store.CreateGroups(context.Background(), LockingStrengthUpdate, accountID, groups)
require.NoError(t, err)
groups[1].Peers = []string{}
- err = store.SaveGroups(context.Background(), LockingStrengthUpdate, accountID, groups)
+ err = store.UpdateGroups(context.Background(), LockingStrengthUpdate, accountID, groups)
require.NoError(t, err)
group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groups[1].ID)
@@ -2523,7 +2531,7 @@ func TestSqlStore_AddPeerToGroup(t *testing.T) {
require.NoError(t, err, "failed to get group")
require.Len(t, group.Peers, 0, "group should have 0 peers")
- err = store.AddPeerToGroup(context.Background(), LockingStrengthUpdate, accountID, peerID, groupID)
+ err = store.AddPeerToGroup(context.Background(), accountID, peerID, groupID)
require.NoError(t, err, "failed to add peer to group")
group, err = store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID)
@@ -2554,7 +2562,7 @@ func TestSqlStore_AddPeerToAllGroup(t *testing.T) {
err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer)
require.NoError(t, err, "failed to add peer to account")
- err = store.AddPeerToAllGroup(context.Background(), LockingStrengthUpdate, accountID, peer.ID)
+ err = store.AddPeerToAllGroup(context.Background(), accountID, peer.ID)
require.NoError(t, err, "failed to add peer to all group")
group, err = store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID)
@@ -2640,7 +2648,7 @@ func TestSqlStore_GetPeerGroups(t *testing.T) {
assert.Len(t, groups, 1)
assert.Equal(t, groups[0].Name, "All")
- err = store.AddPeerToGroup(context.Background(), LockingStrengthUpdate, accountID, peerID, "cfefqs706sqkneg59g4h")
+ err = store.AddPeerToGroup(context.Background(), accountID, peerID, "cfefqs706sqkneg59g4h")
require.NoError(t, err)
groups, err = store.GetPeerGroups(context.Background(), LockingStrengthShare, accountID, peerID)
@@ -3307,7 +3315,7 @@ func TestSqlStore_SaveGroups_LargeBatch(t *testing.T) {
})
}
- err = store.SaveGroups(context.Background(), LockingStrengthUpdate, accountID, groupsToSave)
+ err = store.CreateGroups(context.Background(), LockingStrengthUpdate, accountID, groupsToSave)
require.NoError(t, err)
accountGroups, err = store.GetAccountGroups(context.Background(), LockingStrengthShare, accountID)
@@ -3538,3 +3546,64 @@ func TestSqlStore_GetAnyAccountID(t *testing.T) {
assert.Empty(t, accountID)
})
}
+
+func BenchmarkGetAccountPeers(b *testing.B) {
+ store, cleanup, err := NewTestStoreFromSQL(context.Background(), "../testdata/store_with_expired_peers.sql", b.TempDir())
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.Cleanup(cleanup)
+
+ numberOfPeers := 1000
+ numberOfGroups := 200
+ numberOfPeersPerGroup := 500
+ accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b"
+
+ peers := make([]*nbpeer.Peer, 0, numberOfPeers)
+ for i := 0; i < numberOfPeers; i++ {
+ peer := &nbpeer.Peer{
+ ID: fmt.Sprintf("peer-%d", i),
+ AccountID: accountID,
+ DNSLabel: fmt.Sprintf("peer%d.example.com", i),
+ IP: intToIPv4(uint32(i)),
+ }
+ err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer)
+ if err != nil {
+ b.Fatalf("Failed to add peer: %v", err)
+ }
+ peers = append(peers, peer)
+ }
+
+ for i := 0; i < numberOfGroups; i++ {
+ groupID := fmt.Sprintf("group-%d", i)
+ group := &types.Group{
+ ID: groupID,
+ AccountID: accountID,
+ }
+ err = store.CreateGroup(context.Background(), LockingStrengthUpdate, group)
+ if err != nil {
+ b.Fatalf("Failed to create group: %v", err)
+ }
+ for j := 0; j < numberOfPeersPerGroup; j++ {
+ peerIndex := (i*numberOfPeersPerGroup + j) % numberOfPeers
+ err = store.AddPeerToGroup(context.Background(), accountID, peers[peerIndex].ID, groupID)
+ if err != nil {
+ b.Fatalf("Failed to add peer to group: %v", err)
+ }
+ }
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ _, err := store.GetPeerGroups(context.Background(), LockingStrengthShare, accountID, peers[i%numberOfPeers].ID)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func intToIPv4(n uint32) net.IP {
+ ip := make(net.IP, 4)
+ binary.BigEndian.PutUint32(ip, n)
+ return ip
+}
diff --git a/management/server/store/store.go b/management/server/store/store.go
index b3254c4c9..912939bc2 100644
--- a/management/server/store/store.go
+++ b/management/server/store/store.go
@@ -101,8 +101,10 @@ type Store interface {
GetGroupByID(ctx context.Context, lockStrength LockingStrength, accountID, groupID string) (*types.Group, error)
GetGroupByName(ctx context.Context, lockStrength LockingStrength, groupName, accountID string) (*types.Group, error)
GetGroupsByIDs(ctx context.Context, lockStrength LockingStrength, accountID string, groupIDs []string) (map[string]*types.Group, error)
- SaveGroups(ctx context.Context, lockStrength LockingStrength, accountID string, groups []*types.Group) error
- SaveGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error
+ CreateGroups(ctx context.Context, lockStrength LockingStrength, accountID string, groups []*types.Group) error
+ UpdateGroups(ctx context.Context, lockStrength LockingStrength, accountID string, groups []*types.Group) error
+ CreateGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error
+ UpdateGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error
DeleteGroup(ctx context.Context, lockStrength LockingStrength, accountID, groupID string) error
DeleteGroups(ctx context.Context, strength LockingStrength, accountID string, groupIDs []string) error
@@ -120,9 +122,12 @@ type Store interface {
DeletePostureChecks(ctx context.Context, lockStrength LockingStrength, accountID, postureChecksID string) error
GetPeerLabelsInAccount(ctx context.Context, lockStrength LockingStrength, accountId string, hostname string) ([]string, error)
- AddPeerToAllGroup(ctx context.Context, lockStrength LockingStrength, accountID string, peerID string) error
- AddPeerToGroup(ctx context.Context, lockStrength LockingStrength, accountId string, peerId string, groupID string) error
+ AddPeerToAllGroup(ctx context.Context, accountID string, peerID string) error
+ AddPeerToGroup(ctx context.Context, accountID, peerId string, groupID string) error
+ RemovePeerFromGroup(ctx context.Context, peerID string, groupID string) error
+ RemovePeerFromAllGroups(ctx context.Context, peerID string) error
GetPeerGroups(ctx context.Context, lockStrength LockingStrength, accountId string, peerId string) ([]*types.Group, error)
+ GetPeerGroupIDs(ctx context.Context, lockStrength LockingStrength, accountId string, peerId string) ([]string, error)
AddResourceToGroup(ctx context.Context, accountId string, groupID string, resource *types.Resource) error
RemoveResourceFromGroup(ctx context.Context, accountId string, groupID string, resourceID string) error
AddPeerToAccount(ctx context.Context, lockStrength LockingStrength, peer *nbpeer.Peer) error
@@ -196,6 +201,7 @@ type Store interface {
DeleteNetworkResource(ctx context.Context, lockStrength LockingStrength, accountID, resourceID string) error
GetPeerByIP(ctx context.Context, lockStrength LockingStrength, accountID string, ip net.IP) (*nbpeer.Peer, error)
GetPeerIdByLabel(ctx context.Context, lockStrength LockingStrength, accountID string, hostname string) (string, error)
+ GetAccountGroupPeers(ctx context.Context, lockStrength LockingStrength, accountID string) (map[string]map[string]struct{}, error)
}
const (
@@ -353,6 +359,15 @@ func getMigrationsPostAuto(ctx context.Context) []migrationFunc {
func(db *gorm.DB) error {
return migration.CreateIndexIfNotExists[nbpeer.Peer](ctx, db, "idx_account_dnslabel", "account_id", "dns_label")
},
+ func(db *gorm.DB) error {
+ return migration.MigrateJsonToTable[types.Group](ctx, db, "peers", func(accountID, id, value string) any {
+ return &types.GroupPeer{
+ AccountID: accountID,
+ GroupID: id,
+ PeerID: value,
+ }
+ })
+ },
}
}
diff --git a/management/server/token_mgr.go b/management/server/token_mgr.go
index 2f1243512..6f6e20b48 100644
--- a/management/server/token_mgr.go
+++ b/management/server/token_mgr.go
@@ -11,11 +11,11 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/settings"
"github.com/netbirdio/netbird/management/server/types"
- auth "github.com/netbirdio/netbird/relay/auth/hmac"
- authv2 "github.com/netbirdio/netbird/relay/auth/hmac/v2"
+ auth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ authv2 "github.com/netbirdio/netbird/shared/relay/auth/hmac/v2"
integrationsConfig "github.com/netbirdio/management-integrations/integrations/config"
)
diff --git a/management/server/token_mgr_test.go b/management/server/token_mgr_test.go
index b2184717d..8bd757565 100644
--- a/management/server/token_mgr_test.go
+++ b/management/server/token_mgr_test.go
@@ -13,7 +13,7 @@ import (
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/settings"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/util"
diff --git a/management/server/types/account.go b/management/server/types/account.go
index f0887be07..17a838aae 100644
--- a/management/server/types/account.go
+++ b/management/server/types/account.go
@@ -16,13 +16,13 @@ import (
log "github.com/sirupsen/logrus"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
resourceTypes "github.com/netbirdio/netbird/management/server/networks/resources/types"
routerTypes "github.com/netbirdio/netbird/management/server/networks/routers/types"
networkTypes "github.com/netbirdio/netbird/management/server/networks/types"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/posture"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/util"
"github.com/netbirdio/netbird/route"
@@ -73,7 +73,7 @@ type Account struct {
Users map[string]*User `gorm:"-"`
UsersG []User `json:"-" gorm:"foreignKey:AccountID;references:id"`
Groups map[string]*Group `gorm:"-"`
- GroupsG []Group `json:"-" gorm:"foreignKey:AccountID;references:id"`
+ GroupsG []*Group `json:"-" gorm:"foreignKey:AccountID;references:id"`
Policies []*Policy `gorm:"foreignKey:AccountID;references:id"`
Routes map[route.ID]*route.Route `gorm:"-"`
RoutesG []route.Route `json:"-" gorm:"foreignKey:AccountID;references:id"`
diff --git a/management/server/types/config.go b/management/server/types/config.go
index 5c64d6c6d..bb1dddbb1 100644
--- a/management/server/types/config.go
+++ b/management/server/types/config.go
@@ -3,7 +3,7 @@ package types
import (
"net/netip"
- "github.com/netbirdio/netbird/management/client/common"
+ "github.com/netbirdio/netbird/shared/management/client/common"
"github.com/netbirdio/netbird/management/server/idp"
"github.com/netbirdio/netbird/util"
)
@@ -53,7 +53,7 @@ type Config struct {
StoreConfig StoreConfig
ReverseProxy ReverseProxy
-
+
// disable default all-to-all policy
DisableDefaultPolicy bool
}
diff --git a/management/server/types/group.go b/management/server/types/group.go
index 1b321387c..00fdf7a69 100644
--- a/management/server/types/group.go
+++ b/management/server/types/group.go
@@ -26,7 +26,8 @@ type Group struct {
Issued string
// Peers list of the group
- Peers []string `gorm:"serializer:json"`
+ Peers []string `gorm:"-"` // Peers and GroupPeers list will be ignored when writing to the DB. Use AddPeerToGroup and RemovePeerFromGroup methods to modify group membership
+ GroupPeers []GroupPeer `gorm:"foreignKey:GroupID;references:id;constraint:OnDelete:CASCADE;"`
// Resources contains a list of resources in that group
Resources []Resource `gorm:"serializer:json"`
@@ -34,6 +35,32 @@ type Group struct {
IntegrationReference integration_reference.IntegrationReference `gorm:"embedded;embeddedPrefix:integration_ref_"`
}
+type GroupPeer struct {
+ AccountID string `gorm:"index"`
+ GroupID string `gorm:"primaryKey"`
+ PeerID string `gorm:"primaryKey"`
+}
+
+func (g *Group) LoadGroupPeers() {
+ g.Peers = make([]string, len(g.GroupPeers))
+ for i, peer := range g.GroupPeers {
+ g.Peers[i] = peer.PeerID
+ }
+ g.GroupPeers = []GroupPeer{}
+}
+
+func (g *Group) StoreGroupPeers() {
+ g.GroupPeers = make([]GroupPeer, len(g.Peers))
+ for i, peer := range g.Peers {
+ g.GroupPeers[i] = GroupPeer{
+ AccountID: g.AccountID,
+ GroupID: g.ID,
+ PeerID: peer,
+ }
+ }
+ g.Peers = []string{}
+}
+
// EventMeta returns activity event meta related to the group
func (g *Group) EventMeta() map[string]any {
return map[string]any{"name": g.Name}
@@ -46,13 +73,16 @@ func (g *Group) EventMetaResource(resource *types.NetworkResource) map[string]an
func (g *Group) Copy() *Group {
group := &Group{
ID: g.ID,
+ AccountID: g.AccountID,
Name: g.Name,
Issued: g.Issued,
Peers: make([]string, len(g.Peers)),
+ GroupPeers: make([]GroupPeer, len(g.GroupPeers)),
Resources: make([]Resource, len(g.Resources)),
IntegrationReference: g.IntegrationReference,
}
copy(group.Peers, g.Peers)
+ copy(group.GroupPeers, g.GroupPeers)
copy(group.Resources, g.Resources)
return group
}
diff --git a/management/server/types/network.go b/management/server/types/network.go
index eb8415264..f072a4294 100644
--- a/management/server/types/network.go
+++ b/management/server/types/network.go
@@ -12,9 +12,9 @@ import (
"golang.org/x/exp/maps"
nbdns "github.com/netbirdio/netbird/dns"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
nbpeer "github.com/netbirdio/netbird/management/server/peer"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/util"
"github.com/netbirdio/netbird/route"
)
@@ -163,7 +163,10 @@ func (n *Network) Copy() *Network {
// E.g. if ipNet=100.30.0.0/16 and takenIps=[100.30.0.1, 100.30.0.4] then the result would be 100.30.0.2 or 100.30.0.3
func AllocatePeerIP(ipNet net.IPNet, takenIps []net.IP) (net.IP, error) {
baseIP := ipToUint32(ipNet.IP.Mask(ipNet.Mask))
- totalIPs := uint32(1 << SubnetSize)
+
+ ones, bits := ipNet.Mask.Size()
+ hostBits := bits - ones
+ totalIPs := uint32(1 << hostBits)
taken := make(map[uint32]struct{}, len(takenIps)+1)
taken[baseIP] = struct{}{} // reserve network IP
diff --git a/management/server/types/network_test.go b/management/server/types/network_test.go
index d0b0894d4..4c1459ce5 100644
--- a/management/server/types/network_test.go
+++ b/management/server/types/network_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestNewNetwork(t *testing.T) {
@@ -38,6 +39,107 @@ func TestAllocatePeerIP(t *testing.T) {
}
}
+func TestAllocatePeerIPSmallSubnet(t *testing.T) {
+ // Test /27 network (10.0.0.0/27) - should only have 30 usable IPs (10.0.0.1 to 10.0.0.30)
+ ipNet := net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.IPMask{255, 255, 255, 224}}
+ var ips []net.IP
+
+ // Allocate all available IPs in the /27 network
+ for i := 0; i < 30; i++ {
+ ip, err := AllocatePeerIP(ipNet, ips)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Verify IP is within the correct range
+ if !ipNet.Contains(ip) {
+ t.Errorf("allocated IP %s is not within network %s", ip.String(), ipNet.String())
+ }
+
+ ips = append(ips, ip)
+ }
+
+ assert.Len(t, ips, 30)
+
+ // Verify all IPs are unique
+ uniq := make(map[string]struct{})
+ for _, ip := range ips {
+ if _, ok := uniq[ip.String()]; !ok {
+ uniq[ip.String()] = struct{}{}
+ } else {
+ t.Errorf("found duplicate IP %s", ip.String())
+ }
+ }
+
+ // Try to allocate one more IP - should fail as network is full
+ _, err := AllocatePeerIP(ipNet, ips)
+ if err == nil {
+ t.Error("expected error when network is full, but got none")
+ }
+}
+
+func TestAllocatePeerIPVariousCIDRs(t *testing.T) {
+ testCases := []struct {
+ name string
+ cidr string
+ expectedUsable int
+ }{
+ {"/30 network", "192.168.1.0/30", 2}, // 4 total - 2 reserved = 2 usable
+ {"/29 network", "192.168.1.0/29", 6}, // 8 total - 2 reserved = 6 usable
+ {"/28 network", "192.168.1.0/28", 14}, // 16 total - 2 reserved = 14 usable
+ {"/27 network", "192.168.1.0/27", 30}, // 32 total - 2 reserved = 30 usable
+ {"/26 network", "192.168.1.0/26", 62}, // 64 total - 2 reserved = 62 usable
+ {"/25 network", "192.168.1.0/25", 126}, // 128 total - 2 reserved = 126 usable
+ {"/16 network", "10.0.0.0/16", 65534}, // 65536 total - 2 reserved = 65534 usable
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ _, ipNet, err := net.ParseCIDR(tc.cidr)
+ require.NoError(t, err)
+
+ var ips []net.IP
+
+ // For larger networks, test only a subset to avoid long test runs
+ testCount := tc.expectedUsable
+ if testCount > 1000 {
+ testCount = 1000
+ }
+
+ // Allocate IPs and verify they're within the correct range
+ for i := 0; i < testCount; i++ {
+ ip, err := AllocatePeerIP(*ipNet, ips)
+ require.NoError(t, err, "failed to allocate IP %d", i)
+
+ // Verify IP is within the correct range
+ assert.True(t, ipNet.Contains(ip), "allocated IP %s is not within network %s", ip.String(), ipNet.String())
+
+ // Verify IP is not network or broadcast address
+ networkIP := ipNet.IP.Mask(ipNet.Mask)
+ ones, bits := ipNet.Mask.Size()
+ hostBits := bits - ones
+ broadcastInt := uint32(ipToUint32(networkIP)) + (1 << hostBits) - 1
+ broadcastIP := uint32ToIP(broadcastInt)
+
+ assert.False(t, ip.Equal(networkIP), "allocated network address %s", ip.String())
+ assert.False(t, ip.Equal(broadcastIP), "allocated broadcast address %s", ip.String())
+
+ ips = append(ips, ip)
+ }
+
+ assert.Len(t, ips, testCount)
+
+ // Verify all IPs are unique
+ uniq := make(map[string]struct{})
+ for _, ip := range ips {
+ ipStr := ip.String()
+ assert.NotContains(t, uniq, ipStr, "found duplicate IP %s", ipStr)
+ uniq[ipStr] = struct{}{}
+ }
+ })
+ }
+}
+
func TestGenerateIPs(t *testing.T) {
ipNet := net.IPNet{IP: net.ParseIP("100.64.0.0"), Mask: net.IPMask{255, 255, 255, 0}}
ips, ipsLen := generateIPs(&ipNet, map[string]struct{}{"100.64.0.0": {}})
diff --git a/management/server/types/policyrule.go b/management/server/types/policyrule.go
index b86732415..2643ae45c 100644
--- a/management/server/types/policyrule.go
+++ b/management/server/types/policyrule.go
@@ -1,7 +1,7 @@
package types
import (
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
)
// PolicyUpdateOperationType operation type
diff --git a/management/server/types/resource.go b/management/server/types/resource.go
index 820872f20..84d8e4b88 100644
--- a/management/server/types/resource.go
+++ b/management/server/types/resource.go
@@ -1,7 +1,7 @@
package types
import (
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
type Resource struct {
diff --git a/management/server/types/route_firewall_rule.go b/management/server/types/route_firewall_rule.go
index c09c64a3d..6eb391cb5 100644
--- a/management/server/types/route_firewall_rule.go
+++ b/management/server/types/route_firewall_rule.go
@@ -1,7 +1,7 @@
package types
import (
- "github.com/netbirdio/netbird/management/domain"
+ "github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/route"
)
diff --git a/management/server/types/settings.go b/management/server/types/settings.go
index 37c728bf8..436eb337c 100644
--- a/management/server/types/settings.go
+++ b/management/server/types/settings.go
@@ -1,6 +1,7 @@
package types
import (
+ "net/netip"
"time"
)
@@ -42,6 +43,9 @@ type Settings struct {
// DNSDomain is the custom domain for that account
DNSDomain string
+ // NetworkRange is the custom network range for that account
+ NetworkRange netip.Prefix `gorm:"serializer:json"`
+
// Extra is a dictionary of Account settings
Extra *ExtraSettings `gorm:"embedded;embeddedPrefix:extra_"`
@@ -66,6 +70,7 @@ func (s *Settings) Copy() *Settings {
RoutingPeerDNSResolutionEnabled: s.RoutingPeerDNSResolutionEnabled,
LazyConnectionEnabled: s.LazyConnectionEnabled,
DNSDomain: s.DNSDomain,
+ NetworkRange: s.NetworkRange,
}
if s.Extra != nil {
settings.Extra = s.Extra.Copy()
diff --git a/management/server/types/setupkey.go b/management/server/types/setupkey.go
index 69b381ae5..3d421342d 100644
--- a/management/server/types/setupkey.go
+++ b/management/server/types/setupkey.go
@@ -35,7 +35,7 @@ type SetupKey struct {
// AccountID is a reference to Account that this object belongs
AccountID string `json:"-" gorm:"index"`
Key string
- KeySecret string
+ KeySecret string `gorm:"index"`
Name string
Type SetupKeyType
CreatedAt time.Time
diff --git a/management/server/updatechannel.go b/management/server/updatechannel.go
index a85650136..da12f1b70 100644
--- a/management/server/updatechannel.go
+++ b/management/server/updatechannel.go
@@ -7,7 +7,7 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/netbirdio/netbird/management/server/types"
)
diff --git a/management/server/updatechannel_test.go b/management/server/updatechannel_test.go
index 69f5b895c..0dc86563d 100644
--- a/management/server/updatechannel_test.go
+++ b/management/server/updatechannel_test.go
@@ -5,7 +5,7 @@ import (
"testing"
"time"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/proto"
)
// var peersUpdater *PeersUpdateManager
diff --git a/management/server/user.go b/management/server/user.go
index 7d8382978..e33f89dfd 100644
--- a/management/server/user.go
+++ b/management/server/user.go
@@ -17,7 +17,7 @@ import (
nbpeer "github.com/netbirdio/netbird/management/server/peer"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/operations"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/store"
"github.com/netbirdio/netbird/management/server/types"
"github.com/netbirdio/netbird/management/server/users"
@@ -677,13 +677,18 @@ func (am *DefaultAccountManager) processUserUpdate(ctx context.Context, transact
if update.AutoGroups != nil && settings.GroupsPropagationEnabled {
removedGroups := util.Difference(oldUser.AutoGroups, update.AutoGroups)
- updatedGroups, err := updateUserPeersInGroups(groupsMap, userPeers, update.AutoGroups, removedGroups)
- if err != nil {
- return false, nil, nil, nil, fmt.Errorf("error modifying user peers in groups: %w", err)
- }
-
- if err = transaction.SaveGroups(ctx, store.LockingStrengthUpdate, accountID, updatedGroups); err != nil {
- return false, nil, nil, nil, fmt.Errorf("error saving groups: %w", err)
+ addedGroups := util.Difference(update.AutoGroups, oldUser.AutoGroups)
+ for _, peer := range userPeers {
+ for _, groupID := range removedGroups {
+ if err := transaction.RemovePeerFromGroup(ctx, peer.ID, groupID); err != nil {
+ return false, nil, nil, nil, fmt.Errorf("failed to remove peer %s from group %s: %w", peer.ID, groupID, err)
+ }
+ }
+ for _, groupID := range addedGroups {
+ if err := transaction.AddPeerToGroup(ctx, accountID, peer.ID, groupID); err != nil {
+ return false, nil, nil, nil, fmt.Errorf("failed to add peer %s to group %s: %w", peer.ID, groupID, err)
+ }
+ }
}
}
@@ -933,6 +938,7 @@ func (am *DefaultAccountManager) BuildUserInfosForAccount(ctx context.Context, a
// expireAndUpdatePeers expires all peers of the given user and updates them in the account
func (am *DefaultAccountManager) expireAndUpdatePeers(ctx context.Context, accountID string, peers []*nbpeer.Peer) error {
+ log.WithContext(ctx).Debugf("Expiring %d peers for account %s", len(peers), accountID)
settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID)
if err != nil {
return err
@@ -963,7 +969,7 @@ func (am *DefaultAccountManager) expireAndUpdatePeers(ctx context.Context, accou
if len(peerIDs) != 0 {
// this will trigger peer disconnect from the management service
am.peersUpdateManager.CloseChannels(ctx, peerIDs)
- am.UpdateAccountPeers(ctx, accountID)
+ am.BufferUpdateAccountPeers(ctx, accountID)
}
return nil
}
@@ -1137,93 +1143,6 @@ func (am *DefaultAccountManager) GetOwnerInfo(ctx context.Context, accountID str
return userInfo, nil
}
-// updateUserPeersInGroups updates the user's peers in the specified groups by adding or removing them.
-func updateUserPeersInGroups(accountGroups map[string]*types.Group, peers []*nbpeer.Peer, groupsToAdd, groupsToRemove []string) (groupsToUpdate []*types.Group, err error) {
- if len(groupsToAdd) == 0 && len(groupsToRemove) == 0 {
- return
- }
-
- userPeerIDMap := make(map[string]struct{}, len(peers))
- for _, peer := range peers {
- userPeerIDMap[peer.ID] = struct{}{}
- }
-
- for _, gid := range groupsToAdd {
- group, ok := accountGroups[gid]
- if !ok {
- return nil, errors.New("group not found")
- }
- if changed := addUserPeersToGroup(userPeerIDMap, group); changed {
- groupsToUpdate = append(groupsToUpdate, group)
- }
- }
-
- for _, gid := range groupsToRemove {
- group, ok := accountGroups[gid]
- if !ok {
- return nil, errors.New("group not found")
- }
- if changed := removeUserPeersFromGroup(userPeerIDMap, group); changed {
- groupsToUpdate = append(groupsToUpdate, group)
- }
- }
-
- return groupsToUpdate, nil
-}
-
-// addUserPeersToGroup adds the user's peers to the group.
-func addUserPeersToGroup(userPeerIDs map[string]struct{}, group *types.Group) bool {
- groupPeers := make(map[string]struct{}, len(group.Peers))
- for _, pid := range group.Peers {
- groupPeers[pid] = struct{}{}
- }
-
- changed := false
- for pid := range userPeerIDs {
- if _, exists := groupPeers[pid]; !exists {
- groupPeers[pid] = struct{}{}
- changed = true
- }
- }
-
- group.Peers = make([]string, 0, len(groupPeers))
- for pid := range groupPeers {
- group.Peers = append(group.Peers, pid)
- }
-
- if changed {
- group.Peers = make([]string, 0, len(groupPeers))
- for pid := range groupPeers {
- group.Peers = append(group.Peers, pid)
- }
- }
- return changed
-}
-
-// removeUserPeersFromGroup removes user's peers from the group.
-func removeUserPeersFromGroup(userPeerIDs map[string]struct{}, group *types.Group) bool {
- // skip removing peers from group All
- if group.Name == "All" {
- return false
- }
-
- updatedPeers := make([]string, 0, len(group.Peers))
- changed := false
-
- for _, pid := range group.Peers {
- if _, owned := userPeerIDs[pid]; owned {
- changed = true
- continue
- }
- updatedPeers = append(updatedPeers, pid)
- }
-
- if changed {
- group.Peers = updatedPeers
- }
- return changed
-}
-
func findUserInIDPUserdata(userID string, userData []*idp.UserData) (*idp.UserData, bool) {
for _, user := range userData {
if user.ID == userID {
diff --git a/management/server/user_test.go b/management/server/user_test.go
index 53baf8f7e..7515439b8 100644
--- a/management/server/user_test.go
+++ b/management/server/user_test.go
@@ -15,7 +15,7 @@ import (
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/permissions/modules"
"github.com/netbirdio/netbird/management/server/permissions/roles"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
"github.com/netbirdio/netbird/management/server/users"
"github.com/netbirdio/netbird/management/server/util"
@@ -1335,11 +1335,11 @@ func TestUserAccountPeersUpdate(t *testing.T) {
// account groups propagation is enabled
manager, account, peer1, peer2, peer3 := setupNetworkMapTest(t)
- err := manager.SaveGroup(context.Background(), account.Id, userID, &types.Group{
+ err := manager.CreateGroup(context.Background(), account.Id, userID, &types.Group{
ID: "groupA",
Name: "GroupA",
Peers: []string{peer1.ID, peer2.ID, peer3.ID},
- }, true)
+ })
require.NoError(t, err)
policy := &types.Policy{
diff --git a/relay/LICENSE b/relay/LICENSE
new file mode 100644
index 000000000..be3f7b28e
--- /dev/null
+++ b/relay/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ 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
+them 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey 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;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ 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.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+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.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ 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
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/relay/cmd/root.go b/relay/cmd/root.go
index 7b8e5bbeb..c662dfbb7 100644
--- a/relay/cmd/root.go
+++ b/relay/cmd/root.go
@@ -17,7 +17,7 @@ import (
"github.com/spf13/cobra"
"github.com/netbirdio/netbird/encryption"
- "github.com/netbirdio/netbird/relay/auth"
+ "github.com/netbirdio/netbird/shared/relay/auth"
"github.com/netbirdio/netbird/relay/server"
"github.com/netbirdio/netbird/signal/metrics"
"github.com/netbirdio/netbird/util"
diff --git a/relay/server/handshake.go b/relay/server/handshake.go
index eb72b3bae..922369798 100644
--- a/relay/server/handshake.go
+++ b/relay/server/handshake.go
@@ -6,11 +6,11 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
//nolint:staticcheck
- "github.com/netbirdio/netbird/relay/messages/address"
+ "github.com/netbirdio/netbird/shared/relay/messages/address"
//nolint:staticcheck
- authmsg "github.com/netbirdio/netbird/relay/messages/auth"
+ authmsg "github.com/netbirdio/netbird/shared/relay/messages/auth"
)
type Validator interface {
diff --git a/relay/server/listener/ws/listener.go b/relay/server/listener/ws/listener.go
index 3a95951ee..8579fb137 100644
--- a/relay/server/listener/ws/listener.go
+++ b/relay/server/listener/ws/listener.go
@@ -10,10 +10,12 @@ import (
"github.com/coder/websocket"
log "github.com/sirupsen/logrus"
+
+ "github.com/netbirdio/netbird/shared/relay"
)
// URLPath is the path for the websocket connection.
-const URLPath = "/relay"
+const URLPath = relay.WebSocketURLPath
type Listener struct {
// Address is the address to listen on.
diff --git a/relay/server/peer.go b/relay/server/peer.go
index 9caa5b06f..c47f2e960 100644
--- a/relay/server/peer.go
+++ b/relay/server/peer.go
@@ -9,8 +9,8 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/relay/healthcheck"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/healthcheck"
+ "github.com/netbirdio/netbird/shared/relay/messages"
"github.com/netbirdio/netbird/relay/metrics"
"github.com/netbirdio/netbird/relay/server/store"
)
diff --git a/relay/server/server.go b/relay/server/server.go
index f0b480ee4..59695e8a9 100644
--- a/relay/server/server.go
+++ b/relay/server/server.go
@@ -10,7 +10,7 @@ import (
"github.com/netbirdio/netbird/relay/server/listener"
"github.com/netbirdio/netbird/relay/server/listener/quic"
"github.com/netbirdio/netbird/relay/server/listener/ws"
- quictls "github.com/netbirdio/netbird/relay/tls"
+ quictls "github.com/netbirdio/netbird/shared/relay/tls"
log "github.com/sirupsen/logrus"
)
diff --git a/relay/server/store/listener.go b/relay/server/store/listener.go
index e9c77d953..f09f2ffdd 100644
--- a/relay/server/store/listener.go
+++ b/relay/server/store/listener.go
@@ -4,7 +4,7 @@ import (
"context"
"sync"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
type event struct {
diff --git a/relay/server/store/notifier.go b/relay/server/store/notifier.go
index 335522537..0140d6633 100644
--- a/relay/server/store/notifier.go
+++ b/relay/server/store/notifier.go
@@ -4,7 +4,7 @@ import (
"context"
"sync"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
type PeerNotifier struct {
diff --git a/relay/server/store/store.go b/relay/server/store/store.go
index fd0578603..556307885 100644
--- a/relay/server/store/store.go
+++ b/relay/server/store/store.go
@@ -3,7 +3,7 @@ package store
import (
"sync"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
type IPeer interface {
diff --git a/relay/server/store/store_test.go b/relay/server/store/store_test.go
index ad549a62c..1bf68aa59 100644
--- a/relay/server/store/store_test.go
+++ b/relay/server/store/store_test.go
@@ -3,7 +3,7 @@ package store
import (
"testing"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
type MocPeer struct {
diff --git a/relay/test/benchmark_test.go b/relay/test/benchmark_test.go
index afbb14b84..6b8a6f701 100644
--- a/relay/test/benchmark_test.go
+++ b/relay/test/benchmark_test.go
@@ -13,9 +13,9 @@ import (
"github.com/pion/logging"
"github.com/pion/turn/v3"
- "github.com/netbirdio/netbird/relay/auth/allow"
- "github.com/netbirdio/netbird/relay/auth/hmac"
- "github.com/netbirdio/netbird/relay/client"
+ "github.com/netbirdio/netbird/shared/relay/auth/allow"
+ "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ "github.com/netbirdio/netbird/shared/relay/client"
"github.com/netbirdio/netbird/relay/server"
"github.com/netbirdio/netbird/util"
)
diff --git a/relay/testec2/relay.go b/relay/testec2/relay.go
index 9e22a80ea..aa0fc662a 100644
--- a/relay/testec2/relay.go
+++ b/relay/testec2/relay.go
@@ -11,8 +11,8 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/relay/auth/hmac"
- "github.com/netbirdio/netbird/relay/client"
+ "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ "github.com/netbirdio/netbird/shared/relay/client"
)
var (
diff --git a/route/route.go b/route/route.go
index 722dacc2d..bf62bf666 100644
--- a/route/route.go
+++ b/route/route.go
@@ -6,8 +6,8 @@ import (
"slices"
"strings"
- "github.com/netbirdio/netbird/management/domain"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ "github.com/netbirdio/netbird/shared/management/status"
)
// Windows has some limitation regarding metric size that differ from Unix-like systems.
diff --git a/shared/context/keys.go b/shared/context/keys.go
new file mode 100644
index 000000000..5345ee214
--- /dev/null
+++ b/shared/context/keys.go
@@ -0,0 +1,8 @@
+package context
+
+const (
+ RequestIDKey = "requestID"
+ AccountIDKey = "accountID"
+ UserIDKey = "userID"
+ PeerIDKey = "peerID"
+)
\ No newline at end of file
diff --git a/management/client/client.go b/shared/management/client/client.go
similarity index 87%
rename from management/client/client.go
rename to shared/management/client/client.go
index 950f6137e..3126bcd1f 100644
--- a/management/client/client.go
+++ b/shared/management/client/client.go
@@ -7,8 +7,8 @@ import (
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/netbirdio/netbird/client/system"
- "github.com/netbirdio/netbird/management/domain"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ "github.com/netbirdio/netbird/shared/management/proto"
)
type Client interface {
@@ -22,4 +22,5 @@ type Client interface {
GetNetworkMap(sysInfo *system.Info) (*proto.NetworkMap, error)
IsHealthy() bool
SyncMeta(sysInfo *system.Info) error
+ Logout() error
}
diff --git a/management/client/client_test.go b/shared/management/client/client_test.go
similarity index 98%
rename from management/client/client_test.go
rename to shared/management/client/client_test.go
index 5b2a87492..061f21d44 100644
--- a/management/client/client_test.go
+++ b/shared/management/client/client_test.go
@@ -26,7 +26,7 @@ import (
"github.com/netbirdio/management-integrations/integrations"
"github.com/netbirdio/netbird/encryption"
- mgmtProto "github.com/netbirdio/netbird/management/proto"
+ mgmtProto "github.com/netbirdio/netbird/shared/management/proto"
mgmt "github.com/netbirdio/netbird/management/server"
"github.com/netbirdio/netbird/management/server/mock_server"
@@ -52,7 +52,7 @@ func startManagement(t *testing.T) (*grpc.Server, net.Listener) {
log.SetLevel(level)
config := &types.Config{}
- _, err := util.ReadJson("../server/testdata/management.json", config)
+ _, err := util.ReadJson("../../../management/server/testdata/management.json", config)
if err != nil {
t.Fatal(err)
}
@@ -62,7 +62,7 @@ func startManagement(t *testing.T) (*grpc.Server, net.Listener) {
t.Fatal(err)
}
s := grpc.NewServer()
- store, cleanUp, err := store.NewTestStoreFromSQL(context.Background(), "../server/testdata/store.sql", t.TempDir())
+ store, cleanUp, err := store.NewTestStoreFromSQL(context.Background(), "../../../management/server/testdata/store.sql", t.TempDir())
if err != nil {
t.Fatal(err)
}
diff --git a/management/client/common/types.go b/shared/management/client/common/types.go
similarity index 100%
rename from management/client/common/types.go
rename to shared/management/client/common/types.go
diff --git a/shared/management/client/go.sum b/shared/management/client/go.sum
new file mode 100644
index 000000000..4badfd6cb
--- /dev/null
+++ b/shared/management/client/go.sum
@@ -0,0 +1,3 @@
+github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
+golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
+google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
diff --git a/management/client/grpc.go b/shared/management/client/grpc.go
similarity index 95%
rename from management/client/grpc.go
rename to shared/management/client/grpc.go
index ef26574bd..7e3004945 100644
--- a/management/client/grpc.go
+++ b/shared/management/client/grpc.go
@@ -19,8 +19,8 @@ import (
"github.com/netbirdio/netbird/client/system"
"github.com/netbirdio/netbird/encryption"
- "github.com/netbirdio/netbird/management/domain"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ "github.com/netbirdio/netbird/shared/management/proto"
nbgrpc "github.com/netbirdio/netbird/util/grpc"
)
@@ -497,6 +497,32 @@ func (c *GrpcClient) notifyConnected() {
c.connStateCallback.MarkManagementConnected()
}
+func (c *GrpcClient) Logout() error {
+ serverKey, err := c.GetServerPublicKey()
+ if err != nil {
+ return fmt.Errorf("get server public key: %w", err)
+ }
+
+ mgmCtx, cancel := context.WithTimeout(c.ctx, time.Second*5)
+ defer cancel()
+
+ message := &proto.Empty{}
+ encryptedMSG, err := encryption.EncryptMessage(*serverKey, c.key, message)
+ if err != nil {
+ return fmt.Errorf("encrypt logout message: %w", err)
+ }
+
+ _, err = c.realClient.Logout(mgmCtx, &proto.EncryptedMessage{
+ WgPubKey: c.key.PublicKey().String(),
+ Body: encryptedMSG,
+ })
+ if err != nil {
+ return fmt.Errorf("logout: %w", err)
+ }
+
+ return nil
+}
+
func infoToMetaData(info *system.Info) *proto.PeerSystemMeta {
if info == nil {
return nil
diff --git a/management/client/mock.go b/shared/management/client/mock.go
similarity index 91%
rename from management/client/mock.go
rename to shared/management/client/mock.go
index 9e1786f82..29006c9c3 100644
--- a/management/client/mock.go
+++ b/shared/management/client/mock.go
@@ -6,8 +6,8 @@ import (
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/netbirdio/netbird/client/system"
- "github.com/netbirdio/netbird/management/domain"
- "github.com/netbirdio/netbird/management/proto"
+ "github.com/netbirdio/netbird/shared/management/domain"
+ "github.com/netbirdio/netbird/shared/management/proto"
)
type MockClient struct {
@@ -19,6 +19,7 @@ type MockClient struct {
GetDeviceAuthorizationFlowFunc func(serverKey wgtypes.Key) (*proto.DeviceAuthorizationFlow, error)
GetPKCEAuthorizationFlowFunc func(serverKey wgtypes.Key) (*proto.PKCEAuthorizationFlow, error)
SyncMetaFunc func(sysInfo *system.Info) error
+ LogoutFunc func() error
}
func (m *MockClient) IsHealthy() bool {
@@ -85,3 +86,10 @@ func (m *MockClient) SyncMeta(sysInfo *system.Info) error {
}
return m.SyncMetaFunc(sysInfo)
}
+
+func (m *MockClient) Logout() error {
+ if m.LogoutFunc == nil {
+ return nil
+ }
+ return m.LogoutFunc()
+}
diff --git a/management/client/rest/accounts.go b/shared/management/client/rest/accounts.go
similarity index 96%
rename from management/client/rest/accounts.go
rename to shared/management/client/rest/accounts.go
index fbe3010e1..2211f4a43 100644
--- a/management/client/rest/accounts.go
+++ b/shared/management/client/rest/accounts.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// AccountsAPI APIs for accounts, do not use directly
diff --git a/management/client/rest/accounts_test.go b/shared/management/client/rest/accounts_test.go
similarity index 96%
rename from management/client/rest/accounts_test.go
rename to shared/management/client/rest/accounts_test.go
index d2ace4ec9..be0066488 100644
--- a/management/client/rest/accounts_test.go
+++ b/shared/management/client/rest/accounts_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/client.go b/shared/management/client/rest/client.go
similarity index 98%
rename from management/client/rest/client.go
rename to shared/management/client/rest/client.go
index b5945985f..2a5de5bbc 100644
--- a/management/client/rest/client.go
+++ b/shared/management/client/rest/client.go
@@ -8,7 +8,7 @@ import (
"io"
"net/http"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
// Client Management service HTTP REST API Client
diff --git a/management/client/rest/client_test.go b/shared/management/client/rest/client_test.go
similarity index 85%
rename from management/client/rest/client_test.go
rename to shared/management/client/rest/client_test.go
index 70e6c73e1..56c859652 100644
--- a/management/client/rest/client_test.go
+++ b/shared/management/client/rest/client_test.go
@@ -8,7 +8,7 @@ import (
"net/http/httptest"
"testing"
- "github.com/netbirdio/netbird/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
"github.com/netbirdio/netbird/management/server/http/testing/testing_tools"
)
@@ -26,7 +26,7 @@ func ptr[T any, PT *T](x T) PT {
func withBlackBoxServer(t *testing.T, callback func(*rest.Client)) {
t.Helper()
- handler, _, _ := testing_tools.BuildApiBlackBoxWithDBState(t, "../../server/testdata/store.sql", nil, false)
+ handler, _, _ := testing_tools.BuildApiBlackBoxWithDBState(t, "../../../../management/server/testdata/store.sql", nil, false)
server := httptest.NewServer(handler)
defer server.Close()
c := rest.New(server.URL, "nbp_apTmlmUXHSC4PKmHwtIZNaGr8eqcVI2gMURp")
diff --git a/management/client/rest/dns.go b/shared/management/client/rest/dns.go
similarity index 98%
rename from management/client/rest/dns.go
rename to shared/management/client/rest/dns.go
index 3fb74d5f5..aeef02735 100644
--- a/management/client/rest/dns.go
+++ b/shared/management/client/rest/dns.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// DNSAPI APIs for DNS Management, do not use directly
diff --git a/management/client/rest/dns_test.go b/shared/management/client/rest/dns_test.go
similarity index 98%
rename from management/client/rest/dns_test.go
rename to shared/management/client/rest/dns_test.go
index b2e0a0bee..58082abe8 100644
--- a/management/client/rest/dns_test.go
+++ b/shared/management/client/rest/dns_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/events.go b/shared/management/client/rest/events.go
similarity index 89%
rename from management/client/rest/events.go
rename to shared/management/client/rest/events.go
index 775d3ba2e..2d25333ae 100644
--- a/management/client/rest/events.go
+++ b/shared/management/client/rest/events.go
@@ -3,7 +3,7 @@ package rest
import (
"context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// EventsAPI APIs for Events, do not use directly
diff --git a/management/client/rest/events_test.go b/shared/management/client/rest/events_test.go
similarity index 90%
rename from management/client/rest/events_test.go
rename to shared/management/client/rest/events_test.go
index 2589193a2..b28390001 100644
--- a/management/client/rest/events_test.go
+++ b/shared/management/client/rest/events_test.go
@@ -12,9 +12,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/geo.go b/shared/management/client/rest/geo.go
similarity index 95%
rename from management/client/rest/geo.go
rename to shared/management/client/rest/geo.go
index dfecee09e..3c4a3ff9f 100644
--- a/management/client/rest/geo.go
+++ b/shared/management/client/rest/geo.go
@@ -3,7 +3,7 @@ package rest
import (
"context"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// GeoLocationAPI APIs for Geo-Location, do not use directly
diff --git a/management/client/rest/geo_test.go b/shared/management/client/rest/geo_test.go
similarity index 93%
rename from management/client/rest/geo_test.go
rename to shared/management/client/rest/geo_test.go
index d24405094..fcb4808a1 100644
--- a/management/client/rest/geo_test.go
+++ b/shared/management/client/rest/geo_test.go
@@ -12,9 +12,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/groups.go b/shared/management/client/rest/groups.go
similarity index 97%
rename from management/client/rest/groups.go
rename to shared/management/client/rest/groups.go
index 7d4bac62c..af068e077 100644
--- a/management/client/rest/groups.go
+++ b/shared/management/client/rest/groups.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// GroupsAPI APIs for Groups, do not use directly
diff --git a/management/client/rest/groups_test.go b/shared/management/client/rest/groups_test.go
similarity index 97%
rename from management/client/rest/groups_test.go
rename to shared/management/client/rest/groups_test.go
index d6a5410e0..fcd759e9a 100644
--- a/management/client/rest/groups_test.go
+++ b/shared/management/client/rest/groups_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/impersonation.go b/shared/management/client/rest/impersonation.go
similarity index 100%
rename from management/client/rest/impersonation.go
rename to shared/management/client/rest/impersonation.go
diff --git a/management/client/rest/impersonation_test.go b/shared/management/client/rest/impersonation_test.go
similarity index 95%
rename from management/client/rest/impersonation_test.go
rename to shared/management/client/rest/impersonation_test.go
index 69c0f9728..4fb8f24eb 100644
--- a/management/client/rest/impersonation_test.go
+++ b/shared/management/client/rest/impersonation_test.go
@@ -12,8 +12,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
var (
diff --git a/management/client/rest/networks.go b/shared/management/client/rest/networks.go
similarity index 99%
rename from management/client/rest/networks.go
rename to shared/management/client/rest/networks.go
index 9441780f3..cb25dcbef 100644
--- a/management/client/rest/networks.go
+++ b/shared/management/client/rest/networks.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// NetworksAPI APIs for Networks, do not use directly
diff --git a/management/client/rest/networks_test.go b/shared/management/client/rest/networks_test.go
similarity index 99%
rename from management/client/rest/networks_test.go
rename to shared/management/client/rest/networks_test.go
index 0772d7540..ca2a294ae 100644
--- a/management/client/rest/networks_test.go
+++ b/shared/management/client/rest/networks_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/options.go b/shared/management/client/rest/options.go
similarity index 100%
rename from management/client/rest/options.go
rename to shared/management/client/rest/options.go
diff --git a/management/client/rest/peers.go b/shared/management/client/rest/peers.go
similarity index 97%
rename from management/client/rest/peers.go
rename to shared/management/client/rest/peers.go
index f4364bb62..359c21e42 100644
--- a/management/client/rest/peers.go
+++ b/shared/management/client/rest/peers.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// PeersAPI APIs for peers, do not use directly
diff --git a/management/client/rest/peers_test.go b/shared/management/client/rest/peers_test.go
similarity index 97%
rename from management/client/rest/peers_test.go
rename to shared/management/client/rest/peers_test.go
index f31e44e10..a45f9d6ec 100644
--- a/management/client/rest/peers_test.go
+++ b/shared/management/client/rest/peers_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/policies.go b/shared/management/client/rest/policies.go
similarity index 97%
rename from management/client/rest/policies.go
rename to shared/management/client/rest/policies.go
index a6e0e38d3..206205984 100644
--- a/management/client/rest/policies.go
+++ b/shared/management/client/rest/policies.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// PoliciesAPI APIs for Policies, do not use directly
diff --git a/management/client/rest/policies_test.go b/shared/management/client/rest/policies_test.go
similarity index 97%
rename from management/client/rest/policies_test.go
rename to shared/management/client/rest/policies_test.go
index 5792048df..a19d0a728 100644
--- a/management/client/rest/policies_test.go
+++ b/shared/management/client/rest/policies_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/posturechecks.go b/shared/management/client/rest/posturechecks.go
similarity index 97%
rename from management/client/rest/posturechecks.go
rename to shared/management/client/rest/posturechecks.go
index 2ab8f4549..1a440f058 100644
--- a/management/client/rest/posturechecks.go
+++ b/shared/management/client/rest/posturechecks.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// PostureChecksAPI APIs for PostureChecks, do not use directly
diff --git a/management/client/rest/posturechecks_test.go b/shared/management/client/rest/posturechecks_test.go
similarity index 97%
rename from management/client/rest/posturechecks_test.go
rename to shared/management/client/rest/posturechecks_test.go
index a891d6ac9..9b1b618df 100644
--- a/management/client/rest/posturechecks_test.go
+++ b/shared/management/client/rest/posturechecks_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/routes.go b/shared/management/client/rest/routes.go
similarity index 97%
rename from management/client/rest/routes.go
rename to shared/management/client/rest/routes.go
index 183c363cf..31024fe92 100644
--- a/management/client/rest/routes.go
+++ b/shared/management/client/rest/routes.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// RoutesAPI APIs for Routes, do not use directly
diff --git a/management/client/rest/routes_test.go b/shared/management/client/rest/routes_test.go
similarity index 97%
rename from management/client/rest/routes_test.go
rename to shared/management/client/rest/routes_test.go
index 1c698a7fb..9452a07fc 100644
--- a/management/client/rest/routes_test.go
+++ b/shared/management/client/rest/routes_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/setupkeys.go b/shared/management/client/rest/setupkeys.go
similarity index 97%
rename from management/client/rest/setupkeys.go
rename to shared/management/client/rest/setupkeys.go
index 6f26cd0b7..34c07c6ab 100644
--- a/management/client/rest/setupkeys.go
+++ b/shared/management/client/rest/setupkeys.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// SetupKeysAPI APIs for Setup keys, do not use directly
diff --git a/management/client/rest/setupkeys_test.go b/shared/management/client/rest/setupkeys_test.go
similarity index 97%
rename from management/client/rest/setupkeys_test.go
rename to shared/management/client/rest/setupkeys_test.go
index 8edce8428..0fa782da5 100644
--- a/management/client/rest/setupkeys_test.go
+++ b/shared/management/client/rest/setupkeys_test.go
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/tokens.go b/shared/management/client/rest/tokens.go
similarity index 97%
rename from management/client/rest/tokens.go
rename to shared/management/client/rest/tokens.go
index 7a63d0c9d..38b305722 100644
--- a/management/client/rest/tokens.go
+++ b/shared/management/client/rest/tokens.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// TokensAPI APIs for PATs, do not use directly
diff --git a/management/client/rest/tokens_test.go b/shared/management/client/rest/tokens_test.go
similarity index 96%
rename from management/client/rest/tokens_test.go
rename to shared/management/client/rest/tokens_test.go
index eea55d22f..ce3748751 100644
--- a/management/client/rest/tokens_test.go
+++ b/shared/management/client/rest/tokens_test.go
@@ -14,9 +14,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/client/rest/users.go b/shared/management/client/rest/users.go
similarity index 97%
rename from management/client/rest/users.go
rename to shared/management/client/rest/users.go
index f0ef54be2..b0ea46d55 100644
--- a/management/client/rest/users.go
+++ b/shared/management/client/rest/users.go
@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
- "github.com/netbirdio/netbird/management/server/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/api"
)
// UsersAPI APIs for users, do not use directly
diff --git a/management/client/rest/users_test.go b/shared/management/client/rest/users_test.go
similarity index 97%
rename from management/client/rest/users_test.go
rename to shared/management/client/rest/users_test.go
index 715eb1661..d53c4eb6a 100644
--- a/management/client/rest/users_test.go
+++ b/shared/management/client/rest/users_test.go
@@ -14,9 +14,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/netbirdio/netbird/management/client/rest"
- "github.com/netbirdio/netbird/management/server/http/api"
- "github.com/netbirdio/netbird/management/server/http/util"
+ "github.com/netbirdio/netbird/shared/management/client/rest"
+ "github.com/netbirdio/netbird/shared/management/http/api"
+ "github.com/netbirdio/netbird/shared/management/http/util"
)
var (
diff --git a/management/domain/domain.go b/shared/management/domain/domain.go
similarity index 100%
rename from management/domain/domain.go
rename to shared/management/domain/domain.go
diff --git a/management/domain/list.go b/shared/management/domain/list.go
similarity index 100%
rename from management/domain/list.go
rename to shared/management/domain/list.go
diff --git a/management/domain/list_test.go b/shared/management/domain/list_test.go
similarity index 100%
rename from management/domain/list_test.go
rename to shared/management/domain/list_test.go
diff --git a/management/domain/validate.go b/shared/management/domain/validate.go
similarity index 100%
rename from management/domain/validate.go
rename to shared/management/domain/validate.go
diff --git a/management/domain/validate_test.go b/shared/management/domain/validate_test.go
similarity index 100%
rename from management/domain/validate_test.go
rename to shared/management/domain/validate_test.go
diff --git a/management/server/http/api/cfg.yaml b/shared/management/http/api/cfg.yaml
similarity index 100%
rename from management/server/http/api/cfg.yaml
rename to shared/management/http/api/cfg.yaml
diff --git a/management/server/http/api/generate.sh b/shared/management/http/api/generate.sh
similarity index 100%
rename from management/server/http/api/generate.sh
rename to shared/management/http/api/generate.sh
diff --git a/management/server/http/api/openapi.yml b/shared/management/http/api/openapi.yml
similarity index 99%
rename from management/server/http/api/openapi.yml
rename to shared/management/http/api/openapi.yml
index f8c2b9854..877c68df0 100644
--- a/management/server/http/api/openapi.yml
+++ b/shared/management/http/api/openapi.yml
@@ -133,6 +133,11 @@ components:
description: Allows to define a custom dns domain for the account
type: string
example: my-organization.org
+ network_range:
+ description: Allows to define a custom network range for the account in CIDR format
+ type: string
+ format: cidr
+ example: 100.64.0.0/16
extra:
$ref: '#/components/schemas/AccountExtraSettings'
lazy_connection_enabled:
@@ -342,6 +347,11 @@ components:
description: (Cloud only) Indicates whether peer needs approval
type: boolean
example: true
+ ip:
+ description: Peer's IP address
+ type: string
+ format: ipv4
+ example: 100.64.0.15
required:
- name
- ssh_enabled
diff --git a/management/server/http/api/types.gen.go b/shared/management/http/api/types.gen.go
similarity index 99%
rename from management/server/http/api/types.gen.go
rename to shared/management/http/api/types.gen.go
index a9f17aab4..71aa9c830 100644
--- a/management/server/http/api/types.gen.go
+++ b/shared/management/http/api/types.gen.go
@@ -303,6 +303,9 @@ type AccountSettings struct {
// LazyConnectionEnabled Enables or disables experimental lazy connection
LazyConnectionEnabled *bool `json:"lazy_connection_enabled,omitempty"`
+ // NetworkRange Allows to define a custom network range for the account in CIDR format
+ NetworkRange *string `json:"network_range,omitempty"`
+
// PeerInactivityExpiration Period of time of inactivity after which peer session expires (seconds).
PeerInactivityExpiration int `json:"peer_inactivity_expiration"`
@@ -1196,11 +1199,14 @@ type PeerNetworkRangeCheckAction string
// PeerRequest defines model for PeerRequest.
type PeerRequest struct {
// ApprovalRequired (Cloud only) Indicates whether peer needs approval
- ApprovalRequired *bool `json:"approval_required,omitempty"`
- InactivityExpirationEnabled bool `json:"inactivity_expiration_enabled"`
- LoginExpirationEnabled bool `json:"login_expiration_enabled"`
- Name string `json:"name"`
- SshEnabled bool `json:"ssh_enabled"`
+ ApprovalRequired *bool `json:"approval_required,omitempty"`
+ InactivityExpirationEnabled bool `json:"inactivity_expiration_enabled"`
+
+ // Ip Peer's IP address
+ Ip *string `json:"ip,omitempty"`
+ LoginExpirationEnabled bool `json:"login_expiration_enabled"`
+ Name string `json:"name"`
+ SshEnabled bool `json:"ssh_enabled"`
}
// PersonalAccessToken defines model for PersonalAccessToken.
diff --git a/management/server/http/util/util.go b/shared/management/http/util/util.go
similarity index 98%
rename from management/server/http/util/util.go
rename to shared/management/http/util/util.go
index 3d7eed498..3ae321023 100644
--- a/management/server/http/util/util.go
+++ b/shared/management/http/util/util.go
@@ -11,7 +11,7 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/management/server/status"
+ "github.com/netbirdio/netbird/shared/management/status"
)
// EmptyObject is an empty struct used to return empty JSON object
diff --git a/shared/management/operations/operation.go b/shared/management/operations/operation.go
new file mode 100644
index 000000000..b9b500362
--- /dev/null
+++ b/shared/management/operations/operation.go
@@ -0,0 +1,4 @@
+package operations
+
+// Operation represents a permission operation type
+type Operation string
\ No newline at end of file
diff --git a/management/proto/generate.sh b/shared/management/proto/generate.sh
similarity index 100%
rename from management/proto/generate.sh
rename to shared/management/proto/generate.sh
diff --git a/shared/management/proto/go.sum b/shared/management/proto/go.sum
new file mode 100644
index 000000000..66d866626
--- /dev/null
+++ b/shared/management/proto/go.sum
@@ -0,0 +1,2 @@
+google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
+google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
diff --git a/management/proto/management.pb.go b/shared/management/proto/management.pb.go
similarity index 99%
rename from management/proto/management.pb.go
rename to shared/management/proto/management.pb.go
index 8503f2e94..848610c78 100644
--- a/management/proto/management.pb.go
+++ b/shared/management/proto/management.pb.go
@@ -3825,7 +3825,7 @@ var file_management_proto_rawDesc = []byte{
0x6e, 0x12, 0x06, 0x0a, 0x02, 0x49, 0x4e, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x4f, 0x55, 0x54,
0x10, 0x01, 0x2a, 0x22, 0x0a, 0x0a, 0x52, 0x75, 0x6c, 0x65, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e,
0x12, 0x0a, 0x0a, 0x06, 0x41, 0x43, 0x43, 0x45, 0x50, 0x54, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04,
- 0x44, 0x52, 0x4f, 0x50, 0x10, 0x01, 0x32, 0x90, 0x04, 0x0a, 0x11, 0x4d, 0x61, 0x6e, 0x61, 0x67,
+ 0x44, 0x52, 0x4f, 0x50, 0x10, 0x01, 0x32, 0xcd, 0x04, 0x0a, 0x11, 0x4d, 0x61, 0x6e, 0x61, 0x67,
0x65, 0x6d, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x45, 0x0a, 0x05,
0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x1c, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65,
0x6e, 0x74, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73,
@@ -3858,8 +3858,12 @@ var file_management_proto_rawDesc = []byte{
0x6e, 0x63, 0x4d, 0x65, 0x74, 0x61, 0x12, 0x1c, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d,
0x65, 0x6e, 0x74, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x1a, 0x11, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e,
- 0x74, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x22, 0x00, 0x42, 0x08, 0x5a, 0x06, 0x2f, 0x70, 0x72,
- 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+ 0x74, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x22, 0x00, 0x12, 0x3b, 0x0a, 0x06, 0x4c, 0x6f, 0x67,
+ 0x6f, 0x75, 0x74, 0x12, 0x1c, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74,
+ 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67,
+ 0x65, 0x1a, 0x11, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x45,
+ 0x6d, 0x70, 0x74, 0x79, 0x22, 0x00, 0x42, 0x08, 0x5a, 0x06, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
+ 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
@@ -3986,15 +3990,17 @@ var file_management_proto_depIdxs = []int32{
5, // 57: management.ManagementService.GetDeviceAuthorizationFlow:input_type -> management.EncryptedMessage
5, // 58: management.ManagementService.GetPKCEAuthorizationFlow:input_type -> management.EncryptedMessage
5, // 59: management.ManagementService.SyncMeta:input_type -> management.EncryptedMessage
- 5, // 60: management.ManagementService.Login:output_type -> management.EncryptedMessage
- 5, // 61: management.ManagementService.Sync:output_type -> management.EncryptedMessage
- 16, // 62: management.ManagementService.GetServerKey:output_type -> management.ServerKeyResponse
- 17, // 63: management.ManagementService.isHealthy:output_type -> management.Empty
- 5, // 64: management.ManagementService.GetDeviceAuthorizationFlow:output_type -> management.EncryptedMessage
- 5, // 65: management.ManagementService.GetPKCEAuthorizationFlow:output_type -> management.EncryptedMessage
- 17, // 66: management.ManagementService.SyncMeta:output_type -> management.Empty
- 60, // [60:67] is the sub-list for method output_type
- 53, // [53:60] is the sub-list for method input_type
+ 5, // 60: management.ManagementService.Logout:input_type -> management.EncryptedMessage
+ 5, // 61: management.ManagementService.Login:output_type -> management.EncryptedMessage
+ 5, // 62: management.ManagementService.Sync:output_type -> management.EncryptedMessage
+ 16, // 63: management.ManagementService.GetServerKey:output_type -> management.ServerKeyResponse
+ 17, // 64: management.ManagementService.isHealthy:output_type -> management.Empty
+ 5, // 65: management.ManagementService.GetDeviceAuthorizationFlow:output_type -> management.EncryptedMessage
+ 5, // 66: management.ManagementService.GetPKCEAuthorizationFlow:output_type -> management.EncryptedMessage
+ 17, // 67: management.ManagementService.SyncMeta:output_type -> management.Empty
+ 17, // 68: management.ManagementService.Logout:output_type -> management.Empty
+ 61, // [61:69] is the sub-list for method output_type
+ 53, // [53:61] is the sub-list for method input_type
53, // [53:53] is the sub-list for extension type_name
53, // [53:53] is the sub-list for extension extendee
0, // [0:53] is the sub-list for field type_name
diff --git a/management/proto/management.proto b/shared/management/proto/management.proto
similarity index 99%
rename from management/proto/management.proto
rename to shared/management/proto/management.proto
index 8e137df93..d5441d352 100644
--- a/management/proto/management.proto
+++ b/shared/management/proto/management.proto
@@ -45,6 +45,9 @@ service ManagementService {
// sync meta will evaluate the checks and update the peer meta with the result.
// EncryptedMessage of the request has a body of Empty.
rpc SyncMeta(EncryptedMessage) returns (Empty) {}
+
+ // Logout logs out the peer and removes it from the management server
+ rpc Logout(EncryptedMessage) returns (Empty) {}
}
message EncryptedMessage {
diff --git a/management/proto/management_grpc.pb.go b/shared/management/proto/management_grpc.pb.go
similarity index 91%
rename from management/proto/management_grpc.pb.go
rename to shared/management/proto/management_grpc.pb.go
index badf242f5..5b189334d 100644
--- a/management/proto/management_grpc.pb.go
+++ b/shared/management/proto/management_grpc.pb.go
@@ -48,6 +48,8 @@ type ManagementServiceClient interface {
// sync meta will evaluate the checks and update the peer meta with the result.
// EncryptedMessage of the request has a body of Empty.
SyncMeta(ctx context.Context, in *EncryptedMessage, opts ...grpc.CallOption) (*Empty, error)
+ // Logout logs out the peer and removes it from the management server
+ Logout(ctx context.Context, in *EncryptedMessage, opts ...grpc.CallOption) (*Empty, error)
}
type managementServiceClient struct {
@@ -144,6 +146,15 @@ func (c *managementServiceClient) SyncMeta(ctx context.Context, in *EncryptedMes
return out, nil
}
+func (c *managementServiceClient) Logout(ctx context.Context, in *EncryptedMessage, opts ...grpc.CallOption) (*Empty, error) {
+ out := new(Empty)
+ err := c.cc.Invoke(ctx, "/management.ManagementService/Logout", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// ManagementServiceServer is the server API for ManagementService service.
// All implementations must embed UnimplementedManagementServiceServer
// for forward compatibility
@@ -178,6 +189,8 @@ type ManagementServiceServer interface {
// sync meta will evaluate the checks and update the peer meta with the result.
// EncryptedMessage of the request has a body of Empty.
SyncMeta(context.Context, *EncryptedMessage) (*Empty, error)
+ // Logout logs out the peer and removes it from the management server
+ Logout(context.Context, *EncryptedMessage) (*Empty, error)
mustEmbedUnimplementedManagementServiceServer()
}
@@ -206,6 +219,9 @@ func (UnimplementedManagementServiceServer) GetPKCEAuthorizationFlow(context.Con
func (UnimplementedManagementServiceServer) SyncMeta(context.Context, *EncryptedMessage) (*Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method SyncMeta not implemented")
}
+func (UnimplementedManagementServiceServer) Logout(context.Context, *EncryptedMessage) (*Empty, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented")
+}
func (UnimplementedManagementServiceServer) mustEmbedUnimplementedManagementServiceServer() {}
// UnsafeManagementServiceServer may be embedded to opt out of forward compatibility for this service.
@@ -348,6 +364,24 @@ func _ManagementService_SyncMeta_Handler(srv interface{}, ctx context.Context, d
return interceptor(ctx, in, info, handler)
}
+func _ManagementService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(EncryptedMessage)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ManagementServiceServer).Logout(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/management.ManagementService/Logout",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ManagementServiceServer).Logout(ctx, req.(*EncryptedMessage))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// ManagementService_ServiceDesc is the grpc.ServiceDesc for ManagementService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -379,6 +413,10 @@ var ManagementService_ServiceDesc = grpc.ServiceDesc{
MethodName: "SyncMeta",
Handler: _ManagementService_SyncMeta_Handler,
},
+ {
+ MethodName: "Logout",
+ Handler: _ManagementService_Logout_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{
diff --git a/management/server/status/error.go b/shared/management/status/error.go
similarity index 99%
rename from management/server/status/error.go
rename to shared/management/status/error.go
index e3cc27b29..7660174d6 100644
--- a/management/server/status/error.go
+++ b/shared/management/status/error.go
@@ -4,7 +4,7 @@ import (
"errors"
"fmt"
- "github.com/netbirdio/netbird/management/server/permissions/operations"
+ "github.com/netbirdio/netbird/shared/management/operations"
)
const (
diff --git a/relay/auth/allow/allow_all.go b/shared/relay/auth/allow/allow_all.go
similarity index 100%
rename from relay/auth/allow/allow_all.go
rename to shared/relay/auth/allow/allow_all.go
diff --git a/relay/auth/doc.go b/shared/relay/auth/doc.go
similarity index 100%
rename from relay/auth/doc.go
rename to shared/relay/auth/doc.go
diff --git a/shared/relay/auth/go.sum b/shared/relay/auth/go.sum
new file mode 100644
index 000000000..938ef5547
--- /dev/null
+++ b/shared/relay/auth/go.sum
@@ -0,0 +1 @@
+golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
diff --git a/relay/auth/hmac/doc.go b/shared/relay/auth/hmac/doc.go
similarity index 100%
rename from relay/auth/hmac/doc.go
rename to shared/relay/auth/hmac/doc.go
diff --git a/relay/auth/hmac/store.go b/shared/relay/auth/hmac/store.go
similarity index 92%
rename from relay/auth/hmac/store.go
rename to shared/relay/auth/hmac/store.go
index 169b8d6b0..f177b5b06 100644
--- a/relay/auth/hmac/store.go
+++ b/shared/relay/auth/hmac/store.go
@@ -5,7 +5,7 @@ import (
"fmt"
"sync"
- v2 "github.com/netbirdio/netbird/relay/auth/hmac/v2"
+ v2 "github.com/netbirdio/netbird/shared/relay/auth/hmac/v2"
)
// TokenStore is a simple in-memory store for token
diff --git a/relay/auth/hmac/token.go b/shared/relay/auth/hmac/token.go
similarity index 100%
rename from relay/auth/hmac/token.go
rename to shared/relay/auth/hmac/token.go
diff --git a/relay/auth/hmac/token_test.go b/shared/relay/auth/hmac/token_test.go
similarity index 100%
rename from relay/auth/hmac/token_test.go
rename to shared/relay/auth/hmac/token_test.go
diff --git a/relay/auth/hmac/v2/algo.go b/shared/relay/auth/hmac/v2/algo.go
similarity index 100%
rename from relay/auth/hmac/v2/algo.go
rename to shared/relay/auth/hmac/v2/algo.go
diff --git a/relay/auth/hmac/v2/generator.go b/shared/relay/auth/hmac/v2/generator.go
similarity index 100%
rename from relay/auth/hmac/v2/generator.go
rename to shared/relay/auth/hmac/v2/generator.go
diff --git a/relay/auth/hmac/v2/hmac_test.go b/shared/relay/auth/hmac/v2/hmac_test.go
similarity index 100%
rename from relay/auth/hmac/v2/hmac_test.go
rename to shared/relay/auth/hmac/v2/hmac_test.go
diff --git a/relay/auth/hmac/v2/token.go b/shared/relay/auth/hmac/v2/token.go
similarity index 100%
rename from relay/auth/hmac/v2/token.go
rename to shared/relay/auth/hmac/v2/token.go
diff --git a/relay/auth/hmac/v2/validator.go b/shared/relay/auth/hmac/v2/validator.go
similarity index 100%
rename from relay/auth/hmac/v2/validator.go
rename to shared/relay/auth/hmac/v2/validator.go
diff --git a/relay/auth/hmac/validator.go b/shared/relay/auth/hmac/validator.go
similarity index 100%
rename from relay/auth/hmac/validator.go
rename to shared/relay/auth/hmac/validator.go
diff --git a/relay/auth/validator.go b/shared/relay/auth/validator.go
similarity index 83%
rename from relay/auth/validator.go
rename to shared/relay/auth/validator.go
index 56a20fbfe..8e339bb2e 100644
--- a/relay/auth/validator.go
+++ b/shared/relay/auth/validator.go
@@ -3,8 +3,8 @@ package auth
import (
"time"
- auth "github.com/netbirdio/netbird/relay/auth/hmac"
- authv2 "github.com/netbirdio/netbird/relay/auth/hmac/v2"
+ auth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ authv2 "github.com/netbirdio/netbird/shared/relay/auth/hmac/v2"
)
type TimedHMACValidator struct {
diff --git a/relay/client/addr.go b/shared/relay/client/addr.go
similarity index 100%
rename from relay/client/addr.go
rename to shared/relay/client/addr.go
diff --git a/relay/client/client.go b/shared/relay/client/client.go
similarity index 97%
rename from relay/client/client.go
rename to shared/relay/client/client.go
index e4db278f5..37c9debc2 100644
--- a/relay/client/client.go
+++ b/shared/relay/client/client.go
@@ -9,12 +9,12 @@ import (
log "github.com/sirupsen/logrus"
- auth "github.com/netbirdio/netbird/relay/auth/hmac"
- "github.com/netbirdio/netbird/relay/client/dialer"
- "github.com/netbirdio/netbird/relay/client/dialer/quic"
- "github.com/netbirdio/netbird/relay/client/dialer/ws"
- "github.com/netbirdio/netbird/relay/healthcheck"
- "github.com/netbirdio/netbird/relay/messages"
+ auth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
+ "github.com/netbirdio/netbird/shared/relay/client/dialer"
+ "github.com/netbirdio/netbird/shared/relay/client/dialer/quic"
+ "github.com/netbirdio/netbird/shared/relay/client/dialer/ws"
+ "github.com/netbirdio/netbird/shared/relay/healthcheck"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
const (
diff --git a/relay/client/client_test.go b/shared/relay/client/client_test.go
similarity index 99%
rename from relay/client/client_test.go
rename to shared/relay/client/client_test.go
index 2ce8d7e34..c7c5fbf2b 100644
--- a/relay/client/client_test.go
+++ b/shared/relay/client/client_test.go
@@ -10,8 +10,8 @@ import (
log "github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
- "github.com/netbirdio/netbird/relay/auth/allow"
- "github.com/netbirdio/netbird/relay/auth/hmac"
+ "github.com/netbirdio/netbird/shared/relay/auth/allow"
+ "github.com/netbirdio/netbird/shared/relay/auth/hmac"
"github.com/netbirdio/netbird/util"
"github.com/netbirdio/netbird/relay/server"
diff --git a/relay/client/conn.go b/shared/relay/client/conn.go
similarity index 96%
rename from relay/client/conn.go
rename to shared/relay/client/conn.go
index d8cffa695..4e151aaa4 100644
--- a/relay/client/conn.go
+++ b/shared/relay/client/conn.go
@@ -4,7 +4,7 @@ import (
"net"
"time"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
// Conn represent a connection to a relayed remote peer.
diff --git a/relay/client/dialer/net/err.go b/shared/relay/client/dialer/net/err.go
similarity index 100%
rename from relay/client/dialer/net/err.go
rename to shared/relay/client/dialer/net/err.go
diff --git a/relay/client/dialer/quic/conn.go b/shared/relay/client/dialer/quic/conn.go
similarity index 96%
rename from relay/client/dialer/quic/conn.go
rename to shared/relay/client/dialer/quic/conn.go
index d64633c8c..9243605b5 100644
--- a/relay/client/dialer/quic/conn.go
+++ b/shared/relay/client/dialer/quic/conn.go
@@ -10,7 +10,7 @@ import (
"github.com/quic-go/quic-go"
log "github.com/sirupsen/logrus"
- netErr "github.com/netbirdio/netbird/relay/client/dialer/net"
+ netErr "github.com/netbirdio/netbird/shared/relay/client/dialer/net"
)
const (
diff --git a/relay/client/dialer/quic/quic.go b/shared/relay/client/dialer/quic/quic.go
similarity index 97%
rename from relay/client/dialer/quic/quic.go
rename to shared/relay/client/dialer/quic/quic.go
index 3fd48fb19..b496f6a9b 100644
--- a/relay/client/dialer/quic/quic.go
+++ b/shared/relay/client/dialer/quic/quic.go
@@ -11,7 +11,7 @@ import (
"github.com/quic-go/quic-go"
log "github.com/sirupsen/logrus"
- quictls "github.com/netbirdio/netbird/relay/tls"
+ quictls "github.com/netbirdio/netbird/shared/relay/tls"
nbnet "github.com/netbirdio/netbird/util/net"
)
diff --git a/relay/client/dialer/race_dialer.go b/shared/relay/client/dialer/race_dialer.go
similarity index 100%
rename from relay/client/dialer/race_dialer.go
rename to shared/relay/client/dialer/race_dialer.go
diff --git a/relay/client/dialer/race_dialer_test.go b/shared/relay/client/dialer/race_dialer_test.go
similarity index 100%
rename from relay/client/dialer/race_dialer_test.go
rename to shared/relay/client/dialer/race_dialer_test.go
diff --git a/relay/client/dialer/ws/addr.go b/shared/relay/client/dialer/ws/addr.go
similarity index 100%
rename from relay/client/dialer/ws/addr.go
rename to shared/relay/client/dialer/ws/addr.go
diff --git a/relay/client/dialer/ws/conn.go b/shared/relay/client/dialer/ws/conn.go
similarity index 100%
rename from relay/client/dialer/ws/conn.go
rename to shared/relay/client/dialer/ws/conn.go
diff --git a/relay/client/dialer/ws/ws.go b/shared/relay/client/dialer/ws/ws.go
similarity index 95%
rename from relay/client/dialer/ws/ws.go
rename to shared/relay/client/dialer/ws/ws.go
index cb525865b..109651f5d 100644
--- a/relay/client/dialer/ws/ws.go
+++ b/shared/relay/client/dialer/ws/ws.go
@@ -14,7 +14,7 @@ import (
"github.com/coder/websocket"
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/relay/server/listener/ws"
+ "github.com/netbirdio/netbird/shared/relay"
"github.com/netbirdio/netbird/util/embeddedroots"
nbnet "github.com/netbirdio/netbird/util/net"
)
@@ -40,7 +40,7 @@ func (d Dialer) Dial(ctx context.Context, address string) (net.Conn, error) {
if err != nil {
return nil, err
}
- parsedURL.Path = ws.URLPath
+ parsedURL.Path = relay.WebSocketURLPath
wsConn, resp, err := websocket.Dial(ctx, parsedURL.String(), opts)
if err != nil {
diff --git a/relay/client/doc.go b/shared/relay/client/doc.go
similarity index 100%
rename from relay/client/doc.go
rename to shared/relay/client/doc.go
diff --git a/shared/relay/client/go.sum b/shared/relay/client/go.sum
new file mode 100644
index 000000000..dc9715262
--- /dev/null
+++ b/shared/relay/client/go.sum
@@ -0,0 +1,10 @@
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/relay/client/guard.go b/shared/relay/client/guard.go
similarity index 100%
rename from relay/client/guard.go
rename to shared/relay/client/guard.go
diff --git a/relay/client/manager.go b/shared/relay/client/manager.go
similarity index 99%
rename from relay/client/manager.go
rename to shared/relay/client/manager.go
index f32bb9f26..f3428f255 100644
--- a/relay/client/manager.go
+++ b/shared/relay/client/manager.go
@@ -11,7 +11,7 @@ import (
log "github.com/sirupsen/logrus"
- relayAuth "github.com/netbirdio/netbird/relay/auth/hmac"
+ relayAuth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
)
var (
diff --git a/relay/client/manager_test.go b/shared/relay/client/manager_test.go
similarity index 99%
rename from relay/client/manager_test.go
rename to shared/relay/client/manager_test.go
index d0075f982..674555ff4 100644
--- a/relay/client/manager_test.go
+++ b/shared/relay/client/manager_test.go
@@ -8,7 +8,7 @@ import (
log "github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
- "github.com/netbirdio/netbird/relay/auth/allow"
+ "github.com/netbirdio/netbird/shared/relay/auth/allow"
"github.com/netbirdio/netbird/relay/server"
)
diff --git a/relay/client/peer_subscription.go b/shared/relay/client/peer_subscription.go
similarity index 98%
rename from relay/client/peer_subscription.go
rename to shared/relay/client/peer_subscription.go
index 85bd41cbd..b594b65b7 100644
--- a/relay/client/peer_subscription.go
+++ b/shared/relay/client/peer_subscription.go
@@ -9,7 +9,7 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
)
const (
diff --git a/relay/client/peer_subscription_test.go b/shared/relay/client/peer_subscription_test.go
similarity index 97%
rename from relay/client/peer_subscription_test.go
rename to shared/relay/client/peer_subscription_test.go
index 0437efa04..bcc7a552d 100644
--- a/relay/client/peer_subscription_test.go
+++ b/shared/relay/client/peer_subscription_test.go
@@ -6,7 +6,7 @@ import (
"testing"
"time"
- "github.com/netbirdio/netbird/relay/messages"
+ "github.com/netbirdio/netbird/shared/relay/messages"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
diff --git a/relay/client/picker.go b/shared/relay/client/picker.go
similarity index 97%
rename from relay/client/picker.go
rename to shared/relay/client/picker.go
index 9565425a8..1cad466ba 100644
--- a/relay/client/picker.go
+++ b/shared/relay/client/picker.go
@@ -9,7 +9,7 @@ import (
log "github.com/sirupsen/logrus"
- auth "github.com/netbirdio/netbird/relay/auth/hmac"
+ auth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
)
const (
diff --git a/relay/client/picker_test.go b/shared/relay/client/picker_test.go
similarity index 100%
rename from relay/client/picker_test.go
rename to shared/relay/client/picker_test.go
diff --git a/shared/relay/constants.go b/shared/relay/constants.go
new file mode 100644
index 000000000..3c7c3cd29
--- /dev/null
+++ b/shared/relay/constants.go
@@ -0,0 +1,6 @@
+package relay
+
+const (
+ // WebSocketURLPath is the path for the websocket relay connection
+ WebSocketURLPath = "/relay"
+)
\ No newline at end of file
diff --git a/relay/healthcheck/doc.go b/shared/relay/healthcheck/doc.go
similarity index 100%
rename from relay/healthcheck/doc.go
rename to shared/relay/healthcheck/doc.go
diff --git a/relay/healthcheck/receiver.go b/shared/relay/healthcheck/receiver.go
similarity index 100%
rename from relay/healthcheck/receiver.go
rename to shared/relay/healthcheck/receiver.go
diff --git a/relay/healthcheck/receiver_test.go b/shared/relay/healthcheck/receiver_test.go
similarity index 100%
rename from relay/healthcheck/receiver_test.go
rename to shared/relay/healthcheck/receiver_test.go
diff --git a/relay/healthcheck/sender.go b/shared/relay/healthcheck/sender.go
similarity index 100%
rename from relay/healthcheck/sender.go
rename to shared/relay/healthcheck/sender.go
diff --git a/relay/healthcheck/sender_test.go b/shared/relay/healthcheck/sender_test.go
similarity index 100%
rename from relay/healthcheck/sender_test.go
rename to shared/relay/healthcheck/sender_test.go
diff --git a/relay/messages/address/address.go b/shared/relay/messages/address/address.go
similarity index 100%
rename from relay/messages/address/address.go
rename to shared/relay/messages/address/address.go
diff --git a/relay/messages/auth/auth.go b/shared/relay/messages/auth/auth.go
similarity index 100%
rename from relay/messages/auth/auth.go
rename to shared/relay/messages/auth/auth.go
diff --git a/relay/messages/doc.go b/shared/relay/messages/doc.go
similarity index 100%
rename from relay/messages/doc.go
rename to shared/relay/messages/doc.go
diff --git a/relay/messages/id.go b/shared/relay/messages/id.go
similarity index 100%
rename from relay/messages/id.go
rename to shared/relay/messages/id.go
diff --git a/relay/messages/message.go b/shared/relay/messages/message.go
similarity index 100%
rename from relay/messages/message.go
rename to shared/relay/messages/message.go
diff --git a/relay/messages/message_test.go b/shared/relay/messages/message_test.go
similarity index 100%
rename from relay/messages/message_test.go
rename to shared/relay/messages/message_test.go
diff --git a/relay/messages/peer_state.go b/shared/relay/messages/peer_state.go
similarity index 100%
rename from relay/messages/peer_state.go
rename to shared/relay/messages/peer_state.go
diff --git a/relay/messages/peer_state_test.go b/shared/relay/messages/peer_state_test.go
similarity index 100%
rename from relay/messages/peer_state_test.go
rename to shared/relay/messages/peer_state_test.go
diff --git a/relay/tls/alpn.go b/shared/relay/tls/alpn.go
similarity index 100%
rename from relay/tls/alpn.go
rename to shared/relay/tls/alpn.go
diff --git a/relay/tls/client_dev.go b/shared/relay/tls/client_dev.go
similarity index 100%
rename from relay/tls/client_dev.go
rename to shared/relay/tls/client_dev.go
diff --git a/relay/tls/client_prod.go b/shared/relay/tls/client_prod.go
similarity index 100%
rename from relay/tls/client_prod.go
rename to shared/relay/tls/client_prod.go
diff --git a/relay/tls/doc.go b/shared/relay/tls/doc.go
similarity index 100%
rename from relay/tls/doc.go
rename to shared/relay/tls/doc.go
diff --git a/relay/tls/server_dev.go b/shared/relay/tls/server_dev.go
similarity index 100%
rename from relay/tls/server_dev.go
rename to shared/relay/tls/server_dev.go
diff --git a/relay/tls/server_prod.go b/shared/relay/tls/server_prod.go
similarity index 100%
rename from relay/tls/server_prod.go
rename to shared/relay/tls/server_prod.go
diff --git a/signal/client/client.go b/shared/signal/client/client.go
similarity index 97%
rename from signal/client/client.go
rename to shared/signal/client/client.go
index cca69a862..e29940e75 100644
--- a/signal/client/client.go
+++ b/shared/signal/client/client.go
@@ -6,7 +6,7 @@ import (
"io"
"strings"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/signal/proto"
"github.com/netbirdio/netbird/version"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
diff --git a/signal/client/client_suite_test.go b/shared/signal/client/client_suite_test.go
similarity index 100%
rename from signal/client/client_suite_test.go
rename to shared/signal/client/client_suite_test.go
diff --git a/signal/client/client_test.go b/shared/signal/client/client_test.go
similarity index 98%
rename from signal/client/client_test.go
rename to shared/signal/client/client_test.go
index f7d4ebc50..1af34e37a 100644
--- a/signal/client/client_test.go
+++ b/shared/signal/client/client_test.go
@@ -16,7 +16,7 @@ import (
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
- sigProto "github.com/netbirdio/netbird/signal/proto"
+ sigProto "github.com/netbirdio/netbird/shared/signal/proto"
"github.com/netbirdio/netbird/signal/server"
)
diff --git a/shared/signal/client/go.sum b/shared/signal/client/go.sum
new file mode 100644
index 000000000..961f68d3d
--- /dev/null
+++ b/shared/signal/client/go.sum
@@ -0,0 +1,10 @@
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/signal/client/grpc.go b/shared/signal/client/grpc.go
similarity index 99%
rename from signal/client/grpc.go
rename to shared/signal/client/grpc.go
index bfc221858..ae40caa3b 100644
--- a/signal/client/grpc.go
+++ b/shared/signal/client/grpc.go
@@ -17,8 +17,8 @@ import (
"google.golang.org/grpc/status"
"github.com/netbirdio/netbird/encryption"
- "github.com/netbirdio/netbird/management/client"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/management/client"
+ "github.com/netbirdio/netbird/shared/signal/proto"
nbgrpc "github.com/netbirdio/netbird/util/grpc"
)
diff --git a/signal/client/mock.go b/shared/signal/client/mock.go
similarity index 97%
rename from signal/client/mock.go
rename to shared/signal/client/mock.go
index 32236c82c..95381a5b0 100644
--- a/signal/client/mock.go
+++ b/shared/signal/client/mock.go
@@ -3,7 +3,7 @@ package client
import (
"context"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/signal/proto"
)
type MockClient struct {
diff --git a/signal/client/worker.go b/shared/signal/client/worker.go
similarity index 100%
rename from signal/client/worker.go
rename to shared/signal/client/worker.go
diff --git a/signal/proto/constants.go b/shared/signal/proto/constants.go
similarity index 100%
rename from signal/proto/constants.go
rename to shared/signal/proto/constants.go
diff --git a/signal/proto/generate.sh b/shared/signal/proto/generate.sh
similarity index 100%
rename from signal/proto/generate.sh
rename to shared/signal/proto/generate.sh
diff --git a/shared/signal/proto/go.sum b/shared/signal/proto/go.sum
new file mode 100644
index 000000000..66d866626
--- /dev/null
+++ b/shared/signal/proto/go.sum
@@ -0,0 +1,2 @@
+google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
+google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
diff --git a/signal/proto/signalexchange.pb.go b/shared/signal/proto/signalexchange.pb.go
similarity index 100%
rename from signal/proto/signalexchange.pb.go
rename to shared/signal/proto/signalexchange.pb.go
diff --git a/signal/proto/signalexchange.proto b/shared/signal/proto/signalexchange.proto
similarity index 100%
rename from signal/proto/signalexchange.proto
rename to shared/signal/proto/signalexchange.proto
diff --git a/signal/proto/signalexchange_grpc.pb.go b/shared/signal/proto/signalexchange_grpc.pb.go
similarity index 100%
rename from signal/proto/signalexchange_grpc.pb.go
rename to shared/signal/proto/signalexchange_grpc.pb.go
diff --git a/signal/LICENSE b/signal/LICENSE
new file mode 100644
index 000000000..be3f7b28e
--- /dev/null
+++ b/signal/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ 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
+them 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey 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;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ 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.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+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.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ 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
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/signal/cmd/run.go b/signal/cmd/run.go
index 39bc8331f..2e89b491a 100644
--- a/signal/cmd/run.go
+++ b/signal/cmd/run.go
@@ -19,7 +19,7 @@ import (
"github.com/netbirdio/netbird/signal/metrics"
"github.com/netbirdio/netbird/encryption"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/signal/proto"
"github.com/netbirdio/netbird/signal/server"
"github.com/netbirdio/netbird/util"
"github.com/netbirdio/netbird/version"
diff --git a/signal/peer/peer.go b/signal/peer/peer.go
index 2252e877e..f21c95a41 100644
--- a/signal/peer/peer.go
+++ b/signal/peer/peer.go
@@ -8,7 +8,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/signal/metrics"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/signal/proto"
)
// Peer representation of a connected Peer
diff --git a/signal/server/signal.go b/signal/server/signal.go
index 9dfba7798..8ae14822b 100644
--- a/signal/server/signal.go
+++ b/signal/server/signal.go
@@ -17,7 +17,7 @@ import (
"github.com/netbirdio/netbird/signal/metrics"
"github.com/netbirdio/netbird/signal/peer"
- "github.com/netbirdio/netbird/signal/proto"
+ "github.com/netbirdio/netbird/shared/signal/proto"
)
const (
diff --git a/util/common.go b/util/common.go
index cd19d9747..27adb9d13 100644
--- a/util/common.go
+++ b/util/common.go
@@ -23,7 +23,6 @@ func FileExists(path string) bool {
return err == nil
}
-
/// Bool helpers
// True returns a *bool whose underlying value is true.
@@ -56,4 +55,4 @@ func ReturnBoolWithDefaultTrue(b *bool) bool {
return true
}
-}
\ No newline at end of file
+}
diff --git a/util/duration.go b/util/duration.go
index 4757bf17e..b657a582d 100644
--- a/util/duration.go
+++ b/util/duration.go
@@ -6,7 +6,7 @@ import (
"time"
)
-//Duration is used strictly for JSON requests/responses due to duration marshalling issues
+// Duration is used strictly for JSON requests/responses due to duration marshalling issues
type Duration struct {
time.Duration
}