diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index f41bc9e89..9d6bc96eb 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,6 +12,16 @@ - [ ] Is a feature enhancement - [ ] It is a refactor - [ ] Created tests that fail without the change (if possible) -- [ ] Extended the README / documentation, if necessary > By submitting this pull request, you confirm that you have read and agree to the terms of the [Contributor License Agreement](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT.md). + +## Documentation +Select exactly one: + +- [ ] I added/updated documentation for this change +- [ ] Documentation is **not needed** for this change (explain why) + +### Docs PR URL (required if "docs added" is checked) +Paste the PR link from https://github.com/netbirdio/docs here: + +https://github.com/netbirdio/docs/pull/__ 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/docs-ack.yml b/.github/workflows/docs-ack.yml new file mode 100644 index 000000000..9116be8c7 --- /dev/null +++ b/.github/workflows/docs-ack.yml @@ -0,0 +1,94 @@ +name: Docs Acknowledgement + +on: + pull_request: + types: [opened, edited, synchronize] + +permissions: + contents: read + pull-requests: read + +jobs: + docs-ack: + name: Require docs PR URL or explicit "not needed" + runs-on: ubuntu-latest + + steps: + - name: Read PR body + id: body + run: | + BODY=$(jq -r '.pull_request.body // ""' "$GITHUB_EVENT_PATH") + echo "body<> $GITHUB_OUTPUT + echo "$BODY" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Validate checkbox selection + id: validate + run: | + body='${{ steps.body.outputs.body }}' + + added_checked=$(printf "%s" "$body" | grep -E '^- \[x\] I added/updated documentation' -i | wc -l | tr -d ' ') + noneed_checked=$(printf "%s" "$body" | grep -E '^- \[x\] Documentation is \*\*not needed\*\*' -i | wc -l | tr -d ' ') + + if [ "$added_checked" -eq 1 ] && [ "$noneed_checked" -eq 1 ]; then + echo "::error::Choose exactly one: either 'docs added' OR 'not needed'." + exit 1 + fi + + if [ "$added_checked" -eq 0 ] && [ "$noneed_checked" -eq 0 ]; then + echo "::error::You must check exactly one docs option in the PR template." + exit 1 + fi + + if [ "$added_checked" -eq 1 ]; then + echo "mode=added" >> $GITHUB_OUTPUT + else + echo "mode=noneed" >> $GITHUB_OUTPUT + fi + + - name: Extract docs PR URL (when 'docs added') + if: steps.validate.outputs.mode == 'added' + id: extract + run: | + body='${{ steps.body.outputs.body }}' + + # Strictly require HTTPS and that it's a PR in netbirdio/docs + # Examples accepted: + # https://github.com/netbirdio/docs/pull/1234 + url=$(printf "%s" "$body" | grep -Eo 'https://github\.com/netbirdio/docs/pull/[0-9]+' | head -n1 || true) + + if [ -z "$url" ]; then + echo "::error::You checked 'docs added' but didn't include a valid HTTPS PR link to netbirdio/docs (e.g., https://github.com/netbirdio/docs/pull/1234)." + exit 1 + fi + + pr_number=$(echo "$url" | sed -E 's#.*/pull/([0-9]+)$#\1#') + echo "url=$url" >> $GITHUB_OUTPUT + echo "pr_number=$pr_number" >> $GITHUB_OUTPUT + + - name: Verify docs PR exists (and is open or merged) + if: steps.validate.outputs.mode == 'added' + uses: actions/github-script@v7 + id: verify + with: + pr_number: ${{ steps.extract.outputs.pr_number }} + script: | + const prNumber = parseInt(core.getInput('pr_number'), 10); + const { data } = await github.rest.pulls.get({ + owner: 'netbirdio', + repo: 'docs', + pull_number: prNumber + }); + + // Allow open or merged PRs + const ok = data.state === 'open' || data.merged === true; + core.setOutput('state', data.state); + core.setOutput('merged', String(!!data.merged)); + if (!ok) { + core.setFailed(`Docs PR #${prNumber} exists but is neither open nor merged (state=${data.state}, merged=${data.merged}).`); + } + result-encoding: string + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: All good + run: echo "Documentation requirement satisfied ✅" diff --git a/.github/workflows/forum.yml b/.github/workflows/forum.yml new file mode 100644 index 000000000..a26a72586 --- /dev/null +++ b/.github/workflows/forum.yml @@ -0,0 +1,18 @@ +name: Post release topic on Discourse + +on: + release: + types: [published] + +jobs: + post: + runs-on: ubuntu-latest + steps: + - uses: roots/discourse-topic-github-release-action@main + with: + discourse-api-key: ${{ secrets.DISCOURSE_RELEASES_API_KEY }} + discourse-base-url: https://forum.netbird.io + discourse-author-username: NetBird + discourse-category: 17 + discourse-tags: + releases 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/release.yml b/.github/workflows/release.yml index 44e02f457..7be52259b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,7 +9,7 @@ on: pull_request: env: - SIGN_PIPE_VER: "v0.0.21" + SIGN_PIPE_VER: "v0.0.22" GORELEASER_VER: "v2.3.2" PRODUCT_NAME: "NetBird" COPYRIGHT: "NetBird GmbH" @@ -79,6 +79,8 @@ jobs: run: go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@233067e - name: Generate windows syso amd64 run: goversioninfo -icon client/ui/assets/netbird.ico -manifest client/manifest.xml -product-name ${{ env.PRODUCT_NAME }} -copyright "${{ env.COPYRIGHT }}" -ver-major ${{ steps.semver_parser.outputs.major }} -ver-minor ${{ steps.semver_parser.outputs.minor }} -ver-patch ${{ steps.semver_parser.outputs.patch }} -ver-build 0 -file-version ${{ steps.semver_parser.outputs.fullversion }}.0 -product-version ${{ steps.semver_parser.outputs.fullversion }}.0 -o client/resources_windows_amd64.syso + - name: Generate windows syso arm64 + run: goversioninfo -arm -64 -icon client/ui/assets/netbird.ico -manifest client/manifest.xml -product-name ${{ env.PRODUCT_NAME }} -copyright "${{ env.COPYRIGHT }}" -ver-major ${{ steps.semver_parser.outputs.major }} -ver-minor ${{ steps.semver_parser.outputs.minor }} -ver-patch ${{ steps.semver_parser.outputs.patch }} -ver-build 0 -file-version ${{ steps.semver_parser.outputs.fullversion }}.0 -product-version ${{ steps.semver_parser.outputs.fullversion }}.0 -o client/resources_windows_arm64.syso - name: Run GoReleaser uses: goreleaser/goreleaser-action@v4 with: @@ -154,10 +156,20 @@ jobs: - name: Install dependencies run: sudo apt update && sudo apt install -y -q libappindicator3-dev gir1.2-appindicator3-0.1 libxxf86vm-dev gcc-mingw-w64-x86-64 + + - name: Install LLVM-MinGW for ARM64 cross-compilation + run: | + cd /tmp + wget -q https://github.com/mstorsjo/llvm-mingw/releases/download/20250709/llvm-mingw-20250709-ucrt-ubuntu-22.04-x86_64.tar.xz + echo "60cafae6474c7411174cff1d4ba21a8e46cadbaeb05a1bace306add301628337 llvm-mingw-20250709-ucrt-ubuntu-22.04-x86_64.tar.xz" | sha256sum -c + tar -xf llvm-mingw-20250709-ucrt-ubuntu-22.04-x86_64.tar.xz + echo "/tmp/llvm-mingw-20250709-ucrt-ubuntu-22.04-x86_64/bin" >> $GITHUB_PATH - name: Install goversioninfo run: go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@233067e - name: Generate windows syso amd64 run: goversioninfo -64 -icon client/ui/assets/netbird.ico -manifest client/ui/manifest.xml -product-name ${{ env.PRODUCT_NAME }}-"UI" -copyright "${{ env.COPYRIGHT }}" -ver-major ${{ steps.semver_parser.outputs.major }} -ver-minor ${{ steps.semver_parser.outputs.minor }} -ver-patch ${{ steps.semver_parser.outputs.patch }} -ver-build 0 -file-version ${{ steps.semver_parser.outputs.fullversion }}.0 -product-version ${{ steps.semver_parser.outputs.fullversion }}.0 -o client/ui/resources_windows_amd64.syso + - name: Generate windows syso arm64 + run: goversioninfo -arm -64 -icon client/ui/assets/netbird.ico -manifest client/ui/manifest.xml -product-name ${{ env.PRODUCT_NAME }}-"UI" -copyright "${{ env.COPYRIGHT }}" -ver-major ${{ steps.semver_parser.outputs.major }} -ver-minor ${{ steps.semver_parser.outputs.minor }} -ver-patch ${{ steps.semver_parser.outputs.patch }} -ver-build 0 -file-version ${{ steps.semver_parser.outputs.fullversion }}.0 -product-version ${{ steps.semver_parser.outputs.fullversion }}.0 -o client/ui/resources_windows_arm64.syso - name: Run GoReleaser uses: goreleaser/goreleaser-action@v4 @@ -231,17 +243,3 @@ jobs: ref: ${{ env.SIGN_PIPE_VER }} token: ${{ secrets.SIGN_GITHUB_TOKEN }} inputs: '{ "tag": "${{ github.ref }}", "skipRelease": false }' - - post_on_forum: - runs-on: ubuntu-latest - continue-on-error: true - needs: [trigger_signer] - steps: - - uses: Codixer/discourse-topic-github-release-action@v2.0.1 - with: - discourse-api-key: ${{ secrets.DISCOURSE_RELEASES_API_KEY }} - discourse-base-url: https://forum.netbird.io - discourse-author-username: NetBird - discourse-category: 17 - discourse-tags: - releases 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/.goreleaser.yaml b/.goreleaser.yaml index d4a97b447..59a95c89a 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -16,8 +16,6 @@ builds: - arm64 - 386 ignore: - - goos: windows - goarch: arm64 - goos: windows goarch: arm - goos: windows diff --git a/.goreleaser_ui.yaml b/.goreleaser_ui.yaml index 459f204d3..a243702ea 100644 --- a/.goreleaser_ui.yaml +++ b/.goreleaser_ui.yaml @@ -15,7 +15,7 @@ builds: - -s -w -X github.com/netbirdio/netbird/version.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.CommitDate}} -X main.builtBy=goreleaser mod_timestamp: "{{ .CommitTimestamp }}" - - id: netbird-ui-windows + - id: netbird-ui-windows-amd64 dir: client/ui binary: netbird-ui env: @@ -30,6 +30,22 @@ builds: - -H windowsgui mod_timestamp: "{{ .CommitTimestamp }}" + - id: netbird-ui-windows-arm64 + dir: client/ui + binary: netbird-ui + env: + - CGO_ENABLED=1 + - CC=aarch64-w64-mingw32-clang + - CXX=aarch64-w64-mingw32-clang++ + goos: + - windows + goarch: + - arm64 + ldflags: + - -s -w -X github.com/netbirdio/netbird/version.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.CommitDate}} -X main.builtBy=goreleaser + - -H windowsgui + mod_timestamp: "{{ .CommitTimestamp }}" + archives: - id: linux-arch name_template: "{{ .ProjectName }}-linux_{{ .Version }}_{{ .Os }}_{{ .Arch }}" @@ -38,7 +54,8 @@ archives: - id: windows-arch name_template: "{{ .ProjectName }}-windows_{{ .Version }}_{{ .Os }}_{{ .Arch }}" builds: - - netbird-ui-windows + - netbird-ui-windows-amd64 + - netbird-ui-windows-arm64 nfpms: - maintainer: Netbird 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/android/client.go b/client/android/client.go index 6924d333c..c05246569 100644 --- a/client/android/client.go +++ b/client/android/client.go @@ -4,6 +4,7 @@ package android import ( "context" + "slices" "sync" log "github.com/sirupsen/logrus" @@ -112,7 +113,7 @@ func (c *Client) Run(urlOpener URLOpener, dns *DNSList, dnsReadyListener DnsRead // todo do not throw error in case of cancelled context ctx = internal.CtxInitState(ctx) c.connectClient = internal.NewConnectClient(ctx, cfg, c.recorder) - return c.connectClient.RunOnAndroid(c.tunAdapter, c.iFaceDiscover, c.networkChangeListener, dns.items, dnsReadyListener) + return c.connectClient.RunOnAndroid(c.tunAdapter, c.iFaceDiscover, c.networkChangeListener, slices.Clone(dns.items), dnsReadyListener) } // RunWithoutLogin we apply this type of run function when the backed has been started without UI (i.e. after reboot). @@ -138,7 +139,7 @@ func (c *Client) RunWithoutLogin(dns *DNSList, dnsReadyListener DnsReadyListener // todo do not throw error in case of cancelled context ctx = internal.CtxInitState(ctx) c.connectClient = internal.NewConnectClient(ctx, cfg, c.recorder) - return c.connectClient.RunOnAndroid(c.tunAdapter, c.iFaceDiscover, c.networkChangeListener, dns.items, dnsReadyListener) + return c.connectClient.RunOnAndroid(c.tunAdapter, c.iFaceDiscover, c.networkChangeListener, slices.Clone(dns.items), dnsReadyListener) } // Stop the internal client and free the resources @@ -235,7 +236,7 @@ func (c *Client) OnUpdatedHostDNS(list *DNSList) error { return err } - dnsServer.OnUpdatedHostDNSServer(list.items) + dnsServer.OnUpdatedHostDNSServer(slices.Clone(list.items)) return nil } diff --git a/client/android/dns_list.go b/client/android/dns_list.go index 76b922220..4c3dff4cc 100644 --- a/client/android/dns_list.go +++ b/client/android/dns_list.go @@ -1,23 +1,34 @@ package android -import "fmt" +import ( + "fmt" + "net/netip" -// DNSList is a wrapper of []string + "github.com/netbirdio/netbird/client/internal/dns" +) + +// DNSList is a wrapper of []netip.AddrPort with default DNS port type DNSList struct { - items []string + items []netip.AddrPort } -// Add new DNS address to the collection -func (array *DNSList) Add(s string) { - array.items = append(array.items, s) +// Add new DNS address to the collection, returns error if invalid +func (array *DNSList) Add(s string) error { + addr, err := netip.ParseAddr(s) + if err != nil { + return fmt.Errorf("invalid DNS address: %s", s) + } + addrPort := netip.AddrPortFrom(addr.Unmap(), dns.DefaultPort) + array.items = append(array.items, addrPort) + return nil } -// Get return an element of the collection +// Get return an element of the collection as string func (array *DNSList) Get(i int) (string, error) { if i >= len(array.items) || i < 0 { return "", fmt.Errorf("out of range") } - return array.items[i], nil + return array.items[i].Addr().String(), nil } // Size return with the size of the collection diff --git a/client/android/dns_list_test.go b/client/android/dns_list_test.go index 93aea78a8..7cb7b33a1 100644 --- a/client/android/dns_list_test.go +++ b/client/android/dns_list_test.go @@ -3,20 +3,30 @@ package android import "testing" func TestDNSList_Get(t *testing.T) { - l := DNSList{ - items: make([]string, 1), + l := DNSList{} + + // Add a valid DNS address + err := l.Add("8.8.8.8") + if err != nil { + t.Errorf("unexpected error: %s", err) } - _, err := l.Get(0) + // Test getting valid index + addr, err := l.Get(0) if err != nil { t.Errorf("invalid error: %s", err) } + if addr != "8.8.8.8" { + t.Errorf("expected 8.8.8.8, got %s", addr) + } + // Test negative index _, err = l.Get(-1) if err == nil { t.Errorf("expected error but got nil") } + // Test out of bounds index _, err = l.Get(1) if err == nil { t.Errorf("expected error but got nil") diff --git a/client/cmd/debug.go b/client/cmd/debug.go index a79fd40d0..bfb2e61c1 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" ) @@ -33,7 +33,7 @@ var ( var debugCmd = &cobra.Command{ Use: "debug", Short: "Debugging commands", - Long: "Provides commands for debugging and logging control within the Netbird daemon.", + Long: "Provides commands for debugging and logging control within the NetBird daemon.", } var debugBundleCmd = &cobra.Command{ @@ -46,8 +46,8 @@ var debugBundleCmd = &cobra.Command{ var logCmd = &cobra.Command{ Use: "log", - Short: "Manage logging for the Netbird daemon", - Long: `Commands to manage logging settings for the Netbird daemon, including ICE, gRPC, and general log levels.`, + Short: "Manage logging for the NetBird daemon", + Long: `Commands to manage logging settings for the NetBird daemon, including ICE, gRPC, and general log levels.`, } var logLevelCmd = &cobra.Command{ @@ -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 { @@ -184,7 +184,7 @@ func runForDuration(cmd *cobra.Command, args []string) error { if _, err := client.Up(cmd.Context(), &proto.UpRequest{}); err != nil { return fmt.Errorf("failed to up: %v", status.Convert(err).Message()) } - cmd.Println("Netbird up") + cmd.Println("netbird up") time.Sleep(time.Second * 10) } @@ -202,25 +202,25 @@ func runForDuration(cmd *cobra.Command, args []string) error { if _, err := client.Down(cmd.Context(), &proto.DownRequest{}); err != nil { return fmt.Errorf("failed to down: %v", status.Convert(err).Message()) } - cmd.Println("Netbird down") + cmd.Println("netbird down") 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 { return fmt.Errorf("failed to up: %v", status.Convert(err).Message()) } - cmd.Println("Netbird up") + cmd.Println("netbird up") time.Sleep(3 * time.Second) - headerPostUp := fmt.Sprintf("----- Netbird post-up - Timestamp: %s", time.Now().Format(time.RFC3339)) + headerPostUp := fmt.Sprintf("----- NetBird post-up - Timestamp: %s", time.Now().Format(time.RFC3339)) statusOutput := fmt.Sprintf("%s\n%s", headerPostUp, getStatusOutput(cmd, anonymizeFlag)) if waitErr := waitForDurationOrCancel(cmd.Context(), duration, cmd); waitErr != nil { @@ -230,7 +230,7 @@ func runForDuration(cmd *cobra.Command, args []string) error { cmd.Println("Creating debug bundle...") - headerPreDown := fmt.Sprintf("----- Netbird pre-down - Timestamp: %s - Duration: %s", time.Now().Format(time.RFC3339), duration) + headerPreDown := fmt.Sprintf("----- NetBird pre-down - Timestamp: %s - Duration: %s", time.Now().Format(time.RFC3339), duration) statusOutput = fmt.Sprintf("%s\n%s\n%s", statusOutput, headerPreDown, getStatusOutput(cmd, anonymizeFlag)) request := &proto.DebugBundleRequest{ Anonymize: anonymizeFlag, @@ -250,7 +250,7 @@ func runForDuration(cmd *cobra.Command, args []string) error { if _, err := client.Down(cmd.Context(), &proto.DownRequest{}); err != nil { return fmt.Errorf("failed to down: %v", status.Convert(err).Message()) } - cmd.Println("Netbird down") + cmd.Println("netbird down") } if !initialLevelTrace { @@ -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/login.go b/client/cmd/login.go index d6381f6e2..a6ae13ed8 100644 --- a/client/cmd/login.go +++ b/client/cmd/login.go @@ -31,7 +31,7 @@ func init() { var loginCmd = &cobra.Command{ Use: "login", - Short: "login to the Netbird Management Service (first run)", + Short: "login to the NetBird Management Service (first run)", RunE: func(cmd *cobra.Command, args []string) error { if err := setEnvAndFlags(cmd); err != nil { return fmt.Errorf("set env and flags: %v", err) diff --git a/client/cmd/logout.go b/client/cmd/logout.go new file mode 100644 index 000000000..5e04a8c3a --- /dev/null +++ b/client/cmd/logout.go @@ -0,0 +1,58 @@ +package cmd + +import ( + "context" + "fmt" + "os/user" + "time" + + "github.com/spf13/cobra" + + "github.com/netbirdio/netbird/client/proto" +) + +var logoutCmd = &cobra.Command{ + Use: "deregister", + Aliases: []string{"logout"}, + Short: "deregister 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(cmd.Context(), time.Second*15) + 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("deregister: %v", err) + } + + cmd.Println("Deregistered 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..0cb068d05 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" @@ -17,21 +16,22 @@ import ( var profileCmd = &cobra.Command{ Use: "profile", - Short: "manage Netbird profiles", - Long: `Manage Netbird profiles, allowing you to list, switch, and remove profiles.`, + Short: "manage NetBird profiles", + Long: `Manage NetBird profiles, allowing you to list, switch, and remove profiles.`, } 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{ Use: "add ", Short: "add a new profile", - Long: `Add a new profile to the Netbird client. The profile name must be unique.`, + Long: `Add a new profile to the NetBird client. The profile name must be unique.`, Args: cobra.ExactArgs(1), RunE: addProfileFunc, } @@ -39,7 +39,7 @@ var profileAddCmd = &cobra.Command{ var profileRemoveCmd = &cobra.Command{ Use: "remove ", Short: "remove a profile", - Long: `Remove a profile from the Netbird client. The profile must not be active.`, + Long: `Remove a profile from the NetBird client. The profile must not be active.`, Args: cobra.ExactArgs(1), RunE: removeProfileFunc, } @@ -47,7 +47,7 @@ var profileRemoveCmd = &cobra.Command{ var profileSelectCmd = &cobra.Command{ Use: "select ", Short: "select a profile", - Long: `Select a profile to be the active profile in the Netbird client. The profile must exist.`, + Long: `Select a profile to be the active profile in the NetBird client. The profile must exist.`, Args: cobra.ExactArgs(1), RunE: selectProfileFunc, } diff --git a/client/cmd/root.go b/client/cmd/root.go index e3ce79964..0f9330601 100644 --- a/client/cmd/root.go +++ b/client/cmd/root.go @@ -119,20 +119,21 @@ func init() { rootCmd.PersistentFlags().StringVar(&daemonAddr, "daemon-addr", defaultDaemonAddr, "Daemon service address to serve CLI requests [unix|tcp]://[path|host:port]") rootCmd.PersistentFlags().StringVarP(&managementURL, "management-url", "m", "", fmt.Sprintf("Management Service URL [http|https]://[host]:[port] (default \"%s\")", profilemanager.DefaultManagementURL)) rootCmd.PersistentFlags().StringVar(&adminURL, "admin-url", "", fmt.Sprintf("Admin Panel URL [http|https]://[host]:[port] (default \"%s\")", profilemanager.DefaultAdminURL)) - rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "info", "sets Netbird log level") - rootCmd.PersistentFlags().StringSliceVar(&logFiles, "log-file", []string{defaultLogFile}, "sets Netbird log paths written to simultaneously. If `console` is specified the log will be output to stdout. If `syslog` is specified the log will be sent to syslog daemon. You can pass the flag multiple times or separate entries by `,` character") + rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "info", "sets NetBird log level") + rootCmd.PersistentFlags().StringSliceVar(&logFiles, "log-file", []string{defaultLogFile}, "sets NetBird log paths written to simultaneously. If `console` is specified the log will be output to stdout. If `syslog` is specified the log will be sent to syslog daemon. You can pass the flag multiple times or separate entries by `,` character") rootCmd.PersistentFlags().StringVarP(&setupKey, "setup-key", "k", "", "Setup key obtained from the Management Service Dashboard (used to register peer)") rootCmd.PersistentFlags().StringVar(&setupKeyPath, "setup-key-file", "", "The path to a setup key obtained from the Management Service Dashboard (used to register peer) This is ignored if the setup-key flag is provided.") rootCmd.MarkFlagsMutuallyExclusive("setup-key", "setup-key-file") - rootCmd.PersistentFlags().StringVar(&preSharedKey, preSharedKeyFlag, "", "Sets Wireguard PreSharedKey property. If set, then only peers that have the same key can communicate.") + 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/root_test.go b/client/cmd/root_test.go index 4cbbe8783..844eea853 100644 --- a/client/cmd/root_test.go +++ b/client/cmd/root_test.go @@ -50,10 +50,10 @@ func TestSetFlagsFromEnvVars(t *testing.T) { } cmd.PersistentFlags().StringSliceVar(&natExternalIPs, externalIPMapFlag, nil, - `comma separated list of external IPs to map to the Wireguard interface`) - cmd.PersistentFlags().StringVar(&interfaceName, interfaceNameFlag, iface.WgInterfaceDefault, "Wireguard interface name") + `comma separated list of external IPs to map to the WireGuard interface`) + cmd.PersistentFlags().StringVar(&interfaceName, interfaceNameFlag, iface.WgInterfaceDefault, "WireGuard interface name") cmd.PersistentFlags().BoolVar(&rosenpassEnabled, enableRosenpassFlag, false, "Enable Rosenpass feature Rosenpass.") - cmd.PersistentFlags().Uint16Var(&wireguardPort, wireguardPortFlag, iface.DefaultWgPort, "Wireguard interface listening port") + cmd.PersistentFlags().Uint16Var(&wireguardPort, wireguardPortFlag, iface.DefaultWgPort, "WireGuard interface listening port") t.Setenv("NB_EXTERNAL_IP_MAP", "abc,dec") t.Setenv("NB_INTERFACE_NAME", "test-name") diff --git a/client/cmd/service.go b/client/cmd/service.go index d8745f1c4..997520f4c 100644 --- a/client/cmd/service.go +++ b/client/cmd/service.go @@ -19,7 +19,7 @@ import ( var serviceCmd = &cobra.Command{ Use: "service", - Short: "manages Netbird service", + Short: "manages NetBird service", } var ( @@ -47,7 +47,7 @@ func init() { rootCmd.PersistentFlags().StringVarP(&serviceName, "service", "s", defaultServiceName, "Netbird system service name") serviceEnvDesc := `Sets extra environment variables for the service. ` + `You can specify a comma-separated list of KEY=VALUE pairs. ` + - `E.g. --service-env LOG_LEVEL=debug,CUSTOM_VAR=value` + `E.g. --service-env NB_LOG_LEVEL=debug,CUSTOM_VAR=value` installCmd.Flags().StringSliceVar(&serviceEnvVars, "service-env", nil, serviceEnvDesc) reconfigureCmd.Flags().StringSliceVar(&serviceEnvVars, "service-env", nil, serviceEnvDesc) @@ -64,7 +64,7 @@ func newSVCConfig() (*service.Config, error) { config := &service.Config{ Name: serviceName, DisplayName: "Netbird", - Description: "Netbird mesh network client", + Description: "NetBird mesh network client", Option: make(service.KeyValue), EnvVars: make(map[string]string), } diff --git a/client/cmd/service_controller.go b/client/cmd/service_controller.go index 6dc6bca9b..f67b294d4 100644 --- a/client/cmd/service_controller.go +++ b/client/cmd/service_controller.go @@ -24,7 +24,7 @@ import ( func (p *program) Start(svc service.Service) error { // Start should not block. Do the actual work async. - log.Info("starting Netbird service") //nolint + log.Info("starting NetBird service") //nolint // Collect static system and platform information system.UpdateStaticInfo() @@ -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) } @@ -97,7 +97,7 @@ func (p *program) Stop(srv service.Service) error { } time.Sleep(time.Second * 2) - log.Info("stopped Netbird service") //nolint + log.Info("stopped NetBird service") //nolint return nil } @@ -131,7 +131,7 @@ func setupServiceControlCommand(cmd *cobra.Command, ctx context.Context, cancel var runCmd = &cobra.Command{ Use: "run", - Short: "runs Netbird as service", + Short: "runs NetBird as service", RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithCancel(cmd.Context()) @@ -149,7 +149,7 @@ var runCmd = &cobra.Command{ var startCmd = &cobra.Command{ Use: "start", - Short: "starts Netbird service", + Short: "starts NetBird service", RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithCancel(cmd.Context()) s, err := setupServiceControlCommand(cmd, ctx, cancel) @@ -160,14 +160,14 @@ var startCmd = &cobra.Command{ if err := s.Start(); err != nil { return fmt.Errorf("start service: %w", err) } - cmd.Println("Netbird service has been started") + cmd.Println("NetBird service has been started") return nil }, } var stopCmd = &cobra.Command{ Use: "stop", - Short: "stops Netbird service", + Short: "stops NetBird service", RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithCancel(cmd.Context()) s, err := setupServiceControlCommand(cmd, ctx, cancel) @@ -178,14 +178,14 @@ var stopCmd = &cobra.Command{ if err := s.Stop(); err != nil { return fmt.Errorf("stop service: %w", err) } - cmd.Println("Netbird service has been stopped") + cmd.Println("NetBird service has been stopped") return nil }, } var restartCmd = &cobra.Command{ Use: "restart", - Short: "restarts Netbird service", + Short: "restarts NetBird service", RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithCancel(cmd.Context()) s, err := setupServiceControlCommand(cmd, ctx, cancel) @@ -196,14 +196,14 @@ var restartCmd = &cobra.Command{ if err := s.Restart(); err != nil { return fmt.Errorf("restart service: %w", err) } - cmd.Println("Netbird service has been restarted") + cmd.Println("NetBird service has been restarted") return nil }, } var svcStatusCmd = &cobra.Command{ Use: "status", - Short: "shows Netbird service status", + Short: "shows NetBird service status", RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithCancel(cmd.Context()) s, err := setupServiceControlCommand(cmd, ctx, cancel) @@ -228,7 +228,7 @@ var svcStatusCmd = &cobra.Command{ statusText = fmt.Sprintf("Unknown (%d)", status) } - cmd.Printf("Netbird service status: %s\n", statusText) + cmd.Printf("NetBird service status: %s\n", statusText) return nil }, } diff --git a/client/cmd/service_installer.go b/client/cmd/service_installer.go index be8a897dc..92f935d60 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) } @@ -95,7 +99,7 @@ func createServiceConfigForInstall() (*service.Config, error) { var installCmd = &cobra.Command{ Use: "install", - Short: "installs Netbird service", + Short: "installs NetBird service", RunE: func(cmd *cobra.Command, args []string) error { if err := setupServiceCommand(cmd); err != nil { return err @@ -118,14 +122,14 @@ var installCmd = &cobra.Command{ return fmt.Errorf("install service: %w", err) } - cmd.Println("Netbird service has been installed") + cmd.Println("NetBird service has been installed") return nil }, } var uninstallCmd = &cobra.Command{ Use: "uninstall", - Short: "uninstalls Netbird service from system", + Short: "uninstalls NetBird service from system", RunE: func(cmd *cobra.Command, args []string) error { if err := setupServiceCommand(cmd); err != nil { return err @@ -148,15 +152,15 @@ var uninstallCmd = &cobra.Command{ return fmt.Errorf("uninstall service: %w", err) } - cmd.Println("Netbird service has been uninstalled") + cmd.Println("NetBird service has been uninstalled") return nil }, } var reconfigureCmd = &cobra.Command{ Use: "reconfigure", - Short: "reconfigures Netbird service with new settings", - Long: `Reconfigures the Netbird service with new settings without manual uninstall/install. + Short: "reconfigures NetBird service with new settings", + Long: `Reconfigures the NetBird service with new settings without manual uninstall/install. This command will temporarily stop the service, update its configuration, and restart it if it was running.`, RunE: func(cmd *cobra.Command, args []string) error { if err := setupServiceCommand(cmd); err != nil { @@ -182,7 +186,7 @@ This command will temporarily stop the service, update its configuration, and re } if wasRunning { - cmd.Println("Stopping Netbird service...") + cmd.Println("Stopping NetBird service...") if err := s.Stop(); err != nil { cmd.Printf("Warning: failed to stop service: %v\n", err) } @@ -199,13 +203,13 @@ This command will temporarily stop the service, update its configuration, and re } if wasRunning { - cmd.Println("Starting Netbird service...") + cmd.Println("Starting NetBird service...") if err := s.Start(); err != nil { return fmt.Errorf("start service after reconfigure: %w", err) } - cmd.Println("Netbird service has been reconfigured and started") + cmd.Println("NetBird service has been reconfigured and started") } else { - cmd.Println("Netbird service has been reconfigured") + cmd.Println("NetBird service has been reconfigured") } return nil diff --git a/client/cmd/ssh.go b/client/cmd/ssh.go index 5a52b3795..035d06727 100644 --- a/client/cmd/ssh.go +++ b/client/cmd/ssh.go @@ -59,8 +59,8 @@ var sshCmd = &cobra.Command{ ctx := internal.CtxInitState(cmd.Context()) - pm := profilemanager.NewProfileManager() - activeProf, err := pm.GetActiveProfile() + sm := profilemanager.NewServiceManager(configPath) + activeProf, err := sm.GetActiveProfileState() if err != nil { return fmt.Errorf("get active profile: %v", err) } diff --git a/client/cmd/state.go b/client/cmd/state.go index 21a5508f4..b4612e601 100644 --- a/client/cmd/state.go +++ b/client/cmd/state.go @@ -17,7 +17,7 @@ var ( var stateCmd = &cobra.Command{ Use: "state", Short: "Manage daemon state", - Long: "Provides commands for managing and inspecting the Netbird daemon state.", + Long: "Provides commands for managing and inspecting the NetBird daemon state.", } var stateListCmd = &cobra.Command{ 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..8732a687d 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" ) @@ -53,15 +53,15 @@ var ( upCmd = &cobra.Command{ Use: "up", - Short: "install, login and start Netbird client", + Short: "install, login and start NetBird client", RunE: upFunc, } ) func init() { upCmd.PersistentFlags().BoolVarP(&foregroundMode, "foreground-mode", "F", false, "start service in foreground") - upCmd.PersistentFlags().StringVar(&interfaceName, interfaceNameFlag, iface.WgInterfaceDefault, "Wireguard interface name") - upCmd.PersistentFlags().Uint16Var(&wireguardPort, wireguardPortFlag, iface.DefaultWgPort, "Wireguard interface listening port") + upCmd.PersistentFlags().StringVar(&interfaceName, interfaceNameFlag, iface.WgInterfaceDefault, "WireGuard interface name") + upCmd.PersistentFlags().Uint16Var(&wireguardPort, wireguardPortFlag, iface.DefaultWgPort, "WireGuard interface listening port") upCmd.PersistentFlags().BoolVarP(&networkMonitor, networkMonitorFlag, "N", networkMonitor, `Manage network monitoring. Defaults to true on Windows and macOS, false on Linux and FreeBSD. `+ `E.g. --network-monitor=false to disable or --network-monitor=true to enable.`, @@ -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/cmd/version.go b/client/cmd/version.go index 99f2da698..03541b85e 100644 --- a/client/cmd/version.go +++ b/client/cmd/version.go @@ -9,7 +9,7 @@ import ( var ( versionCmd = &cobra.Command{ Use: "version", - Short: "prints Netbird version", + Short: "prints NetBird version", Run: func(cmd *cobra.Command, args []string) { cmd.SetOut(cmd.OutOrStdout()) cmd.Println(version.NetbirdVersion()) 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/installer.nsis b/client/installer.nsis index fabd727fc..96d60a785 100644 --- a/client/installer.nsis +++ b/client/installer.nsis @@ -3,7 +3,7 @@ !define WEB_SITE "Netbird.io" !define VERSION $%APPVER% !define COPYRIGHT "Netbird Authors, 2022" -!define DESCRIPTION "A WireGuard®-based mesh network that connects your devices into a single private network" +!define DESCRIPTION "Connect your devices into a secure WireGuard-based overlay network with SSO, MFA, and granular access controls." !define INSTALLER_NAME "netbird-installer.exe" !define MAIN_APP_EXE "Netbird" !define ICON "ui\\assets\\netbird.ico" @@ -59,9 +59,15 @@ ShowInstDetails Show !define MUI_UNICON "${ICON}" !define MUI_WELCOMEFINISHPAGE_BITMAP "${BANNER}" !define MUI_UNWELCOMEFINISHPAGE_BITMAP "${BANNER}" -!define MUI_FINISHPAGE_RUN -!define MUI_FINISHPAGE_RUN_TEXT "Start ${UI_APP_NAME}" -!define MUI_FINISHPAGE_RUN_FUNCTION "LaunchLink" +!ifndef ARCH + !define ARCH "amd64" +!endif + +!if ${ARCH} == "amd64" + !define MUI_FINISHPAGE_RUN + !define MUI_FINISHPAGE_RUN_TEXT "Start ${UI_APP_NAME}" + !define MUI_FINISHPAGE_RUN_FUNCTION "LaunchLink" +!endif ###################################################################### !define MUI_ABORTWARNING @@ -213,7 +219,15 @@ Section -MainProgram ${INSTALL_TYPE} # SetOverwrite ifnewer SetOutPath "$INSTDIR" - File /r "..\\dist\\netbird_windows_amd64\\" + !ifndef ARCH + !define ARCH "amd64" + !endif + + !if ${ARCH} == "arm64" + File /r "..\\dist\\netbird_windows_arm64\\" + !else + File /r "..\\dist\\netbird_windows_amd64\\" + !endif SectionEnd ###################################################################### @@ -292,7 +306,9 @@ DetailPrint "Deleting application files..." Delete "$INSTDIR\${UI_APP_EXE}" Delete "$INSTDIR\${MAIN_APP_EXE}" Delete "$INSTDIR\wintun.dll" +!if ${ARCH} == "amd64" Delete "$INSTDIR\opengl32.dll" +!endif DetailPrint "Removing application directory..." RmDir /r "$INSTDIR" @@ -314,8 +330,10 @@ DetailPrint "Uninstallation finished." SectionEnd +!if ${ARCH} == "amd64" Function LaunchLink SetShellVarContext all SetOutPath $INSTDIR ShellExecAsUser::ShellExecAsUser "" "$DESKTOP\${APP_NAME}.lnk" FunctionEnd +!endif 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 ca3c280e3..26694ba48 100644 --- a/client/internal/connect.go +++ b/client/internal/connect.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net" + "net/netip" "runtime" "runtime/debug" "strings" @@ -26,11 +27,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 +44,7 @@ type ConnectClient struct { engine *Engine engineMutex sync.Mutex - persistNetworkMap bool + persistSyncResponse bool } func NewConnectClient( @@ -70,7 +71,7 @@ func (c *ConnectClient) RunOnAndroid( tunAdapter device.TunAdapter, iFaceDiscover stdnet.ExternalIFaceDiscover, networkChangeListener listener.NetworkChangeListener, - dnsAddresses []string, + dnsAddresses []netip.AddrPort, dnsReadyListener dns.ReadyListener, ) error { // in case of non Android os these variables will be nil @@ -270,7 +271,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(loginResp.GetNetbirdConfig(), c.config.ManagementURL); err != nil { @@ -350,23 +351,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 @@ -399,18 +400,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/config/domains.go b/client/internal/dns/config/domains.go index 380046af1..cb651f1e5 100644 --- a/client/internal/dns/config/domains.go +++ b/client/internal/dns/config/domains.go @@ -10,8 +10,8 @@ import ( log "github.com/sirupsen/logrus" - "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 ( diff --git a/client/internal/dns/file_parser_unix.go b/client/internal/dns/file_parser_unix.go index 6e123c94e..8dacb4e51 100644 --- a/client/internal/dns/file_parser_unix.go +++ b/client/internal/dns/file_parser_unix.go @@ -16,7 +16,7 @@ const ( ) type resolvConf struct { - nameServers []string + nameServers []netip.Addr searchDomains []string others []string } @@ -36,7 +36,7 @@ func parseBackupResolvConf() (*resolvConf, error) { func parseResolvConfFile(resolvConfFile string) (*resolvConf, error) { rconf := &resolvConf{ searchDomains: make([]string, 0), - nameServers: make([]string, 0), + nameServers: make([]netip.Addr, 0), others: make([]string, 0), } @@ -94,7 +94,11 @@ func parseResolvConfFile(resolvConfFile string) (*resolvConf, error) { if len(splitLines) != 2 { continue } - rconf.nameServers = append(rconf.nameServers, splitLines[1]) + if addr, err := netip.ParseAddr(splitLines[1]); err == nil { + rconf.nameServers = append(rconf.nameServers, addr.Unmap()) + } else { + log.Warnf("invalid nameserver address in resolv.conf: %s, skipping", splitLines[1]) + } continue } @@ -104,31 +108,3 @@ func parseResolvConfFile(resolvConfFile string) (*resolvConf, error) { } return rconf, nil } - -// removeFirstNbNameserver removes the given nameserver from the given file if it is in the first position -// and writes the file back to the original location -func removeFirstNbNameserver(filename string, nameserverIP netip.Addr) error { - resolvConf, err := parseResolvConfFile(filename) - if err != nil { - return fmt.Errorf("parse backup resolv.conf: %w", err) - } - content, err := os.ReadFile(filename) - if err != nil { - return fmt.Errorf("read %s: %w", filename, err) - } - - if len(resolvConf.nameServers) > 1 && resolvConf.nameServers[0] == nameserverIP.String() { - newContent := strings.Replace(string(content), fmt.Sprintf("nameserver %s\n", nameserverIP), "", 1) - - stat, err := os.Stat(filename) - if err != nil { - return fmt.Errorf("stat %s: %w", filename, err) - } - if err := os.WriteFile(filename, []byte(newContent), stat.Mode()); err != nil { - return fmt.Errorf("write %s: %w", filename, err) - } - - } - - return nil -} diff --git a/client/internal/dns/file_parser_unix_test.go b/client/internal/dns/file_parser_unix_test.go index 228a708f1..17e407d80 100644 --- a/client/internal/dns/file_parser_unix_test.go +++ b/client/internal/dns/file_parser_unix_test.go @@ -3,13 +3,9 @@ package dns import ( - "net/netip" "os" "path/filepath" "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func Test_parseResolvConf(t *testing.T) { @@ -99,9 +95,13 @@ options debug t.Errorf("invalid parse result for search domains, expected: %v, got: %v", testCase.expectedSearch, cfg.searchDomains) } - ok = compareLists(cfg.nameServers, testCase.expectedNS) + nsStrings := make([]string, len(cfg.nameServers)) + for i, ns := range cfg.nameServers { + nsStrings[i] = ns.String() + } + ok = compareLists(nsStrings, testCase.expectedNS) if !ok { - t.Errorf("invalid parse result for ns domains, expected: %v, got: %v", testCase.expectedNS, cfg.nameServers) + t.Errorf("invalid parse result for ns domains, expected: %v, got: %v", testCase.expectedNS, nsStrings) } ok = compareLists(cfg.others, testCase.expectedOther) @@ -176,87 +176,3 @@ nameserver 192.168.0.1 t.Errorf("unexpected resolv.conf content: %v", cfg) } } - -func TestRemoveFirstNbNameserver(t *testing.T) { - testCases := []struct { - name string - content string - ipToRemove string - expected string - }{ - { - name: "Unrelated nameservers with comments and options", - content: `# This is a comment -options rotate -nameserver 1.1.1.1 -# Another comment -nameserver 8.8.4.4 -search example.com`, - ipToRemove: "9.9.9.9", - expected: `# This is a comment -options rotate -nameserver 1.1.1.1 -# Another comment -nameserver 8.8.4.4 -search example.com`, - }, - { - name: "First nameserver matches", - content: `search example.com -nameserver 9.9.9.9 -# oof, a comment -nameserver 8.8.4.4 -options attempts:5`, - ipToRemove: "9.9.9.9", - expected: `search example.com -# oof, a comment -nameserver 8.8.4.4 -options attempts:5`, - }, - { - name: "Target IP not the first nameserver", - // nolint:dupword - content: `# Comment about the first nameserver -nameserver 8.8.4.4 -# Comment before our target -nameserver 9.9.9.9 -options timeout:2`, - ipToRemove: "9.9.9.9", - // nolint:dupword - expected: `# Comment about the first nameserver -nameserver 8.8.4.4 -# Comment before our target -nameserver 9.9.9.9 -options timeout:2`, - }, - { - name: "Only nameserver matches", - content: `options debug -nameserver 9.9.9.9 -search localdomain`, - ipToRemove: "9.9.9.9", - expected: `options debug -nameserver 9.9.9.9 -search localdomain`, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - tempDir := t.TempDir() - tempFile := filepath.Join(tempDir, "resolv.conf") - err := os.WriteFile(tempFile, []byte(tc.content), 0644) - assert.NoError(t, err) - - ip, err := netip.ParseAddr(tc.ipToRemove) - require.NoError(t, err, "Failed to parse IP address") - err = removeFirstNbNameserver(tempFile, ip) - assert.NoError(t, err) - - content, err := os.ReadFile(tempFile) - assert.NoError(t, err) - - assert.Equal(t, tc.expected, string(content), "The resulting content should match the expected output.") - }) - } -} diff --git a/client/internal/dns/file_repair_unix.go b/client/internal/dns/file_repair_unix.go index 75af411df..0846dbf38 100644 --- a/client/internal/dns/file_repair_unix.go +++ b/client/internal/dns/file_repair_unix.go @@ -146,7 +146,7 @@ func isNbParamsMissing(nbSearchDomains []string, nbNameserverIP netip.Addr, rCon return true } - if rConf.nameServers[0] != nbNameserverIP.String() { + if rConf.nameServers[0] != nbNameserverIP { return true } diff --git a/client/internal/dns/file_unix.go b/client/internal/dns/file_unix.go index 423989f72..45e621443 100644 --- a/client/internal/dns/file_unix.go +++ b/client/internal/dns/file_unix.go @@ -29,7 +29,7 @@ type fileConfigurator struct { repair *repair originalPerms os.FileMode nbNameserverIP netip.Addr - originalNameservers []string + originalNameservers []netip.Addr } func newFileConfigurator() (*fileConfigurator, error) { @@ -70,7 +70,7 @@ func (f *fileConfigurator) applyDNSConfig(config HostDNSConfig, stateManager *st } // getOriginalNameservers returns the nameservers that were found in the original resolv.conf -func (f *fileConfigurator) getOriginalNameservers() []string { +func (f *fileConfigurator) getOriginalNameservers() []netip.Addr { return f.originalNameservers } @@ -128,20 +128,14 @@ func (f *fileConfigurator) backup() error { } func (f *fileConfigurator) restore() error { - err := removeFirstNbNameserver(fileDefaultResolvConfBackupLocation, f.nbNameserverIP) - if err != nil { - log.Errorf("Failed to remove netbird nameserver from %s on backup restore: %s", fileDefaultResolvConfBackupLocation, err) - } - - err = copyFile(fileDefaultResolvConfBackupLocation, defaultResolvConfPath) - if err != nil { + if err := copyFile(fileDefaultResolvConfBackupLocation, defaultResolvConfPath); err != nil { return fmt.Errorf("restoring %s from %s: %w", defaultResolvConfPath, fileDefaultResolvConfBackupLocation, err) } return os.RemoveAll(fileDefaultResolvConfBackupLocation) } -func (f *fileConfigurator) restoreUncleanShutdownDNS(storedDNSAddress *netip.Addr) error { +func (f *fileConfigurator) restoreUncleanShutdownDNS(storedDNSAddress netip.Addr) error { resolvConf, err := parseDefaultResolvConf() if err != nil { return fmt.Errorf("parse current resolv.conf: %w", err) @@ -152,16 +146,9 @@ func (f *fileConfigurator) restoreUncleanShutdownDNS(storedDNSAddress *netip.Add return restoreResolvConfFile() } - currentDNSAddress, err := netip.ParseAddr(resolvConf.nameServers[0]) - // not a valid first nameserver -> restore - if err != nil { - log.Errorf("restoring unclean shutdown: parse dns address %s failed: %s", resolvConf.nameServers[0], err) - return restoreResolvConfFile() - } - // current address is still netbird's non-available dns address -> restore - // comparing parsed addresses only, to remove ambiguity - if currentDNSAddress.String() == storedDNSAddress.String() { + currentDNSAddress := resolvConf.nameServers[0] + if currentDNSAddress == storedDNSAddress { return restoreResolvConfFile() } diff --git a/client/internal/dns/host_darwin.go b/client/internal/dns/host_darwin.go index 820cf9029..852dfef48 100644 --- a/client/internal/dns/host_darwin.go +++ b/client/internal/dns/host_darwin.go @@ -239,7 +239,7 @@ func (s *systemConfigurator) getSystemDNSSettings() (SystemDNSSettings, error) { } else if inServerAddressesArray { address := strings.Split(line, " : ")[1] if ip, err := netip.ParseAddr(address); err == nil && ip.Is4() { - dnsSettings.ServerIP = ip + dnsSettings.ServerIP = ip.Unmap() inServerAddressesArray = false // Stop reading after finding the first IPv4 address } } @@ -250,7 +250,7 @@ func (s *systemConfigurator) getSystemDNSSettings() (SystemDNSSettings, error) { } // default to 53 port - dnsSettings.ServerPort = defaultPort + dnsSettings.ServerPort = DefaultPort return dnsSettings, nil } diff --git a/client/internal/dns/host_unix.go b/client/internal/dns/host_unix.go index 297d50822..422fed4e5 100644 --- a/client/internal/dns/host_unix.go +++ b/client/internal/dns/host_unix.go @@ -42,7 +42,7 @@ func (t osManagerType) String() string { type restoreHostManager interface { hostManager - restoreUncleanShutdownDNS(*netip.Addr) error + restoreUncleanShutdownDNS(netip.Addr) error } func newHostManager(wgInterface string) (hostManager, error) { @@ -130,8 +130,9 @@ func checkStub() bool { return true } + systemdResolvedAddr := netip.AddrFrom4([4]byte{127, 0, 0, 53}) // 127.0.0.53 for _, ns := range rConf.nameServers { - if ns == "127.0.0.53" { + if ns == systemdResolvedAddr { return true } } diff --git a/client/internal/dns/host_windows.go b/client/internal/dns/host_windows.go index 648a58207..fdc2c3063 100644 --- a/client/internal/dns/host_windows.go +++ b/client/internal/dns/host_windows.go @@ -64,9 +64,10 @@ const ( ) type registryConfigurator struct { - guid string - routingAll bool - gpo bool + guid string + routingAll bool + gpo bool + nrptEntryCount int } func newHostManager(wgInterface WGIface) (*registryConfigurator, error) { @@ -177,7 +178,11 @@ func (r *registryConfigurator) applyDNSConfig(config HostDNSConfig, stateManager log.Infof("removed %s as main DNS forwarder for this peer", config.ServerIP) } - if err := stateManager.UpdateState(&ShutdownState{Guid: r.guid, GPO: r.gpo}); err != nil { + if err := stateManager.UpdateState(&ShutdownState{ + Guid: r.guid, + GPO: r.gpo, + NRPTEntryCount: r.nrptEntryCount, + }); err != nil { log.Errorf("failed to update shutdown state: %s", err) } @@ -193,13 +198,24 @@ func (r *registryConfigurator) applyDNSConfig(config HostDNSConfig, stateManager } if len(matchDomains) != 0 { - if err := r.addDNSMatchPolicy(matchDomains, config.ServerIP); err != nil { + count, err := r.addDNSMatchPolicy(matchDomains, config.ServerIP) + if err != nil { return fmt.Errorf("add dns match policy: %w", err) } + r.nrptEntryCount = count } else { if err := r.removeDNSMatchPolicies(); err != nil { return fmt.Errorf("remove dns match policies: %w", err) } + r.nrptEntryCount = 0 + } + + if err := stateManager.UpdateState(&ShutdownState{ + Guid: r.guid, + GPO: r.gpo, + NRPTEntryCount: r.nrptEntryCount, + }); err != nil { + log.Errorf("failed to update shutdown state: %s", err) } if err := r.updateSearchDomains(searchDomains); err != nil { @@ -216,32 +232,38 @@ func (r *registryConfigurator) addDNSSetupForAll(ip netip.Addr) error { return fmt.Errorf("adding dns setup for all failed: %w", err) } r.routingAll = true - log.Infof("configured %s:53 as main DNS forwarder for this peer", ip) + log.Infof("configured %s:%d as main DNS forwarder for this peer", ip, DefaultPort) return nil } -func (r *registryConfigurator) addDNSMatchPolicy(domains []string, ip netip.Addr) error { +func (r *registryConfigurator) addDNSMatchPolicy(domains []string, ip netip.Addr) (int, error) { // if the gpo key is present, we need to put our DNS settings there, otherwise our config might be ignored // see https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-gpnrpt/8cc31cb9-20cb-4140-9e85-3e08703b4745 - if r.gpo { - if err := r.configureDNSPolicy(gpoDnsPolicyConfigMatchPath, domains, ip); err != nil { - return fmt.Errorf("configure GPO DNS policy: %w", err) + for i, domain := range domains { + policyPath := fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i) + if r.gpo { + policyPath = fmt.Sprintf("%s-%d", gpoDnsPolicyConfigMatchPath, i) } + singleDomain := []string{domain} + + if err := r.configureDNSPolicy(policyPath, singleDomain, ip); err != nil { + return i, fmt.Errorf("configure DNS policy for domain %s: %w", domain, err) + } + + log.Debugf("added NRPT entry for domain: %s", domain) + } + + if r.gpo { if err := refreshGroupPolicy(); err != nil { log.Warnf("failed to refresh group policy: %v", err) } - } else { - if err := r.configureDNSPolicy(dnsPolicyConfigMatchPath, domains, ip); err != nil { - return fmt.Errorf("configure local DNS policy: %w", err) - } } - log.Infof("added %d match domains. Domain list: %s", len(domains), domains) - return nil + log.Infof("added %d separate NRPT entries. Domain list: %s", len(domains), domains) + return len(domains), nil } -// configureDNSPolicy handles the actual configuration of a DNS policy at the specified path func (r *registryConfigurator) configureDNSPolicy(policyPath string, domains []string, ip netip.Addr) error { if err := removeRegistryKeyFromDNSPolicyConfig(policyPath); err != nil { return fmt.Errorf("remove existing dns policy: %w", err) @@ -374,12 +396,25 @@ func (r *registryConfigurator) restoreHostDNS() error { func (r *registryConfigurator) removeDNSMatchPolicies() error { var merr *multierror.Error + + // Try to remove the base entries (for backward compatibility) if err := removeRegistryKeyFromDNSPolicyConfig(dnsPolicyConfigMatchPath); err != nil { - merr = multierror.Append(merr, fmt.Errorf("remove local registry key: %w", err)) + merr = multierror.Append(merr, fmt.Errorf("remove local base entry: %w", err)) + } + if err := removeRegistryKeyFromDNSPolicyConfig(gpoDnsPolicyConfigMatchPath); err != nil { + merr = multierror.Append(merr, fmt.Errorf("remove GPO base entry: %w", err)) } - if err := removeRegistryKeyFromDNSPolicyConfig(gpoDnsPolicyConfigMatchPath); err != nil { - merr = multierror.Append(merr, fmt.Errorf("remove GPO registry key: %w", err)) + for i := 0; i < r.nrptEntryCount; i++ { + localPath := fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i) + gpoPath := fmt.Sprintf("%s-%d", gpoDnsPolicyConfigMatchPath, i) + + if err := removeRegistryKeyFromDNSPolicyConfig(localPath); err != nil { + merr = multierror.Append(merr, fmt.Errorf("remove local entry %d: %w", i, err)) + } + if err := removeRegistryKeyFromDNSPolicyConfig(gpoPath); err != nil { + merr = multierror.Append(merr, fmt.Errorf("remove GPO entry %d: %w", i, err)) + } } if err := refreshGroupPolicy(); err != nil { diff --git a/client/internal/dns/hosts_dns_holder.go b/client/internal/dns/hosts_dns_holder.go index 2601af9c8..980d917a7 100644 --- a/client/internal/dns/hosts_dns_holder.go +++ b/client/internal/dns/hosts_dns_holder.go @@ -1,38 +1,31 @@ package dns import ( - "fmt" "net/netip" "sync" - - log "github.com/sirupsen/logrus" ) type hostsDNSHolder struct { - unprotectedDNSList map[string]struct{} + unprotectedDNSList map[netip.AddrPort]struct{} mutex sync.RWMutex } func newHostsDNSHolder() *hostsDNSHolder { return &hostsDNSHolder{ - unprotectedDNSList: make(map[string]struct{}), + unprotectedDNSList: make(map[netip.AddrPort]struct{}), } } -func (h *hostsDNSHolder) set(list []string) { +func (h *hostsDNSHolder) set(list []netip.AddrPort) { h.mutex.Lock() - h.unprotectedDNSList = make(map[string]struct{}) - for _, dns := range list { - dnsAddr, err := h.normalizeAddress(dns) - if err != nil { - continue - } - h.unprotectedDNSList[dnsAddr] = struct{}{} + h.unprotectedDNSList = make(map[netip.AddrPort]struct{}) + for _, addrPort := range list { + h.unprotectedDNSList[addrPort] = struct{}{} } h.mutex.Unlock() } -func (h *hostsDNSHolder) get() map[string]struct{} { +func (h *hostsDNSHolder) get() map[netip.AddrPort]struct{} { h.mutex.RLock() l := h.unprotectedDNSList h.mutex.RUnlock() @@ -40,24 +33,10 @@ func (h *hostsDNSHolder) get() map[string]struct{} { } //nolint:unused -func (h *hostsDNSHolder) isContain(upstream string) bool { +func (h *hostsDNSHolder) contains(upstream netip.AddrPort) bool { h.mutex.RLock() defer h.mutex.RUnlock() _, ok := h.unprotectedDNSList[upstream] return ok } - -func (h *hostsDNSHolder) normalizeAddress(addr string) (string, error) { - a, err := netip.ParseAddr(addr) - if err != nil { - log.Errorf("invalid upstream IP address: %s, error: %s", addr, err) - return "", err - } - - if a.Is4() { - return fmt.Sprintf("%s:53", addr), nil - } else { - return fmt.Sprintf("[%s]:53", addr), nil - } -} diff --git a/client/internal/dns/local/local.go b/client/internal/dns/local/local.go index c714331b8..bac7875ec 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/mgmt/mgmt.go b/client/internal/dns/mgmt/mgmt.go index 6a310a790..290395473 100644 --- a/client/internal/dns/mgmt/mgmt.go +++ b/client/internal/dns/mgmt/mgmt.go @@ -13,7 +13,7 @@ import ( log "github.com/sirupsen/logrus" dnsconfig "github.com/netbirdio/netbird/client/internal/dns/config" - "github.com/netbirdio/netbird/management/domain" + "github.com/netbirdio/netbird/shared/management/domain" ) const dnsTimeout = 5 * time.Second diff --git a/client/internal/dns/mock_server.go b/client/internal/dns/mock_server.go index 4ceb1c53d..0f89b9016 100644 --- a/client/internal/dns/mock_server.go +++ b/client/internal/dns/mock_server.go @@ -9,7 +9,7 @@ import ( dnsconfig "github.com/netbirdio/netbird/client/internal/dns/config" 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 @@ -53,7 +53,7 @@ func (m *MockServer) DnsIP() netip.Addr { return netip.MustParseAddr("100.10.254.255") } -func (m *MockServer) OnUpdatedHostDNSServer(strings []string) { +func (m *MockServer) OnUpdatedHostDNSServer(addrs []netip.AddrPort) { // TODO implement me panic("implement me") } diff --git a/client/internal/dns/network_manager_unix.go b/client/internal/dns/network_manager_unix.go index 5459bc2d7..e4ccc8cbd 100644 --- a/client/internal/dns/network_manager_unix.go +++ b/client/internal/dns/network_manager_unix.go @@ -245,7 +245,7 @@ func (n *networkManagerDbusConfigurator) deleteConnectionSettings() error { return nil } -func (n *networkManagerDbusConfigurator) restoreUncleanShutdownDNS(*netip.Addr) error { +func (n *networkManagerDbusConfigurator) restoreUncleanShutdownDNS(netip.Addr) error { if err := n.restoreHostDNS(); err != nil { return fmt.Errorf("restoring dns via network-manager: %w", err) } diff --git a/client/internal/dns/resolvconf_unix.go b/client/internal/dns/resolvconf_unix.go index 6080c1d2c..8cdea562b 100644 --- a/client/internal/dns/resolvconf_unix.go +++ b/client/internal/dns/resolvconf_unix.go @@ -40,7 +40,7 @@ type resolvconf struct { implType resolvconfType originalSearchDomains []string - originalNameServers []string + originalNameServers []netip.Addr othersConfigs []string } @@ -110,7 +110,7 @@ func (r *resolvconf) applyDNSConfig(config HostDNSConfig, stateManager *stateman return nil } -func (r *resolvconf) getOriginalNameservers() []string { +func (r *resolvconf) getOriginalNameservers() []netip.Addr { return r.originalNameServers } @@ -158,7 +158,7 @@ func (r *resolvconf) applyConfig(content bytes.Buffer) error { return nil } -func (r *resolvconf) restoreUncleanShutdownDNS(*netip.Addr) error { +func (r *resolvconf) restoreUncleanShutdownDNS(netip.Addr) error { if err := r.restoreHostDNS(); err != nil { return fmt.Errorf("restoring dns for interface %s: %w", r.ifaceName, err) } diff --git a/client/internal/dns/server.go b/client/internal/dns/server.go index 9d3ca4235..8cb886203 100644 --- a/client/internal/dns/server.go +++ b/client/internal/dns/server.go @@ -24,7 +24,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 @@ -45,7 +45,7 @@ type Server interface { Stop() DnsIP() netip.Addr UpdateDNSServer(serial uint64, update nbdns.Config) error - OnUpdatedHostDNSServer(strings []string) + OnUpdatedHostDNSServer(addrs []netip.AddrPort) SearchDomains() []string ProbeAvailability() UpdateServerConfig(domains dnsconfig.ServerDomains) error @@ -60,7 +60,7 @@ type nsGroupsByDomain struct { // hostManagerWithOriginalNS extends the basic hostManager interface type hostManagerWithOriginalNS interface { hostManager - getOriginalNameservers() []string + getOriginalNameservers() []netip.Addr } // DefaultServer dns server object @@ -146,7 +146,7 @@ func NewDefaultServer(ctx context.Context, config DefaultServerConfig) (*Default func NewDefaultServerPermanentUpstream( ctx context.Context, wgInterface WGIface, - hostsDnsList []string, + hostsDnsList []netip.AddrPort, config nbdns.Config, listener listener.NetworkChangeListener, statusRecorder *peer.Status, @@ -154,6 +154,7 @@ func NewDefaultServerPermanentUpstream( ) *DefaultServer { log.Debugf("host dns address list is: %v", hostsDnsList) ds := newDefaultServer(ctx, wgInterface, NewServiceViaMemory(wgInterface), statusRecorder, nil, disableSys) + ds.hostsDNSHolder.set(hostsDnsList) ds.permanent = true ds.addHostRootZone() @@ -354,7 +355,7 @@ func (s *DefaultServer) disableDNS() error { // OnUpdatedHostDNSServer update the DNS servers addresses for root zones // It will be applied if the mgm server do not enforce DNS settings for root zone -func (s *DefaultServer) OnUpdatedHostDNSServer(hostsDnsList []string) { +func (s *DefaultServer) OnUpdatedHostDNSServer(hostsDnsList []netip.AddrPort) { s.hostsDNSHolder.set(hostsDnsList) // Check if there's any root handler @@ -498,7 +499,7 @@ func (s *DefaultServer) applyConfiguration(update nbdns.Config) error { s.currentConfig = dnsConfigToHostDNSConfig(update, s.service.RuntimeIP(), s.service.RuntimePort()) - if s.service.RuntimePort() != defaultPort && !s.hostManager.supportCustomPort() { + if s.service.RuntimePort() != DefaultPort && !s.hostManager.supportCustomPort() { log.Warnf("the DNS manager of this peer doesn't support custom port. Disabling primary DNS setup. " + "Learn more at: https://docs.netbird.io/how-to/manage-dns-in-your-network#local-resolver") s.currentConfig.RouteAll = false @@ -618,14 +619,13 @@ func (s *DefaultServer) registerFallback(config HostDNSConfig) { } for _, ns := range originalNameservers { - if ns == config.ServerIP.String() { + if ns == config.ServerIP { log.Debugf("skipping original nameserver %s as it is the same as the server IP %s", ns, config.ServerIP) continue } - ns = formatAddr(ns, defaultPort) - - handler.upstreamServers = append(handler.upstreamServers, ns) + addrPort := netip.AddrPortFrom(ns, DefaultPort) + handler.upstreamServers = append(handler.upstreamServers, addrPort) } handler.deactivate = func(error) { /* always active */ } handler.reactivate = func() { /* always active */ } @@ -732,7 +732,13 @@ func (s *DefaultServer) createHandlersForDomainGroup(domainGroup nsGroupsByDomai ns.IP.String(), ns.NSType.String(), nbdns.UDPNameServerType.String()) continue } - handler.upstreamServers = append(handler.upstreamServers, getNSHostPort(ns)) + + if ns.IP == s.service.RuntimeIP() { + log.Warnf("skipping nameserver %s as it matches our DNS server IP, preventing potential loop", ns.IP) + continue + } + + handler.upstreamServers = append(handler.upstreamServers, ns.AddrPort()) } if len(handler.upstreamServers) == 0 { @@ -807,18 +813,6 @@ func (s *DefaultServer) updateMux(muxUpdates []handlerWrapper) { s.dnsMuxMap = muxUpdateMap } -func getNSHostPort(ns nbdns.NameServer) string { - return formatAddr(ns.IP.String(), ns.Port) -} - -// formatAddr formats a nameserver address with port, handling IPv6 addresses properly -func formatAddr(address string, port int) string { - if ip, err := netip.ParseAddr(address); err == nil && ip.Is6() { - return fmt.Sprintf("[%s]:%d", address, port) - } - return fmt.Sprintf("%s:%d", address, port) -} - // upstreamCallbacks returns two functions, the first one is used to deactivate // the upstream resolver from the configuration, the second one is used to // reactivate it. Not allowed to call reactivate before deactivate. @@ -916,10 +910,7 @@ func (s *DefaultServer) addHostRootZone() { return } - handler.upstreamServers = make([]string, 0) - for k := range hostDNSServers { - handler.upstreamServers = append(handler.upstreamServers, k) - } + handler.upstreamServers = maps.Keys(hostDNSServers) handler.deactivate = func(error) {} handler.reactivate = func() {} @@ -930,9 +921,9 @@ func (s *DefaultServer) updateNSGroupStates(groups []*nbdns.NameServerGroup) { var states []peer.NSGroupState for _, group := range groups { - var servers []string + var servers []netip.AddrPort for _, ns := range group.NameServers { - servers = append(servers, fmt.Sprintf("%s:%d", ns.IP, ns.Port)) + servers = append(servers, ns.AddrPort()) } state := peer.NSGroupState{ @@ -964,7 +955,7 @@ func (s *DefaultServer) updateNSState(nsGroup *nbdns.NameServerGroup, err error, func generateGroupKey(nsGroup *nbdns.NameServerGroup) string { var servers []string for _, ns := range nsGroup.NameServers { - servers = append(servers, fmt.Sprintf("%s:%d", ns.IP, ns.Port)) + servers = append(servers, ns.AddrPort().String()) } return fmt.Sprintf("%v_%v", servers, nsGroup.Domains) } diff --git a/client/internal/dns/server_test.go b/client/internal/dns/server_test.go index 85490d15f..11575d500 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() @@ -97,9 +97,9 @@ func init() { } func generateDummyHandler(domain string, servers []nbdns.NameServer) *upstreamResolverBase { - var srvs []string + var srvs []netip.AddrPort for _, srv := range servers { - srvs = append(srvs, getNSHostPort(srv)) + srvs = append(srvs, srv.AddrPort()) } return &upstreamResolverBase{ domain: domain, @@ -723,7 +723,7 @@ func TestDNSPermanent_updateHostDNS_emptyUpstream(t *testing.T) { } defer wgIFace.Close() - var dnsList []string + var dnsList []netip.AddrPort dnsConfig := nbdns.Config{} dnsServer := NewDefaultServerPermanentUpstream(context.Background(), wgIFace, dnsList, dnsConfig, nil, peer.NewRecorder("mgm"), false) err = dnsServer.Initialize() @@ -733,7 +733,8 @@ func TestDNSPermanent_updateHostDNS_emptyUpstream(t *testing.T) { } defer dnsServer.Stop() - dnsServer.OnUpdatedHostDNSServer([]string{"8.8.8.8"}) + addrPort := netip.MustParseAddrPort("8.8.8.8:53") + dnsServer.OnUpdatedHostDNSServer([]netip.AddrPort{addrPort}) resolver := newDnsResolver(dnsServer.service.RuntimeIP(), dnsServer.service.RuntimePort()) _, err = resolver.LookupHost(context.Background(), "netbird.io") @@ -749,7 +750,8 @@ func TestDNSPermanent_updateUpstream(t *testing.T) { } defer wgIFace.Close() dnsConfig := nbdns.Config{} - dnsServer := NewDefaultServerPermanentUpstream(context.Background(), wgIFace, []string{"8.8.8.8"}, dnsConfig, nil, peer.NewRecorder("mgm"), false) + addrPort := netip.MustParseAddrPort("8.8.8.8:53") + dnsServer := NewDefaultServerPermanentUpstream(context.Background(), wgIFace, []netip.AddrPort{addrPort}, dnsConfig, nil, peer.NewRecorder("mgm"), false) err = dnsServer.Initialize() if err != nil { t.Errorf("failed to initialize DNS server: %v", err) @@ -841,7 +843,8 @@ func TestDNSPermanent_matchOnly(t *testing.T) { } defer wgIFace.Close() dnsConfig := nbdns.Config{} - dnsServer := NewDefaultServerPermanentUpstream(context.Background(), wgIFace, []string{"8.8.8.8"}, dnsConfig, nil, peer.NewRecorder("mgm"), false) + addrPort := netip.MustParseAddrPort("8.8.8.8:53") + dnsServer := NewDefaultServerPermanentUpstream(context.Background(), wgIFace, []netip.AddrPort{addrPort}, dnsConfig, nil, peer.NewRecorder("mgm"), false) err = dnsServer.Initialize() if err != nil { t.Errorf("failed to initialize DNS server: %v", err) @@ -2072,55 +2075,123 @@ func TestLocalResolverPriorityConstants(t *testing.T) { assert.Equal(t, "local.example.com", localMuxUpdates[0].domain) } -func TestFormatAddr(t *testing.T) { +func TestDNSLoopPrevention(t *testing.T) { + wgInterface := &mocWGIface{} + service := NewServiceViaMemory(wgInterface) + dnsServerIP := service.RuntimeIP() + + server := &DefaultServer{ + ctx: context.Background(), + wgInterface: wgInterface, + service: service, + localResolver: local.NewResolver(), + handlerChain: NewHandlerChain(), + hostManager: &noopHostConfigurator{}, + dnsMuxMap: make(registeredHandlerMap), + } + tests := []struct { - name string - address string - port int - expected string + name string + nsGroups []*nbdns.NameServerGroup + expectedHandlers int + expectedServers []netip.Addr + shouldFilterOwnIP bool }{ { - name: "IPv4 address", - address: "8.8.8.8", - port: 53, - expected: "8.8.8.8:53", + name: "FilterOwnDNSServerIP", + nsGroups: []*nbdns.NameServerGroup{ + { + Primary: true, + NameServers: []nbdns.NameServer{ + {IP: netip.MustParseAddr("8.8.8.8"), NSType: nbdns.UDPNameServerType, Port: 53}, + {IP: dnsServerIP, NSType: nbdns.UDPNameServerType, Port: 53}, + {IP: netip.MustParseAddr("1.1.1.1"), NSType: nbdns.UDPNameServerType, Port: 53}, + }, + Domains: []string{}, + }, + }, + expectedHandlers: 1, + expectedServers: []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("1.1.1.1")}, + shouldFilterOwnIP: true, }, { - name: "IPv4 address with custom port", - address: "1.1.1.1", - port: 5353, - expected: "1.1.1.1:5353", + name: "AllServersFiltered", + nsGroups: []*nbdns.NameServerGroup{ + { + Primary: false, + NameServers: []nbdns.NameServer{ + {IP: dnsServerIP, NSType: nbdns.UDPNameServerType, Port: 53}, + }, + Domains: []string{"example.com"}, + }, + }, + expectedHandlers: 0, + expectedServers: []netip.Addr{}, + shouldFilterOwnIP: true, }, { - name: "IPv6 address", - address: "fd78:94bf:7df8::1", - port: 53, - expected: "[fd78:94bf:7df8::1]:53", + name: "MixedServersWithOwnIP", + nsGroups: []*nbdns.NameServerGroup{ + { + Primary: false, + NameServers: []nbdns.NameServer{ + {IP: netip.MustParseAddr("8.8.8.8"), NSType: nbdns.UDPNameServerType, Port: 53}, + {IP: dnsServerIP, NSType: nbdns.UDPNameServerType, Port: 53}, + {IP: netip.MustParseAddr("1.1.1.1"), NSType: nbdns.UDPNameServerType, Port: 53}, + {IP: dnsServerIP, NSType: nbdns.UDPNameServerType, Port: 53}, // duplicate + }, + Domains: []string{"test.com"}, + }, + }, + expectedHandlers: 1, + expectedServers: []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("1.1.1.1")}, + shouldFilterOwnIP: true, }, { - name: "IPv6 address with custom port", - address: "2001:db8::1", - port: 5353, - expected: "[2001:db8::1]:5353", - }, - { - name: "IPv6 localhost", - address: "::1", - port: 53, - expected: "[::1]:53", - }, - { - name: "Invalid address treated as hostname", - address: "dns.example.com", - port: 53, - expected: "dns.example.com:53", + name: "NoOwnIPInList", + nsGroups: []*nbdns.NameServerGroup{ + { + Primary: true, + NameServers: []nbdns.NameServer{ + {IP: netip.MustParseAddr("8.8.8.8"), NSType: nbdns.UDPNameServerType, Port: 53}, + {IP: netip.MustParseAddr("1.1.1.1"), NSType: nbdns.UDPNameServerType, Port: 53}, + }, + Domains: []string{}, + }, + }, + expectedHandlers: 1, + expectedServers: []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("1.1.1.1")}, + shouldFilterOwnIP: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := formatAddr(tt.address, tt.port) - assert.Equal(t, tt.expected, result) + muxUpdates, err := server.buildUpstreamHandlerUpdate(tt.nsGroups) + assert.NoError(t, err) + assert.Len(t, muxUpdates, tt.expectedHandlers) + + if tt.expectedHandlers > 0 { + handler := muxUpdates[0].handler.(*upstreamResolver) + assert.Len(t, handler.upstreamServers, len(tt.expectedServers)) + + if tt.shouldFilterOwnIP { + for _, upstream := range handler.upstreamServers { + assert.NotEqual(t, dnsServerIP, upstream.Addr()) + } + } + + for _, expected := range tt.expectedServers { + found := false + for _, upstream := range handler.upstreamServers { + if upstream.Addr() == expected { + found = true + break + } + } + assert.True(t, found, "Expected server %s not found", expected) + } + } }) } } diff --git a/client/internal/dns/service.go b/client/internal/dns/service.go index ab8238a61..6a76c53e3 100644 --- a/client/internal/dns/service.go +++ b/client/internal/dns/service.go @@ -7,7 +7,7 @@ import ( ) const ( - defaultPort = 53 + DefaultPort = 53 ) type service interface { diff --git a/client/internal/dns/service_listener.go b/client/internal/dns/service_listener.go index abd2f4f05..806559444 100644 --- a/client/internal/dns/service_listener.go +++ b/client/internal/dns/service_listener.go @@ -122,7 +122,7 @@ func (s *serviceViaListener) RuntimePort() int { defer s.listenerFlagLock.Unlock() if s.ebpfService != nil { - return defaultPort + return DefaultPort } else { return int(s.listenPort) } @@ -148,9 +148,9 @@ func (s *serviceViaListener) evalListenAddress() (netip.Addr, uint16, error) { return s.customAddr.Addr(), s.customAddr.Port(), nil } - ip, ok := s.testFreePort(defaultPort) + ip, ok := s.testFreePort(DefaultPort) if ok { - return ip, defaultPort, nil + return ip, DefaultPort, nil } ebpfSrv, port, ok := s.tryToUseeBPF() diff --git a/client/internal/dns/service_memory.go b/client/internal/dns/service_memory.go index 9f55838bf..89d637686 100644 --- a/client/internal/dns/service_memory.go +++ b/client/internal/dns/service_memory.go @@ -33,7 +33,7 @@ func NewServiceViaMemory(wgIface WGIface) *ServiceViaMemory { dnsMux: dns.NewServeMux(), runtimeIP: lastIP, - runtimePort: defaultPort, + runtimePort: DefaultPort, } return s } diff --git a/client/internal/dns/systemd_linux.go b/client/internal/dns/systemd_linux.go index a58747d5b..0e8a53a63 100644 --- a/client/internal/dns/systemd_linux.go +++ b/client/internal/dns/systemd_linux.go @@ -235,7 +235,7 @@ func (s *systemdDbusConfigurator) callLinkMethod(method string, value any) error return nil } -func (s *systemdDbusConfigurator) restoreUncleanShutdownDNS(*netip.Addr) error { +func (s *systemdDbusConfigurator) restoreUncleanShutdownDNS(netip.Addr) error { if err := s.restoreHostDNS(); err != nil { return fmt.Errorf("restoring dns via systemd: %w", err) } diff --git a/client/internal/dns/unclean_shutdown_unix.go b/client/internal/dns/unclean_shutdown_unix.go index 2e786f484..dc44aefaf 100644 --- a/client/internal/dns/unclean_shutdown_unix.go +++ b/client/internal/dns/unclean_shutdown_unix.go @@ -27,7 +27,7 @@ func (s *ShutdownState) Cleanup() error { return fmt.Errorf("create previous host manager: %w", err) } - if err := manager.restoreUncleanShutdownDNS(&s.DNSAddress); err != nil { + if err := manager.restoreUncleanShutdownDNS(s.DNSAddress); err != nil { return fmt.Errorf("restore unclean shutdown dns: %w", err) } diff --git a/client/internal/dns/unclean_shutdown_windows.go b/client/internal/dns/unclean_shutdown_windows.go index ab0b2cc63..24a9eca50 100644 --- a/client/internal/dns/unclean_shutdown_windows.go +++ b/client/internal/dns/unclean_shutdown_windows.go @@ -5,8 +5,9 @@ import ( ) type ShutdownState struct { - Guid string - GPO bool + Guid string + GPO bool + NRPTEntryCount int } func (s *ShutdownState) Name() string { @@ -15,8 +16,9 @@ func (s *ShutdownState) Name() string { func (s *ShutdownState) Cleanup() error { manager := ®istryConfigurator{ - guid: s.Guid, - gpo: s.GPO, + guid: s.Guid, + gpo: s.GPO, + nrptEntryCount: s.NRPTEntryCount, } if err := manager.restoreUncleanShutdownDNS(); err != nil { diff --git a/client/internal/dns/upstream.go b/client/internal/dns/upstream.go index f92e66d5e..1d0ad0463 100644 --- a/client/internal/dns/upstream.go +++ b/client/internal/dns/upstream.go @@ -51,7 +51,7 @@ type upstreamResolverBase struct { ctx context.Context cancel context.CancelFunc upstreamClient upstreamClient - upstreamServers []string + upstreamServers []netip.AddrPort domain string disabled bool successCount atomic.Int32 @@ -79,17 +79,20 @@ func newUpstreamResolverBase(ctx context.Context, statusRecorder *peer.Status, d // String returns a string representation of the upstream resolver func (u *upstreamResolverBase) String() string { - return fmt.Sprintf("Upstream %v", u.upstreamServers) + return fmt.Sprintf("Upstream %s", u.upstreamServers) } // ID returns the unique handler ID func (u *upstreamResolverBase) ID() types.HandlerID { servers := slices.Clone(u.upstreamServers) - slices.Sort(servers) + slices.SortFunc(servers, func(a, b netip.AddrPort) int { return a.Compare(b) }) hash := sha256.New() hash.Write([]byte(u.domain + ":")) - hash.Write([]byte(strings.Join(servers, ","))) + for _, s := range servers { + hash.Write([]byte(s.String())) + hash.Write([]byte("|")) + } return types.HandlerID("upstream-" + hex.EncodeToString(hash.Sum(nil)[:8])) } @@ -129,7 +132,6 @@ func (u *upstreamResolverBase) prepareRequest(r *dns.Msg) { } } - func (u *upstreamResolverBase) tryUpstreamServers(w dns.ResponseWriter, r *dns.Msg, logger *log.Entry) bool { timeout := u.upstreamTimeout if len(u.upstreamServers) > 1 { @@ -151,7 +153,7 @@ func (u *upstreamResolverBase) tryUpstreamServers(w dns.ResponseWriter, r *dns.M return false } -func (u *upstreamResolverBase) queryUpstream(w dns.ResponseWriter, r *dns.Msg, upstream string, timeout time.Duration, logger *log.Entry) bool { +func (u *upstreamResolverBase) queryUpstream(w dns.ResponseWriter, r *dns.Msg, upstream netip.AddrPort, timeout time.Duration, logger *log.Entry) bool { var rm *dns.Msg var t time.Duration var err error @@ -161,7 +163,7 @@ func (u *upstreamResolverBase) queryUpstream(w dns.ResponseWriter, r *dns.Msg, u ctx, cancel := context.WithTimeout(u.ctx, timeout) defer cancel() startTime = time.Now() - rm, t, err = u.upstreamClient.exchange(ctx, upstream, r) + rm, t, err = u.upstreamClient.exchange(ctx, upstream.String(), r) }() if err != nil { @@ -177,7 +179,7 @@ func (u *upstreamResolverBase) queryUpstream(w dns.ResponseWriter, r *dns.Msg, u return u.writeSuccessResponse(w, rm, upstream, r.Question[0].Name, t, logger) } -func (u *upstreamResolverBase) handleUpstreamError(err error, upstream, domain string, startTime time.Time, timeout time.Duration, logger *log.Entry) { +func (u *upstreamResolverBase) handleUpstreamError(err error, upstream netip.AddrPort, domain string, startTime time.Time, timeout time.Duration, logger *log.Entry) { if !errors.Is(err, context.DeadlineExceeded) && !isTimeout(err) { logger.Warnf("failed to query upstream %s for question domain=%s: %s", upstream, domain, err) return @@ -192,7 +194,7 @@ func (u *upstreamResolverBase) handleUpstreamError(err error, upstream, domain s logger.Warnf(timeoutMsg) } -func (u *upstreamResolverBase) writeSuccessResponse(w dns.ResponseWriter, rm *dns.Msg, upstream, domain string, t time.Duration, logger *log.Entry) bool { +func (u *upstreamResolverBase) writeSuccessResponse(w dns.ResponseWriter, rm *dns.Msg, upstream netip.AddrPort, domain string, t time.Duration, logger *log.Entry) bool { u.successCount.Add(1) logger.Tracef("took %s to query the upstream %s for question domain=%s", t, upstream, domain) @@ -268,7 +270,7 @@ func (u *upstreamResolverBase) ProbeAvailability() { proto.SystemEvent_DNS, "All upstream servers failed (probe failed)", "Unable to reach one or more DNS servers. This might affect your ability to connect to some services.", - map[string]string{"upstreams": strings.Join(u.upstreamServers, ", ")}, + map[string]string{"upstreams": u.upstreamServersString()}, ) } } @@ -288,7 +290,7 @@ func (u *upstreamResolverBase) waitUntilResponse() { operation := func() error { select { case <-u.ctx.Done(): - return backoff.Permanent(fmt.Errorf("exiting upstream retry loop for upstreams %s: parent context has been canceled", u.upstreamServers)) + return backoff.Permanent(fmt.Errorf("exiting upstream retry loop for upstreams %s: parent context has been canceled", u.upstreamServersString())) default: } @@ -301,7 +303,7 @@ func (u *upstreamResolverBase) waitUntilResponse() { } } - log.Tracef("checking connectivity with upstreams %s failed. Retrying in %s", u.upstreamServers, exponentialBackOff.NextBackOff()) + log.Tracef("checking connectivity with upstreams %s failed. Retrying in %s", u.upstreamServersString(), exponentialBackOff.NextBackOff()) return fmt.Errorf("upstream check call error") } @@ -311,7 +313,7 @@ func (u *upstreamResolverBase) waitUntilResponse() { return } - log.Infof("upstreams %s are responsive again. Adding them back to system", u.upstreamServers) + log.Infof("upstreams %s are responsive again. Adding them back to system", u.upstreamServersString()) u.successCount.Add(1) u.reactivate() u.disabled = false @@ -340,13 +342,21 @@ func (u *upstreamResolverBase) disable(err error) { go u.waitUntilResponse() } -func (u *upstreamResolverBase) testNameserver(server string, timeout time.Duration) error { +func (u *upstreamResolverBase) upstreamServersString() string { + var servers []string + for _, server := range u.upstreamServers { + servers = append(servers, server.String()) + } + return strings.Join(servers, ", ") +} + +func (u *upstreamResolverBase) testNameserver(server netip.AddrPort, timeout time.Duration) error { ctx, cancel := context.WithTimeout(u.ctx, timeout) defer cancel() r := new(dns.Msg).SetQuestion(testRecord, dns.TypeSOA) - _, _, err := u.upstreamClient.exchange(ctx, server, r) + _, _, err := u.upstreamClient.exchange(ctx, server.String(), r) return err } @@ -484,17 +494,12 @@ func parseUpstreamIP(upstream string) (netip.Addr, error) { return upstreamIP, nil } -func (u *upstreamResolverBase) debugUpstreamTimeout(upstream string) string { +func (u *upstreamResolverBase) debugUpstreamTimeout(upstream netip.AddrPort) string { if u.statusRecorder == nil { return "" } - upstreamIP, err := parseUpstreamIP(upstream) - if err != nil { - return "" - } - - peerInfo := findPeerForIP(upstreamIP, u.statusRecorder) + peerInfo := findPeerForIP(upstream.Addr(), u.statusRecorder) if peerInfo == nil { return "" } diff --git a/client/internal/dns/upstream_android.go b/client/internal/dns/upstream_android.go index 53f59032e..6b7dcc05e 100644 --- a/client/internal/dns/upstream_android.go +++ b/client/internal/dns/upstream_android.go @@ -82,8 +82,8 @@ func (u *upstreamResolver) exchangeWithoutVPN(ctx context.Context, upstream stri } func (u *upstreamResolver) isLocalResolver(upstream string) bool { - if u.hostsDNSHolder.isContain(upstream) { - return true + if addrPort, err := netip.ParseAddrPort(upstream); err == nil { + return u.hostsDNSHolder.contains(addrPort) } return false } diff --git a/client/internal/dns/upstream_ios.go b/client/internal/dns/upstream_ios.go index 89d53a482..eadcdd117 100644 --- a/client/internal/dns/upstream_ios.go +++ b/client/internal/dns/upstream_ios.go @@ -64,6 +64,8 @@ func (u *upstreamResolverIOS) exchange(ctx context.Context, upstream string, r * upstreamIP, err := netip.ParseAddr(upstreamHost) if err != nil { log.Warnf("failed to parse upstream host %s: %s", upstreamHost, err) + } else { + upstreamIP = upstreamIP.Unmap() } if u.lNet.Contains(upstreamIP) || upstreamIP.IsPrivate() { log.Debugf("using private client to query upstream: %s", upstream) diff --git a/client/internal/dns/upstream_test.go b/client/internal/dns/upstream_test.go index e290f74f8..e1573e75e 100644 --- a/client/internal/dns/upstream_test.go +++ b/client/internal/dns/upstream_test.go @@ -59,7 +59,14 @@ func TestUpstreamResolver_ServeDNS(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.TODO()) resolver, _ := newUpstreamResolver(ctx, "", netip.Addr{}, netip.Prefix{}, nil, nil, ".") - resolver.upstreamServers = testCase.InputServers + // Convert test servers to netip.AddrPort + var servers []netip.AddrPort + for _, server := range testCase.InputServers { + if addrPort, err := netip.ParseAddrPort(server); err == nil { + servers = append(servers, netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port())) + } + } + resolver.upstreamServers = servers resolver.upstreamTimeout = testCase.timeout if testCase.cancelCTX { cancel() @@ -129,7 +136,8 @@ func TestUpstreamResolver_DeactivationReactivation(t *testing.T) { upstreamTimeout: UpstreamTimeout, reactivatePeriod: time.Microsecond * 100, } - resolver.upstreamServers = []string{"0.0.0.0:-1"} + addrPort, _ := netip.ParseAddrPort("0.0.0.0:1") // Use valid port for parsing, test will still fail on connection + resolver.upstreamServers = []netip.AddrPort{netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port())} failed := false resolver.deactivate = func(error) { diff --git a/client/internal/dnsfwd/forwarder.go b/client/internal/dnsfwd/forwarder.go index 506c429cd..d912919a1 100644 --- a/client/internal/dnsfwd/forwarder.go +++ b/client/internal/dnsfwd/forwarder.go @@ -165,7 +165,7 @@ func (f *DNSForwarder) handleDNSQuery(w dns.ResponseWriter, query *dns.Msg) *dns defer cancel() ips, err := f.resolver.LookupNetIP(ctx, network, domain) if err != nil { - f.handleDNSError(w, query, resp, domain, err) + f.handleDNSError(ctx, w, question, resp, domain, err) return nil } @@ -244,20 +244,57 @@ func (f *DNSForwarder) updateFirewall(matchingEntries []*ForwarderEntry, prefixe } } +// setResponseCodeForNotFound determines and sets the appropriate response code when IsNotFound is true +// It distinguishes between NXDOMAIN (domain doesn't exist) and NODATA (domain exists but no records of requested type) +// +// LIMITATION: This function only checks A and AAAA record types to determine domain existence. +// If a domain has only other record types (MX, TXT, CNAME, etc.) but no A/AAAA records, +// it may incorrectly return NXDOMAIN instead of NODATA. This is acceptable since the forwarder +// only handles A/AAAA queries and returns NOTIMP for other types. +func (f *DNSForwarder) setResponseCodeForNotFound(ctx context.Context, resp *dns.Msg, domain string, originalQtype uint16) { + // Try querying for a different record type to see if the domain exists + // If the original query was for AAAA, try A. If it was for A, try AAAA. + // This helps distinguish between NXDOMAIN and NODATA. + var alternativeNetwork string + switch originalQtype { + case dns.TypeAAAA: + alternativeNetwork = "ip4" + case dns.TypeA: + alternativeNetwork = "ip6" + default: + resp.Rcode = dns.RcodeNameError + return + } + + if _, err := f.resolver.LookupNetIP(ctx, alternativeNetwork, domain); err != nil { + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) && dnsErr.IsNotFound { + // Alternative query also returned not found - domain truly doesn't exist + resp.Rcode = dns.RcodeNameError + return + } + // Some other error (timeout, server failure, etc.) - can't determine, assume domain exists + resp.Rcode = dns.RcodeSuccess + return + } + + // Alternative query succeeded - domain exists but has no records of this type + resp.Rcode = dns.RcodeSuccess +} + // handleDNSError processes DNS lookup errors and sends an appropriate error response -func (f *DNSForwarder) handleDNSError(w dns.ResponseWriter, query, resp *dns.Msg, domain string, err error) { +func (f *DNSForwarder) handleDNSError(ctx context.Context, w dns.ResponseWriter, question dns.Question, resp *dns.Msg, domain string, err error) { var dnsErr *net.DNSError switch { case errors.As(err, &dnsErr): resp.Rcode = dns.RcodeServerFailure if dnsErr.IsNotFound { - // Pass through NXDOMAIN - resp.Rcode = dns.RcodeNameError + f.setResponseCodeForNotFound(ctx, resp, domain, question.Qtype) } if dnsErr.Server != "" { - log.Warnf("failed to resolve query for type=%s domain=%s server=%s: %v", dns.TypeToString[query.Question[0].Qtype], domain, dnsErr.Server, err) + log.Warnf("failed to resolve query for type=%s domain=%s server=%s: %v", dns.TypeToString[question.Qtype], domain, dnsErr.Server, err) } else { log.Warnf(errResolveFailed, domain, err) } diff --git a/client/internal/dnsfwd/forwarder_test.go b/client/internal/dnsfwd/forwarder_test.go index d8228c733..57085e19a 100644 --- a/client/internal/dnsfwd/forwarder_test.go +++ b/client/internal/dnsfwd/forwarder_test.go @@ -3,6 +3,7 @@ package dnsfwd import ( "context" "fmt" + "net" "net/netip" "strings" "testing" @@ -16,8 +17,8 @@ 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/route" + "github.com/netbirdio/netbird/shared/management/domain" ) func Test_getMatchingEntries(t *testing.T) { @@ -708,6 +709,131 @@ func TestDNSForwarder_MultipleOverlappingPatterns(t *testing.T) { assert.Len(t, matches, 3, "Should match 3 patterns") } +// TestDNSForwarder_NodataVsNxdomain tests that the forwarder correctly distinguishes +// between NXDOMAIN (domain doesn't exist) and NODATA (domain exists but no records of that type) +func TestDNSForwarder_NodataVsNxdomain(t *testing.T) { + mockFirewall := &MockFirewall{} + mockResolver := &MockResolver{} + + forwarder := NewDNSForwarder("127.0.0.1:0", 300, mockFirewall, &peer.Status{}) + forwarder.resolver = mockResolver + + d, err := domain.FromString("example.com") + require.NoError(t, err) + + set := firewall.NewDomainSet([]domain.Domain{d}) + entries := []*ForwarderEntry{{Domain: d, ResID: "test-res", Set: set}} + forwarder.UpdateDomains(entries) + + tests := []struct { + name string + queryType uint16 + setupMocks func() + expectedCode int + expectNoAnswer bool // true if we expect NOERROR with empty answer (NODATA case) + description string + }{ + { + name: "domain exists but no AAAA records (NODATA)", + queryType: dns.TypeAAAA, + setupMocks: func() { + // First query for AAAA returns not found + mockResolver.On("LookupNetIP", mock.Anything, "ip6", "example.com."). + Return([]netip.Addr{}, &net.DNSError{IsNotFound: true, Name: "example.com"}).Once() + // Check query for A records succeeds (domain exists) + mockResolver.On("LookupNetIP", mock.Anything, "ip4", "example.com."). + Return([]netip.Addr{netip.MustParseAddr("1.2.3.4")}, nil).Once() + }, + expectedCode: dns.RcodeSuccess, + expectNoAnswer: true, + description: "Should return NOERROR when domain exists but has no records of requested type", + }, + { + name: "domain exists but no A records (NODATA)", + queryType: dns.TypeA, + setupMocks: func() { + // First query for A returns not found + mockResolver.On("LookupNetIP", mock.Anything, "ip4", "example.com."). + Return([]netip.Addr{}, &net.DNSError{IsNotFound: true, Name: "example.com"}).Once() + // Check query for AAAA records succeeds (domain exists) + mockResolver.On("LookupNetIP", mock.Anything, "ip6", "example.com."). + Return([]netip.Addr{netip.MustParseAddr("2001:db8::1")}, nil).Once() + }, + expectedCode: dns.RcodeSuccess, + expectNoAnswer: true, + description: "Should return NOERROR when domain exists but has no A records", + }, + { + name: "domain doesn't exist (NXDOMAIN)", + queryType: dns.TypeA, + setupMocks: func() { + // First query for A returns not found + mockResolver.On("LookupNetIP", mock.Anything, "ip4", "example.com."). + Return([]netip.Addr{}, &net.DNSError{IsNotFound: true, Name: "example.com"}).Once() + // Check query for AAAA also returns not found (domain doesn't exist) + mockResolver.On("LookupNetIP", mock.Anything, "ip6", "example.com."). + Return([]netip.Addr{}, &net.DNSError{IsNotFound: true, Name: "example.com"}).Once() + }, + expectedCode: dns.RcodeNameError, + expectNoAnswer: true, + description: "Should return NXDOMAIN when domain doesn't exist at all", + }, + { + name: "domain exists with records (normal success)", + queryType: dns.TypeA, + setupMocks: func() { + mockResolver.On("LookupNetIP", mock.Anything, "ip4", "example.com."). + Return([]netip.Addr{netip.MustParseAddr("1.2.3.4")}, nil).Once() + // Expect firewall update for successful resolution + expectedPrefix := netip.PrefixFrom(netip.MustParseAddr("1.2.3.4"), 32) + mockFirewall.On("UpdateSet", set, []netip.Prefix{expectedPrefix}).Return(nil).Once() + }, + expectedCode: dns.RcodeSuccess, + expectNoAnswer: false, + description: "Should return NOERROR with answer when records exist", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Reset mock expectations + mockResolver.ExpectedCalls = nil + mockResolver.Calls = nil + mockFirewall.ExpectedCalls = nil + mockFirewall.Calls = nil + + tt.setupMocks() + + query := &dns.Msg{} + query.SetQuestion(dns.Fqdn("example.com"), tt.queryType) + + var writtenResp *dns.Msg + mockWriter := &test.MockResponseWriter{ + WriteMsgFunc: func(m *dns.Msg) error { + writtenResp = m + return nil + }, + } + + resp := forwarder.handleDNSQuery(mockWriter, query) + + // If a response was returned, it means it should be written (happens in wrapper functions) + if resp != nil && writtenResp == nil { + writtenResp = resp + } + + require.NotNil(t, writtenResp, "Expected response to be written") + assert.Equal(t, tt.expectedCode, writtenResp.Rcode, tt.description) + + if tt.expectNoAnswer { + assert.Empty(t, writtenResp.Answer, "Response should have no answer records") + } + + mockResolver.AssertExpectations(t) + }) + } +} + func TestDNSForwarder_EmptyQuery(t *testing.T) { // Test handling of malformed query with no questions forwarder := NewDNSForwarder("127.0.0.1:0", 300, nil, &peer.Status{}) 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 e4be8da51..bd530a6d9 100644 --- a/client/internal/engine.go +++ b/client/internal/engine.go @@ -51,19 +51,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" ) @@ -191,11 +191,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 @@ -240,7 +240,7 @@ func NewEngine( connSemaphore: semaphoregroup.NewSemaphoreGroup(connInitLimit), } - sm := profilemanager.ServiceManager{} + sm := profilemanager.NewServiceManager("") path := sm.GetStatePath() if runtime.GOOS == "ios" { @@ -732,10 +732,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 @@ -896,15 +896,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 { @@ -915,7 +910,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() @@ -1812,44 +1807,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 114488ee7..a42d592ba 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 37ee4e851..257e3c3ac 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/mobile_dependency.go b/client/internal/mobile_dependency.go index 4ac0fc141..7c95e2b99 100644 --- a/client/internal/mobile_dependency.go +++ b/client/internal/mobile_dependency.go @@ -1,6 +1,8 @@ package internal import ( + "net/netip" + "github.com/netbirdio/netbird/client/iface/device" "github.com/netbirdio/netbird/client/internal/dns" "github.com/netbirdio/netbird/client/internal/listener" @@ -13,7 +15,7 @@ type MobileDependency struct { TunAdapter device.TunAdapter IFaceDiscover stdnet.ExternalIFaceDiscover NetworkChangeListener listener.NetworkChangeListener - HostDNSAddresses []string + HostDNSAddresses []netip.AddrPort DnsReadyListener dns.ReadyListener // iOS only diff --git a/client/internal/peer/conn.go b/client/internal/peer/conn.go index ddd90450d..d5a55bc58 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 9022e0299..58df66fcf 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..239cce7e0 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" ) @@ -140,7 +140,7 @@ type RosenpassState struct { // whether it's enabled, and the last error message encountered during probing. type NSGroupState struct { ID string - Servers []string + Servers []netip.AddrPort Domains []string Enabled bool Error error 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..6bbdbd984 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" @@ -594,17 +593,9 @@ func update(input ConfigInput) (*Config, error) { return config, nil } +// GetConfig read config file and return with Config. Errors out if it does not exist func GetConfig(configPath string) (*Config, error) { - if !fileExists(configPath) { - return nil, fmt.Errorf("config file %s does not exist", configPath) - } - - config := &Config{} - if _, err := util.ReadJson(configPath, config); err != nil { - return nil, fmt.Errorf("failed to read config file %s: %w", configPath, err) - } - - return config, nil + return readConfig(configPath, false) } // UpdateOldManagementURL checks whether client can switch to the new Management URL with port 443 and the management domain. @@ -696,6 +687,11 @@ func CreateInMemoryConfig(input ConfigInput) (*Config, error) { // ReadConfig read config file and return with Config. If it is not exists create a new with default values func ReadConfig(configPath string) (*Config, error) { + return readConfig(configPath, true) +} + +// ReadConfig read config file and return with Config. If it is not exists create a new with default values +func readConfig(configPath string, createIfMissing bool) (*Config, error) { if fileExists(configPath) { err := util.EnforcePermission(configPath) if err != nil { @@ -716,6 +712,8 @@ func ReadConfig(configPath string) (*Config, error) { } return config, nil + } else if !createIfMissing { + return nil, fmt.Errorf("config file %s does not exist", configPath) } cfg, err := createNewConfig(ConfigInput{ConfigPath: configPath}) 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 b0413b07d..9069cdcc5 100644 --- a/client/internal/routemanager/dnsinterceptor/handler.go +++ b/client/internal/routemanager/dnsinterceptor/handler.go @@ -24,7 +24,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/netbird.wxs b/client/netbird.wxs index 91595539a..ba827debf 100644 --- a/client/netbird.wxs +++ b/client/netbird.wxs @@ -16,19 +16,21 @@ - - + + - - + + + + 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..daef7d02b 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 @@ -1041,8 +1197,14 @@ func toProtoFullStatus(fullStatus peer.FullStatus) *proto.FullStatus { if dnsState.Error != nil { err = dnsState.Error.Error() } + + var servers []string + for _, server := range dnsState.Servers { + servers = append(servers, server.String()) + } + pbDnsState := &proto.NSGroupState{ - Servers: dnsState.Servers, + Servers: servers, Domains: dnsState.Domains, Enabled: dnsState.Enabled, Error: err, @@ -1107,12 +1269,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..f4505ab19 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("Deregister", 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("Deregister") + 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( + "Deregister", + fmt.Sprintf("Are you sure you want to deregister 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("deregister failed"), s.wProfiles) + return + } + + dialog.ShowInformation( + "Deregistered", + fmt.Sprintf("Successfully deregistered 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("Deregister", "") + 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 deregister")) + } else { + p.app.SendNotification(fyne.NewNotification("Success", "Deregistered 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/dns/nameserver.go b/dns/nameserver.go index bb904b165..81c616c50 100644 --- a/dns/nameserver.go +++ b/dns/nameserver.go @@ -102,6 +102,11 @@ func (n *NameServer) IsEqual(other *NameServer) bool { other.Port == n.Port } +// AddrPort returns the nameserver as a netip.AddrPort +func (n *NameServer) AddrPort() netip.AddrPort { + return netip.AddrPortFrom(n.IP, uint16(n.Port)) +} + // ParseNameServerURL parses a nameserver url in the format ://:, e.g., udp://1.1.1.1:53 func ParseNameServerURL(nsURL string) (NameServer, error) { parsedURL, err := url.Parse(nsURL) 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 d392cd0b9..0f60bc91c 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,12 +40,12 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/telemetry" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/util" "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/status" ) const ( @@ -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 { @@ -338,12 +346,12 @@ func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, acco } if updateAccountPeers || groupsUpdated { - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } } - return transaction.SaveAccountSettings(ctx, store.LockingStrengthUpdate, accountID, newSettings) + return transaction.SaveAccountSettings(ctx, accountID, newSettings) }) if err != nil { return nil, err @@ -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 { @@ -386,7 +405,7 @@ func (am *DefaultAccountManager) validateSettingsUpdate(ctx context.Context, tra return status.Errorf(status.InvalidArgument, "invalid domain \"%s\" provided for DNS domain", newSettings.DNSDomain) } - peers, err := transaction.GetAccountPeers(ctx, store.LockingStrengthShare, accountID, "", "") + peers, err := transaction.GetAccountPeers(ctx, store.LockingStrengthNone, accountID, "", "") if err != nil { return err } @@ -727,7 +746,7 @@ func (am *DefaultAccountManager) DeleteAccount(ctx context.Context, accountID, u // AccountExists checks if an account exists. func (am *DefaultAccountManager) AccountExists(ctx context.Context, accountID string) (bool, error) { - return am.Store.AccountExists(ctx, store.LockingStrengthShare, accountID) + return am.Store.AccountExists(ctx, store.LockingStrengthNone, accountID) } // GetAccountIDByUserID retrieves the account ID based on the userID provided. @@ -739,7 +758,7 @@ func (am *DefaultAccountManager) GetAccountIDByUserID(ctx context.Context, userI return "", status.Errorf(status.NotFound, "no valid userID provided") } - accountID, err := am.Store.GetAccountIDByUserID(ctx, store.LockingStrengthShare, userID) + accountID, err := am.Store.GetAccountIDByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { if s, ok := status.FromError(err); ok && s.Type() == status.NotFound { account, err := am.GetOrCreateAccountByUser(ctx, userID, domain) @@ -794,7 +813,7 @@ func (am *DefaultAccountManager) loadAccount(ctx context.Context, accountID any) log.WithContext(ctx).Debugf("account %s not found in cache, reloading", accountID) accountIDString := fmt.Sprintf("%v", accountID) - accountUsers, err := am.Store.GetAccountUsers(ctx, store.LockingStrengthShare, accountIDString) + accountUsers, err := am.Store.GetAccountUsers(ctx, store.LockingStrengthNone, accountIDString) if err != nil { return nil, nil, err } @@ -848,7 +867,7 @@ func (am *DefaultAccountManager) lookupUserInCacheByEmail(ctx context.Context, e // lookupUserInCache looks up user in the IdP cache and returns it. If the user wasn't found, the function returns nil func (am *DefaultAccountManager) lookupUserInCache(ctx context.Context, userID string, accountID string) (*idp.UserData, error) { - accountUsers, err := am.Store.GetAccountUsers(ctx, store.LockingStrengthShare, accountID) + accountUsers, err := am.Store.GetAccountUsers(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -878,7 +897,7 @@ func (am *DefaultAccountManager) lookupUserInCache(ctx context.Context, userID s // add extra check on external cache manager. We may get to this point when the user is not yet findable in IDP, // or it didn't have its metadata updated with am.addAccountIDToIDPAppMeta - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { log.WithContext(ctx).Errorf("failed finding user %s in account %s", userID, accountID) return nil, err @@ -1029,7 +1048,7 @@ func (am *DefaultAccountManager) updateAccountDomainAttributesIfNotUpToDate(ctx unlockAccount := am.Store.AcquireWriteLockByUID(ctx, accountID) defer unlockAccount() - accountDomain, domainCategory, err := am.Store.GetAccountDomainAndCategory(ctx, store.LockingStrengthShare, accountID) + accountDomain, domainCategory, err := am.Store.GetAccountDomainAndCategory(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error getting account domain and category: %v", err) return err @@ -1039,7 +1058,7 @@ func (am *DefaultAccountManager) updateAccountDomainAttributesIfNotUpToDate(ctx return nil } - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userAuth.UserId) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userAuth.UserId) if err != nil { log.WithContext(ctx).Errorf("error getting user: %v", err) return err @@ -1126,7 +1145,7 @@ func (am *DefaultAccountManager) addNewUserToDomainAccount(ctx context.Context, newUser := types.NewRegularUser(userAuth.UserId) newUser.AccountID = domainAccountID - err := am.Store.SaveUser(ctx, store.LockingStrengthUpdate, newUser) + err := am.Store.SaveUser(ctx, newUser) if err != nil { return "", err } @@ -1204,7 +1223,7 @@ func (am *DefaultAccountManager) GetAccountMeta(ctx context.Context, accountID s return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountMeta(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountMeta(ctx, store.LockingStrengthNone, accountID) } // GetAccountOnboarding retrieves the onboarding information for a specific account. @@ -1289,7 +1308,7 @@ func (am *DefaultAccountManager) GetAccountIDFromUserAuth(ctx context.Context, u return "", "", err } - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userAuth.UserId) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userAuth.UserId) if err != nil { // this is not really possible because we got an account by user ID return "", "", status.Errorf(status.NotFound, "user %s not found", userAuth.UserId) @@ -1321,7 +1340,7 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth return nil } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, userAuth.AccountId) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, userAuth.AccountId) if err != nil { return err } @@ -1347,12 +1366,12 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth var hasChanges bool var user *types.User err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - user, err = transaction.GetUserByUserID(ctx, store.LockingStrengthShare, userAuth.UserId) + user, err = transaction.GetUserByUserID(ctx, store.LockingStrengthNone, userAuth.UserId) if err != nil { return fmt.Errorf("error getting user: %w", err) } - groups, err := transaction.GetAccountGroups(ctx, store.LockingStrengthShare, userAuth.AccountId) + groups, err := transaction.GetAccountGroups(ctx, store.LockingStrengthNone, userAuth.AccountId) if err != nil { return fmt.Errorf("error getting account groups: %w", err) } @@ -1368,7 +1387,7 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth return nil } - if err = transaction.CreateGroups(ctx, store.LockingStrengthUpdate, userAuth.AccountId, newGroupsToCreate); err != nil { + if err = transaction.CreateGroups(ctx, userAuth.AccountId, newGroupsToCreate); err != nil { return fmt.Errorf("error saving groups: %w", err) } @@ -1376,13 +1395,13 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth removeOldGroups = util.Difference(user.AutoGroups, updatedAutoGroups) user.AutoGroups = updatedAutoGroups - if err = transaction.SaveUser(ctx, store.LockingStrengthUpdate, user); err != nil { + if err = transaction.SaveUser(ctx, user); err != nil { return fmt.Errorf("error saving user: %w", err) } // Propagate changes to peers if group propagation is enabled if settings.GroupsPropagationEnabled { - peers, err := transaction.GetUserPeers(ctx, store.LockingStrengthShare, userAuth.AccountId, userAuth.UserId) + peers, err := transaction.GetUserPeers(ctx, store.LockingStrengthNone, userAuth.AccountId, userAuth.UserId) if err != nil { return fmt.Errorf("error getting user peers: %w", err) } @@ -1400,7 +1419,7 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth } } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, userAuth.AccountId); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, userAuth.AccountId); err != nil { return fmt.Errorf("error incrementing network serial: %w", err) } } @@ -1418,7 +1437,7 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth } for _, g := range addNewGroups { - group, err := am.Store.GetGroupByID(ctx, store.LockingStrengthShare, userAuth.AccountId, g) + group, err := am.Store.GetGroupByID(ctx, store.LockingStrengthNone, userAuth.AccountId, g) if err != nil { log.WithContext(ctx).Debugf("group %s not found while saving user activity event of account %s", g, userAuth.AccountId) } else { @@ -1431,7 +1450,7 @@ func (am *DefaultAccountManager) SyncUserJWTGroups(ctx context.Context, userAuth } for _, g := range removeOldGroups { - group, err := am.Store.GetGroupByID(ctx, store.LockingStrengthShare, userAuth.AccountId, g) + group, err := am.Store.GetGroupByID(ctx, store.LockingStrengthNone, userAuth.AccountId, g) if err != nil { log.WithContext(ctx).Debugf("group %s not found while saving user activity event of account %s", g, userAuth.AccountId) } else { @@ -1492,7 +1511,7 @@ func (am *DefaultAccountManager) getAccountIDWithAuthorizationClaims(ctx context } if userAuth.IsChild { - exists, err := am.Store.AccountExists(ctx, store.LockingStrengthShare, userAuth.AccountId) + exists, err := am.Store.AccountExists(ctx, store.LockingStrengthNone, userAuth.AccountId) if err != nil || !exists { return "", err } @@ -1516,7 +1535,7 @@ func (am *DefaultAccountManager) getAccountIDWithAuthorizationClaims(ctx context return "", err } - userAccountID, err := am.Store.GetAccountIDByUserID(ctx, store.LockingStrengthShare, userAuth.UserId) + userAccountID, err := am.Store.GetAccountIDByUserID(ctx, store.LockingStrengthNone, userAuth.UserId) if handleNotFound(err) != nil { log.WithContext(ctx).Errorf("error getting account ID by user ID: %v", err) return "", err @@ -1537,7 +1556,7 @@ func (am *DefaultAccountManager) getAccountIDWithAuthorizationClaims(ctx context return am.addNewPrivateAccount(ctx, domainAccountID, userAuth) } func (am *DefaultAccountManager) getPrivateDomainWithGlobalLock(ctx context.Context, domain string) (string, context.CancelFunc, error) { - domainAccountID, err := am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthShare, domain) + domainAccountID, err := am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthNone, domain) if handleNotFound(err) != nil { log.WithContext(ctx).Errorf(errorGettingDomainAccIDFmt, err) @@ -1552,7 +1571,7 @@ func (am *DefaultAccountManager) getPrivateDomainWithGlobalLock(ctx context.Cont cancel := am.Store.AcquireGlobalLock(ctx) // check again if the domain has a primary account because of simultaneous requests - domainAccountID, err = am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthShare, domain) + domainAccountID, err = am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthNone, domain) if handleNotFound(err) != nil { cancel() log.WithContext(ctx).Errorf(errorGettingDomainAccIDFmt, err) @@ -1563,7 +1582,7 @@ func (am *DefaultAccountManager) getPrivateDomainWithGlobalLock(ctx context.Cont } func (am *DefaultAccountManager) handlePrivateAccountWithIDFromClaim(ctx context.Context, userAuth nbcontext.UserAuth) (string, error) { - userAccountID, err := am.Store.GetAccountIDByUserID(ctx, store.LockingStrengthShare, userAuth.UserId) + userAccountID, err := am.Store.GetAccountIDByUserID(ctx, store.LockingStrengthNone, userAuth.UserId) if err != nil { log.WithContext(ctx).Errorf("error getting account ID by user ID: %v", err) return "", err @@ -1573,7 +1592,7 @@ func (am *DefaultAccountManager) handlePrivateAccountWithIDFromClaim(ctx context return "", fmt.Errorf("user %s is not part of the account id %s", userAuth.UserId, userAuth.AccountId) } - accountDomain, domainCategory, err := am.Store.GetAccountDomainAndCategory(ctx, store.LockingStrengthShare, userAuth.AccountId) + accountDomain, domainCategory, err := am.Store.GetAccountDomainAndCategory(ctx, store.LockingStrengthNone, userAuth.AccountId) if handleNotFound(err) != nil { log.WithContext(ctx).Errorf("error getting account domain and category: %v", err) return "", err @@ -1584,7 +1603,7 @@ func (am *DefaultAccountManager) handlePrivateAccountWithIDFromClaim(ctx context } // We checked if the domain has a primary account already - domainAccountID, err := am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthShare, userAuth.Domain) + domainAccountID, err := am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthNone, userAuth.Domain) if handleNotFound(err) != nil { log.WithContext(ctx).Errorf(errorGettingDomainAccIDFmt, err) return "", err @@ -1700,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) { @@ -1714,7 +1751,7 @@ func (am *DefaultAccountManager) GetAccountIDForPeerKey(ctx context.Context, pee } func (am *DefaultAccountManager) handleUserPeer(ctx context.Context, transaction store.Store, peer *nbpeer.Peer, settings *types.Settings) (bool, error) { - user, err := transaction.GetUserByUserID(ctx, store.LockingStrengthShare, peer.UserID) + user, err := transaction.GetUserByUserID(ctx, store.LockingStrengthNone, peer.UserID) if err != nil { return false, err } @@ -1743,7 +1780,7 @@ func (am *DefaultAccountManager) GetAccountSettings(ctx context.Context, account if !allowed { return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) } // newAccountWithId creates a new Account with a default SetupKey (doesn't store in a Store) and provided id @@ -1833,7 +1870,7 @@ func (am *DefaultAccountManager) GetOrCreateAccountByPrivateDomain(ctx context.C cancel := am.Store.AcquireGlobalLock(ctx) defer cancel() - existingPrimaryAccountID, err := am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthShare, domain) + existingPrimaryAccountID, err := am.Store.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthNone, domain) if handleNotFound(err) != nil { return nil, false, err } @@ -1853,7 +1890,7 @@ func (am *DefaultAccountManager) GetOrCreateAccountByPrivateDomain(ctx context.C for range 2 { accountId := xid.New().String() - exists, err := am.Store.AccountExists(ctx, store.LockingStrengthShare, accountId) + exists, err := am.Store.AccountExists(ctx, store.LockingStrengthNone, accountId) if err != nil || exists { continue } @@ -1928,7 +1965,7 @@ func (am *DefaultAccountManager) UpdateToPrimaryAccount(ctx context.Context, acc return nil } - existingPrimaryAccountID, err := transaction.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthShare, account.Domain) + existingPrimaryAccountID, err := transaction.GetAccountIDByPrivateDomain(ctx, store.LockingStrengthNone, account.Domain) // error is not a not found error if handleNotFound(err) != nil { @@ -1965,17 +2002,17 @@ 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) { - users, err := transaction.GetAccountUsers(ctx, store.LockingStrengthShare, accountID) + users, err := transaction.GetAccountUsers(ctx, store.LockingStrengthNone, accountID) if err != nil { return false, false, err } - accountGroupPeers, err := transaction.GetAccountGroupPeers(ctx, store.LockingStrengthShare, accountID) + accountGroupPeers, err := transaction.GetAccountGroupPeers(ctx, store.LockingStrengthNone, accountID) if err != nil { return false, false, fmt.Errorf("error getting account group peers: %w", err) } - accountGroups, err := transaction.GetAccountGroups(ctx, store.LockingStrengthShare, accountID) + accountGroups, err := transaction.GetAccountGroups(ctx, store.LockingStrengthNone, accountID) if err != nil { return false, false, fmt.Errorf("error getting account groups: %w", err) } @@ -1988,7 +2025,7 @@ func propagateUserGroupMemberships(ctx context.Context, transaction store.Store, updatedGroups := []string{} for _, user := range users { - userPeers, err := transaction.GetUserPeers(ctx, store.LockingStrengthShare, accountID, user.Id) + userPeers, err := transaction.GetUserPeers(ctx, store.LockingStrengthNone, accountID, user.Id) if err != nil { return false, false, err } @@ -2018,3 +2055,154 @@ func propagateUserGroupMemberships(ctx context.Context, transaction store.Store, 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.LockingStrengthNone, 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, 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.LockingStrengthNone, 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.LockingStrengthNone, 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, 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 0cd1c6637..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) diff --git a/management/server/account_test.go b/management/server/account_test.go index 1dd74104b..0c618a8a3 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" @@ -782,7 +783,7 @@ func TestAccountManager_GetAccountByUserID(t *testing.T) { return } - exists, err := manager.Store.AccountExists(context.Background(), store.LockingStrengthShare, accountID) + exists, err := manager.Store.AccountExists(context.Background(), store.LockingStrengthNone, accountID) assert.NoError(t, err) assert.True(t, exists, "expected to get existing account after creation using userid") @@ -899,11 +900,11 @@ func TestAccountManager_DeleteAccount(t *testing.T) { t.Fatal(fmt.Errorf("expected to get an error when trying to get deleted account, got %v", getAccount)) } - pats, err := manager.Store.GetUserPATs(context.Background(), store.LockingStrengthShare, "service-user-1") + pats, err := manager.Store.GetUserPATs(context.Background(), store.LockingStrengthNone, "service-user-1") require.NoError(t, err) assert.Len(t, pats, 0) - pats, err = manager.Store.GetUserPATs(context.Background(), store.LockingStrengthShare, userId) + pats, err = manager.Store.GetUserPATs(context.Background(), store.LockingStrengthNone, userId) require.NoError(t, err) assert.Len(t, pats, 0) } @@ -1785,7 +1786,7 @@ func TestDefaultAccountManager_DefaultAccountSettings(t *testing.T) { accountID, err := manager.GetAccountIDByUserID(context.Background(), userID, "") require.NoError(t, err, "unable to create an account") - settings, err := manager.Store.GetAccountSettings(context.Background(), store.LockingStrengthShare, accountID) + settings, err := manager.Store.GetAccountSettings(context.Background(), store.LockingStrengthNone, accountID) require.NoError(t, err, "unable to get account settings") assert.NotNil(t, settings) @@ -1970,7 +1971,7 @@ func TestDefaultAccountManager_UpdateAccountSettings(t *testing.T) { assert.False(t, updatedSettings.PeerLoginExpirationEnabled) assert.Equal(t, updatedSettings.PeerLoginExpiration, time.Hour) - settings, err := manager.Store.GetAccountSettings(context.Background(), store.LockingStrengthShare, accountID) + settings, err := manager.Store.GetAccountSettings(context.Background(), store.LockingStrengthNone, accountID) require.NoError(t, err, "unable to get account settings") assert.False(t, settings.PeerLoginExpirationEnabled) @@ -2654,7 +2655,7 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 0, "JWT groups should not be synced") }) @@ -2668,7 +2669,7 @@ func TestAccount_SetJWTGroups(t *testing.T) { err := manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Empty(t, user.AutoGroups, "auto groups must be empty") }) @@ -2682,18 +2683,18 @@ func TestAccount_SetJWTGroups(t *testing.T) { err := manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 0) - group1, err := manager.Store.GetGroupByID(context.Background(), store.LockingStrengthShare, "accountID", "group1") + group1, err := manager.Store.GetGroupByID(context.Background(), store.LockingStrengthNone, "accountID", "group1") assert.NoError(t, err, "unable to get group") assert.Equal(t, group1.Issued, types.GroupIssuedAPI, "group should be api issued") }) t.Run("jwt match existing api group in user auto groups", func(t *testing.T) { account.Users["user1"].AutoGroups = []string{"group1"} - assert.NoError(t, manager.Store.SaveUser(context.Background(), store.LockingStrengthUpdate, account.Users["user1"])) + assert.NoError(t, manager.Store.SaveUser(context.Background(), account.Users["user1"])) claims := nbcontext.UserAuth{ UserId: "user1", @@ -2703,11 +2704,11 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 1) - group1, err := manager.Store.GetGroupByID(context.Background(), store.LockingStrengthShare, "accountID", "group1") + group1, err := manager.Store.GetGroupByID(context.Background(), store.LockingStrengthNone, "accountID", "group1") assert.NoError(t, err, "unable to get group") assert.Equal(t, group1.Issued, types.GroupIssuedAPI, "group should be api issued") }) @@ -2721,7 +2722,7 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 2, "groups count should not be change") }) @@ -2735,7 +2736,7 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 2, "groups count should not be change") }) @@ -2749,11 +2750,11 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - groups, err := manager.Store.GetAccountGroups(context.Background(), store.LockingStrengthShare, "accountID") + groups, err := manager.Store.GetAccountGroups(context.Background(), store.LockingStrengthNone, "accountID") assert.NoError(t, err) assert.Len(t, groups, 3, "new group3 should be added") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user2") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user2") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 1, "new group should be added") }) @@ -2767,7 +2768,7 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user1") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user1") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 1, "only non-JWT groups should remain") assert.Contains(t, user.AutoGroups, "group1", "group1 should still be present") @@ -2782,7 +2783,7 @@ func TestAccount_SetJWTGroups(t *testing.T) { err = manager.SyncUserJWTGroups(context.Background(), claims) assert.NoError(t, err, "unable to sync jwt groups") - user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthShare, "user2") + user, err := manager.Store.GetUserByUserID(context.Background(), store.LockingStrengthNone, "user2") assert.NoError(t, err, "unable to get user") assert.Len(t, user.AutoGroups, 0, "all JWT groups should be removed") }) @@ -3347,11 +3348,11 @@ func TestPropagateUserGroupMemberships(t *testing.T) { require.NoError(t, err) peer1 := &nbpeer.Peer{ID: "peer1", AccountID: account.Id, UserID: initiatorId, IP: net.IP{1, 1, 1, 1}, DNSLabel: "peer1.domain.test"} - err = manager.Store.AddPeerToAccount(ctx, store.LockingStrengthUpdate, peer1) + err = manager.Store.AddPeerToAccount(ctx, peer1) require.NoError(t, err) peer2 := &nbpeer.Peer{ID: "peer2", AccountID: account.Id, UserID: initiatorId, IP: net.IP{2, 2, 2, 2}, DNSLabel: "peer2.domain.test"} - err = manager.Store.AddPeerToAccount(ctx, store.LockingStrengthUpdate, peer2) + err = manager.Store.AddPeerToAccount(ctx, peer2) require.NoError(t, err) t.Run("should skip propagation when the user has no groups", func(t *testing.T) { @@ -3363,20 +3364,20 @@ 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.CreateGroup(ctx, store.LockingStrengthUpdate, group1)) + require.NoError(t, manager.Store.CreateGroup(ctx, group1)) - user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorId) + user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorId) require.NoError(t, err) user.AutoGroups = append(user.AutoGroups, group1.ID) - require.NoError(t, manager.Store.SaveUser(ctx, store.LockingStrengthUpdate, user)) + require.NoError(t, manager.Store.SaveUser(ctx, user)) groupsUpdated, groupChangesAffectPeers, err := propagateUserGroupMemberships(ctx, manager.Store, account.Id) require.NoError(t, err) assert.True(t, groupsUpdated) assert.False(t, groupChangesAffectPeers) - group, err := manager.Store.GetGroupByID(ctx, store.LockingStrengthShare, account.Id, group1.ID) + group, err := manager.Store.GetGroupByID(ctx, store.LockingStrengthNone, account.Id, group1.ID) require.NoError(t, err) assert.Len(t, group.Peers, 2) assert.Contains(t, group.Peers, "peer1") @@ -3385,13 +3386,13 @@ 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.CreateGroup(ctx, store.LockingStrengthUpdate, group2)) + require.NoError(t, manager.Store.CreateGroup(ctx, group2)) - user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorId) + user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorId) require.NoError(t, err) user.AutoGroups = append(user.AutoGroups, group2.ID) - require.NoError(t, manager.Store.SaveUser(ctx, store.LockingStrengthUpdate, user)) + require.NoError(t, manager.Store.SaveUser(ctx, user)) _, err = manager.SavePolicy(context.Background(), account.Id, initiatorId, &types.Policy{ Name: "Group1 Policy", @@ -3414,7 +3415,7 @@ func TestPropagateUserGroupMemberships(t *testing.T) { assert.True(t, groupsUpdated) assert.True(t, groupChangesAffectPeers) - groups, err := manager.Store.GetGroupsByIDs(ctx, store.LockingStrengthShare, account.Id, []string{"group1", "group2"}) + groups, err := manager.Store.GetGroupsByIDs(ctx, store.LockingStrengthNone, account.Id, []string{"group1", "group2"}) require.NoError(t, err) for _, group := range groups { assert.Len(t, group.Peers, 2) @@ -3431,18 +3432,18 @@ func TestPropagateUserGroupMemberships(t *testing.T) { }) t.Run("should not remove peers when groups are removed from user", func(t *testing.T) { - user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorId) + user, err := manager.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorId) require.NoError(t, err) user.AutoGroups = []string{"group1"} - require.NoError(t, manager.Store.SaveUser(ctx, store.LockingStrengthUpdate, user)) + require.NoError(t, manager.Store.SaveUser(ctx, user)) groupsUpdated, groupChangesAffectPeers, err := propagateUserGroupMemberships(ctx, manager.Store, account.Id) require.NoError(t, err) assert.False(t, groupsUpdated) assert.False(t, groupChangesAffectPeers) - groups, err := manager.Store.GetGroupsByIDs(ctx, store.LockingStrengthShare, account.Id, []string{"group1", "group2"}) + groups, err := manager.Store.GetGroupsByIDs(ctx, store.LockingStrengthNone, account.Id, []string{"group1", "group2"}) require.NoError(t, err) for _, group := range groups { assert.Len(t, group.Peers, 2) @@ -3522,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/auth/manager.go b/management/server/auth/manager.go index 6835a3ced..53d479c90 100644 --- a/management/server/auth/manager.go +++ b/management/server/auth/manager.go @@ -73,7 +73,7 @@ func (m *manager) EnsureUserAccessByJWTGroups(ctx context.Context, userAuth nbco return userAuth, nil } - settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthShare, userAuth.AccountId) + settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthNone, userAuth.AccountId) if err != nil { return userAuth, err } @@ -94,7 +94,7 @@ func (m *manager) EnsureUserAccessByJWTGroups(ctx context.Context, userAuth nbco // MarkPATUsed marks a personal access token as used func (am *manager) MarkPATUsed(ctx context.Context, tokenID string) error { - return am.store.MarkPATUsed(ctx, store.LockingStrengthUpdate, tokenID) + return am.store.MarkPATUsed(ctx, tokenID) } // GetPATInfo retrieves user, personal access token, domain, and category details from a personal access token. @@ -104,7 +104,7 @@ func (am *manager) GetPATInfo(ctx context.Context, token string) (user *types.Us return nil, nil, "", "", err } - domain, category, err = am.store.GetAccountDomainAndCategory(ctx, store.LockingStrengthShare, user.AccountID) + domain, category, err = am.store.GetAccountDomainAndCategory(ctx, store.LockingStrengthNone, user.AccountID) if err != nil { return nil, nil, "", "", err } @@ -142,12 +142,12 @@ func (am *manager) extractPATFromToken(ctx context.Context, token string) (*type var pat *types.PersonalAccessToken err = am.store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - pat, err = transaction.GetPATByHashedToken(ctx, store.LockingStrengthShare, encodedHashedToken) + pat, err = transaction.GetPATByHashedToken(ctx, store.LockingStrengthNone, encodedHashedToken) if err != nil { return err } - user, err = transaction.GetUserByPATID(ctx, store.LockingStrengthShare, pat.ID) + user, err = transaction.GetUserByPATID(ctx, store.LockingStrengthNone, pat.ID) return err }) if err != nil { 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..12aa6e21c 100644 --- a/management/server/dns.go +++ b/management/server/dns.go @@ -8,14 +8,14 @@ import ( log "github.com/sirupsen/logrus" nbdns "github.com/netbirdio/netbird/dns" - "github.com/netbirdio/netbird/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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/util" + "github.com/netbirdio/netbird/shared/management/proto" + "github.com/netbirdio/netbird/shared/management/status" ) // DNSConfigCache is a thread-safe cache for DNS configuration components @@ -72,7 +72,7 @@ func (am *DefaultAccountManager) GetDNSSettings(ctx context.Context, accountID s return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountDNSSettings(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountDNSSettings(ctx, store.LockingStrengthNone, accountID) } // SaveDNSSettings validates a user role and updates the account's DNS settings @@ -113,11 +113,11 @@ func (am *DefaultAccountManager) SaveDNSSettings(ctx context.Context, accountID events := am.prepareDNSSettingsEvents(ctx, transaction, accountID, userID, addedGroups, removedGroups) eventsToStore = append(eventsToStore, events...) - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.SaveDNSSettings(ctx, store.LockingStrengthUpdate, accountID, dnsSettingsToSave) + return transaction.SaveDNSSettings(ctx, accountID, dnsSettingsToSave) }) if err != nil { return err @@ -139,7 +139,7 @@ func (am *DefaultAccountManager) prepareDNSSettingsEvents(ctx context.Context, t var eventsToStore []func() modifiedGroups := slices.Concat(addedGroups, removedGroups) - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, modifiedGroups) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, modifiedGroups) if err != nil { log.WithContext(ctx).Debugf("failed to get groups for dns settings events: %v", err) return nil @@ -195,7 +195,7 @@ func validateDNSSettings(ctx context.Context, transaction store.Store, accountID return nil } - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, settings.DisabledManagementGroups) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, settings.DisabledManagementGroups) if err != nil { return err } diff --git a/management/server/dns_test.go b/management/server/dns_test.go index 2af07d8e4..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 ( diff --git a/management/server/ephemeral.go b/management/server/ephemeral.go index 9f4348ebb..e3cb5459a 100644 --- a/management/server/ephemeral.go +++ b/management/server/ephemeral.go @@ -134,7 +134,7 @@ func (e *EphemeralManager) OnPeerDisconnected(ctx context.Context, peer *nbpeer. } func (e *EphemeralManager) loadEphemeralPeers(ctx context.Context) { - peers, err := e.store.GetAllEphemeralPeers(ctx, store.LockingStrengthShare) + peers, err := e.store.GetAllEphemeralPeers(ctx, store.LockingStrengthNone) if err != nil { log.WithContext(ctx).Debugf("failed to load ephemeral peers: %s", err) return 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..d26c569ae 100644 --- a/management/server/event.go +++ b/management/server/event.go @@ -11,9 +11,9 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/status" ) func isEnabled() bool { @@ -103,7 +103,7 @@ func (am *DefaultAccountManager) fillEventsWithUserInfo(ctx context.Context, eve } func (am *DefaultAccountManager) getEventsUserInfo(ctx context.Context, events []*activity.Event, accountId string, userId string) (map[string]eventUserInfo, error) { - accountUsers, err := am.Store.GetAccountUsers(ctx, store.LockingStrengthShare, accountId) + accountUsers, err := am.Store.GetAccountUsers(ctx, store.LockingStrengthNone, accountId) if err != nil { return nil, err } @@ -154,7 +154,7 @@ func (am *DefaultAccountManager) getEventsExternalUserInfo(ctx context.Context, continue } - externalUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, id) + externalUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, id) if err != nil { // @todo consider logging continue 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 95bed7d18..915a87086 100644 --- a/management/server/group.go +++ b/management/server/group.go @@ -14,11 +14,11 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/util" "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/status" ) type GroupLinkError struct { @@ -49,7 +49,7 @@ func (am *DefaultAccountManager) GetGroup(ctx context.Context, accountID, groupI if err := am.CheckGroupPermissions(ctx, accountID, userID); err != nil { return nil, err } - return am.Store.GetGroupByID(ctx, store.LockingStrengthShare, accountID, groupID) + return am.Store.GetGroupByID(ctx, store.LockingStrengthNone, accountID, groupID) } // GetAllGroups returns all groups in an account @@ -57,12 +57,12 @@ func (am *DefaultAccountManager) GetAllGroups(ctx context.Context, accountID, us if err := am.CheckGroupPermissions(ctx, accountID, userID); err != nil { return nil, err } - return am.Store.GetAccountGroups(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountGroups(ctx, store.LockingStrengthNone, accountID) } // GetGroupByName filters all groups in an account by name and returns the one with the most peers func (am *DefaultAccountManager) GetGroupByName(ctx context.Context, groupName, accountID string) (*types.Group, error) { - return am.Store.GetGroupByName(ctx, store.LockingStrengthShare, accountID, groupName) + return am.Store.GetGroupByName(ctx, store.LockingStrengthNone, accountID, groupName) } // CreateGroup object of the peers @@ -96,11 +96,11 @@ func (am *DefaultAccountManager) CreateGroup(ctx context.Context, accountID, use return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - if err := transaction.CreateGroup(ctx, store.LockingStrengthUpdate, newGroup); err != nil { + if err := transaction.CreateGroup(ctx, newGroup); err != nil { return status.Errorf(status.Internal, "failed to create group: %v", err) } @@ -147,7 +147,7 @@ func (am *DefaultAccountManager) UpdateGroup(ctx context.Context, accountID, use return err } - oldGroup, err := transaction.GetGroupByID(ctx, store.LockingStrengthShare, accountID, newGroup.ID) + oldGroup, err := transaction.GetGroupByID(ctx, store.LockingStrengthNone, accountID, newGroup.ID) if err != nil { return status.Errorf(status.NotFound, "group with ID %s not found", newGroup.ID) } @@ -176,11 +176,11 @@ func (am *DefaultAccountManager) UpdateGroup(ctx context.Context, accountID, use return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.UpdateGroup(ctx, store.LockingStrengthUpdate, newGroup) + return transaction.UpdateGroup(ctx, newGroup) }) if err != nil { return err @@ -234,11 +234,11 @@ func (am *DefaultAccountManager) CreateGroups(ctx context.Context, accountID, us return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.CreateGroups(ctx, store.LockingStrengthUpdate, accountID, groupsToSave) + return transaction.CreateGroups(ctx, accountID, groupsToSave) }) if err != nil { return err @@ -292,11 +292,11 @@ func (am *DefaultAccountManager) UpdateGroups(ctx context.Context, accountID, us return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.UpdateGroups(ctx, store.LockingStrengthUpdate, accountID, groupsToSave) + return transaction.UpdateGroups(ctx, accountID, groupsToSave) }) if err != nil { return err @@ -320,7 +320,7 @@ func (am *DefaultAccountManager) prepareGroupEvents(ctx context.Context, transac addedPeers := make([]string, 0) removedPeers := make([]string, 0) - oldGroup, err := transaction.GetGroupByID(ctx, store.LockingStrengthShare, accountID, newGroup.ID) + oldGroup, err := transaction.GetGroupByID(ctx, store.LockingStrengthNone, accountID, newGroup.ID) if err == nil && oldGroup != nil { addedPeers = util.Difference(newGroup.Peers, oldGroup.Peers) removedPeers = util.Difference(oldGroup.Peers, newGroup.Peers) @@ -332,13 +332,13 @@ func (am *DefaultAccountManager) prepareGroupEvents(ctx context.Context, transac } modifiedPeers := slices.Concat(addedPeers, removedPeers) - peers, err := transaction.GetPeersByIDs(ctx, store.LockingStrengthShare, accountID, modifiedPeers) + peers, err := transaction.GetPeersByIDs(ctx, store.LockingStrengthNone, accountID, modifiedPeers) if err != nil { log.WithContext(ctx).Debugf("failed to get peers for group events: %v", err) return nil } - settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Debugf("failed to get account settings for group events: %v", err) return nil @@ -423,11 +423,11 @@ func (am *DefaultAccountManager) DeleteGroups(ctx context.Context, accountID, us deletedGroups = append(deletedGroups, group) } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.DeleteGroups(ctx, store.LockingStrengthUpdate, accountID, groupIDsToDelete) + return transaction.DeleteGroups(ctx, accountID, groupIDsToDelete) }) if err != nil { return err @@ -454,7 +454,7 @@ func (am *DefaultAccountManager) GroupAddPeer(ctx context.Context, accountID, gr return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } @@ -495,11 +495,11 @@ func (am *DefaultAccountManager) GroupAddResource(ctx context.Context, accountID return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.UpdateGroup(ctx, store.LockingStrengthUpdate, group) + return transaction.UpdateGroup(ctx, group) }) if err != nil { return err @@ -526,7 +526,7 @@ func (am *DefaultAccountManager) GroupDeletePeer(ctx context.Context, accountID, return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } @@ -567,11 +567,11 @@ func (am *DefaultAccountManager) GroupDeleteResource(ctx context.Context, accoun return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.UpdateGroup(ctx, store.LockingStrengthUpdate, group) + return transaction.UpdateGroup(ctx, group) }) if err != nil { return err @@ -591,7 +591,7 @@ func validateNewGroup(ctx context.Context, transaction store.Store, accountID st } if newGroup.ID == "" && newGroup.Issued == types.GroupIssuedAPI { - existingGroup, err := transaction.GetGroupByName(ctx, store.LockingStrengthShare, accountID, newGroup.Name) + existingGroup, err := transaction.GetGroupByName(ctx, store.LockingStrengthNone, accountID, newGroup.Name) if err != nil { if s, ok := status.FromError(err); !ok || s.Type() != status.NotFound { return err @@ -608,7 +608,7 @@ func validateNewGroup(ctx context.Context, transaction store.Store, accountID st } for _, peerID := range newGroup.Peers { - _, err := transaction.GetPeerByID(ctx, store.LockingStrengthShare, accountID, peerID) + _, err := transaction.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID) if err != nil { return status.Errorf(status.InvalidArgument, "peer with ID \"%s\" not found", peerID) } @@ -620,7 +620,7 @@ func validateNewGroup(ctx context.Context, transaction store.Store, accountID st func validateDeleteGroup(ctx context.Context, transaction store.Store, group *types.Group, userID string) error { // disable a deleting integration group if the initiator is not an admin service user if group.Issued == types.GroupIssuedIntegration { - executingUser, err := transaction.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + executingUser, err := transaction.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { return status.Errorf(status.Internal, "failed to get user") } @@ -666,7 +666,7 @@ func validateDeleteGroup(ctx context.Context, transaction store.Store, group *ty // checkGroupLinkedToSettings verifies if a group is linked to any settings in the account. func checkGroupLinkedToSettings(ctx context.Context, transaction store.Store, group *types.Group) error { - dnsSettings, err := transaction.GetAccountDNSSettings(ctx, store.LockingStrengthShare, group.AccountID) + dnsSettings, err := transaction.GetAccountDNSSettings(ctx, store.LockingStrengthNone, group.AccountID) if err != nil { return status.Errorf(status.Internal, "failed to get DNS settings") } @@ -675,7 +675,7 @@ func checkGroupLinkedToSettings(ctx context.Context, transaction store.Store, gr return &GroupLinkError{"disabled DNS management groups", group.Name} } - settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthShare, group.AccountID) + settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthNone, group.AccountID) if err != nil { return status.Errorf(status.Internal, "failed to get account settings") } @@ -689,7 +689,7 @@ func checkGroupLinkedToSettings(ctx context.Context, transaction store.Store, gr // isGroupLinkedToRoute checks if a group is linked to any route in the account. func isGroupLinkedToRoute(ctx context.Context, transaction store.Store, accountID string, groupID string) (bool, *route.Route) { - routes, err := transaction.GetAccountRoutes(ctx, store.LockingStrengthShare, accountID) + routes, err := transaction.GetAccountRoutes(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving routes while checking group linkage: %v", err) return false, nil @@ -709,7 +709,7 @@ func isGroupLinkedToRoute(ctx context.Context, transaction store.Store, accountI // isGroupLinkedToPolicy checks if a group is linked to any policy in the account. func isGroupLinkedToPolicy(ctx context.Context, transaction store.Store, accountID string, groupID string) (bool, *types.Policy) { - policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthShare, accountID) + policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving policies while checking group linkage: %v", err) return false, nil @@ -727,7 +727,7 @@ func isGroupLinkedToPolicy(ctx context.Context, transaction store.Store, account // isGroupLinkedToDns checks if a group is linked to any nameserver group in the account. func isGroupLinkedToDns(ctx context.Context, transaction store.Store, accountID string, groupID string) (bool, *nbdns.NameServerGroup) { - nameServerGroups, err := transaction.GetAccountNameServerGroups(ctx, store.LockingStrengthShare, accountID) + nameServerGroups, err := transaction.GetAccountNameServerGroups(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving name server groups while checking group linkage: %v", err) return false, nil @@ -746,7 +746,7 @@ func isGroupLinkedToDns(ctx context.Context, transaction store.Store, accountID // isGroupLinkedToSetupKey checks if a group is linked to any setup key in the account. func isGroupLinkedToSetupKey(ctx context.Context, transaction store.Store, accountID string, groupID string) (bool, *types.SetupKey) { - setupKeys, err := transaction.GetAccountSetupKeys(ctx, store.LockingStrengthShare, accountID) + setupKeys, err := transaction.GetAccountSetupKeys(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving setup keys while checking group linkage: %v", err) return false, nil @@ -762,7 +762,7 @@ func isGroupLinkedToSetupKey(ctx context.Context, transaction store.Store, accou // isGroupLinkedToUser checks if a group is linked to any user in the account. func isGroupLinkedToUser(ctx context.Context, transaction store.Store, accountID string, groupID string) (bool, *types.User) { - users, err := transaction.GetAccountUsers(ctx, store.LockingStrengthShare, accountID) + users, err := transaction.GetAccountUsers(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving users while checking group linkage: %v", err) return false, nil @@ -778,7 +778,7 @@ func isGroupLinkedToUser(ctx context.Context, transaction store.Store, accountID // isGroupLinkedToNetworkRouter checks if a group is linked to any network router in the account. func isGroupLinkedToNetworkRouter(ctx context.Context, transaction store.Store, accountID string, groupID string) (bool, *routerTypes.NetworkRouter) { - routers, err := transaction.GetNetworkRoutersByAccountID(ctx, store.LockingStrengthShare, accountID) + routers, err := transaction.GetNetworkRoutersByAccountID(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving network routers while checking group linkage: %v", err) return false, nil @@ -798,7 +798,7 @@ func areGroupChangesAffectPeers(ctx context.Context, transaction store.Store, ac return false, nil } - dnsSettings, err := transaction.GetAccountDNSSettings(ctx, store.LockingStrengthShare, accountID) + dnsSettings, err := transaction.GetAccountDNSSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return false, err } @@ -826,7 +826,7 @@ func areGroupChangesAffectPeers(ctx context.Context, transaction store.Store, ac // anyGroupHasPeersOrResources checks if any of the given groups in the account have peers or resources. func anyGroupHasPeersOrResources(ctx context.Context, transaction store.Store, accountID string, groupIDs []string) (bool, error) { - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, groupIDs) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, groupIDs) if err != nil { return false, err } diff --git a/management/server/group_test.go b/management/server/group_test.go index 51069dc56..1626a0464 100644 --- a/management/server/group_test.go +++ b/management/server/group_test.go @@ -26,10 +26,10 @@ import ( 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/status" ) const ( @@ -898,7 +898,7 @@ func Test_AddPeerAndAddToAll(t *testing.T) { } err = manager.Store.ExecuteInTransaction(context.Background(), func(transaction store.Store) error { - err = transaction.AddPeerToAccount(context.Background(), store.LockingStrengthUpdate, peer) + err = transaction.AddPeerToAccount(context.Background(), peer) if err != nil { return fmt.Errorf("AddPeer failed for peer %d: %w", i, err) } @@ -971,7 +971,7 @@ func Test_IncrementNetworkSerial(t *testing.T) { <-start err = manager.Store.ExecuteInTransaction(context.Background(), func(transaction store.Store) error { - err = transaction.IncrementNetworkSerial(context.Background(), store.LockingStrengthNone, accountID) + err = transaction.IncrementNetworkSerial(context.Background(), accountID) if err != nil { return fmt.Errorf("failed to get account %s: %v", accountID, err) } diff --git a/management/server/groups/manager.go b/management/server/groups/manager.go index df4b6c3d6..dd11f862f 100644 --- a/management/server/groups/manager.go +++ b/management/server/groups/manager.go @@ -6,12 +6,12 @@ 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/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/store" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/http/api" ) type Manager interface { @@ -49,7 +49,7 @@ func (m *managerImpl) GetAllGroups(ctx context.Context, accountID, userID string return nil, err } - groups, err := m.store.GetAccountGroups(ctx, store.LockingStrengthShare, accountID) + groups, err := m.store.GetAccountGroups(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("error getting account groups: %w", err) } @@ -96,13 +96,13 @@ func (m *managerImpl) AddResourceToGroupInTransaction(ctx context.Context, trans return nil, fmt.Errorf("error adding resource to group: %w", err) } - group, err := transaction.GetGroupByID(ctx, store.LockingStrengthShare, accountID, groupID) + group, err := transaction.GetGroupByID(ctx, store.LockingStrengthNone, accountID, groupID) if err != nil { return nil, fmt.Errorf("error getting group: %w", err) } // TODO: at some point, this will need to become a switch statement - networkResource, err := transaction.GetNetworkResourceByID(ctx, store.LockingStrengthShare, accountID, resource.ID) + networkResource, err := transaction.GetNetworkResourceByID(ctx, store.LockingStrengthNone, accountID, resource.ID) if err != nil { return nil, fmt.Errorf("error getting network resource: %w", err) } @@ -120,13 +120,13 @@ func (m *managerImpl) RemoveResourceFromGroupInTransaction(ctx context.Context, return nil, fmt.Errorf("error removing resource from group: %w", err) } - group, err := transaction.GetGroupByID(ctx, store.LockingStrengthShare, accountID, groupID) + group, err := transaction.GetGroupByID(ctx, store.LockingStrengthNone, accountID, groupID) if err != nil { return nil, fmt.Errorf("error getting group: %w", err) } // TODO: at some point, this will need to become a switch statement - networkResource, err := transaction.GetNetworkResourceByID(ctx, store.LockingStrengthShare, accountID, resourceID) + networkResource, err := transaction.GetNetworkResourceByID(ctx, store.LockingStrengthNone, accountID, resourceID) if err != nil { return nil, fmt.Errorf("error getting network resource: %w", err) } diff --git a/management/server/grpcserver.go b/management/server/grpcserver.go index 2f1bc3673..782e46948 100644 --- a/management/server/grpcserver.go +++ b/management/server/grpcserver.go @@ -19,10 +19,11 @@ 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/management/server/account" "github.com/netbirdio/netbird/management/server/activity" "github.com/netbirdio/netbird/management/server/auth" @@ -30,9 +31,10 @@ 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" "github.com/netbirdio/netbird/management/server/telemetry" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/proto" + internalStatus "github.com/netbirdio/netbird/shared/management/status" ) // GRPCServer an instance of a Management gRPC API server @@ -909,6 +911,45 @@ 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) + start := time.Now() + + empty := &proto.Empty{} + peerKey, err := s.parseRequest(ctx, req, empty) + if err != nil { + return nil, err + } + + peer, err := s.accountManager.GetStore().GetPeerByPeerPubKey(ctx, store.LockingStrengthNone, 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).Debugf("peer %s logged out successfully after %s", peerKey.String(), time.Since(start)) + + 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 bede652f5..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" ) 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..73abacc36 100644 --- a/management/server/integrated_validator.go +++ b/management/server/integrated_validator.go @@ -77,7 +77,7 @@ func (am *DefaultAccountManager) GroupValidation(ctx context.Context, accountID err := am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { for _, groupID := range groupIDs { - _, err := transaction.GetGroupByID(context.Background(), store.LockingStrengthShare, accountID, groupID) + _, err := transaction.GetGroupByID(context.Background(), store.LockingStrengthNone, accountID, groupID) if err != nil { return err } @@ -97,17 +97,17 @@ func (am *DefaultAccountManager) GetValidatedPeers(ctx context.Context, accountI var peers []*nbpeer.Peer var settings *types.Settings - groups, err = am.Store.GetAccountGroups(ctx, store.LockingStrengthShare, accountID) + groups, err = am.Store.GetAccountGroups(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } - peers, err = am.Store.GetAccountPeers(ctx, store.LockingStrengthShare, accountID, "", "") + peers, err = am.Store.GetAccountPeers(ctx, store.LockingStrengthNone, accountID, "", "") if err != nil { return nil, err } - settings, err = am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err = am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -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..c9f8b5448 100644 --- a/management/server/management_proto_test.go +++ b/management/server/management_proto_test.go @@ -22,7 +22,6 @@ import ( "github.com/netbirdio/netbird/encryption" "github.com/netbirdio/netbird/formatter/hook" - mgmtProto "github.com/netbirdio/netbird/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" @@ -30,6 +29,7 @@ import ( "github.com/netbirdio/netbird/management/server/store" "github.com/netbirdio/netbird/management/server/telemetry" "github.com/netbirdio/netbird/management/server/types" + mgmtProto "github.com/netbirdio/netbird/shared/management/proto" "github.com/netbirdio/netbird/util" ) @@ -645,7 +645,7 @@ func testSyncStatusRace(t *testing.T) { } time.Sleep(10 * time.Millisecond) - peer, err := am.Store.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthShare, peerWithInvalidStatus.PublicKey().String()) + peer, err := am.Store.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthNone, peerWithInvalidStatus.PublicKey().String()) if err != nil { t.Fatal(err) return 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 88af9a58f..78f4afbd5 100644 --- a/management/server/migration/migration.go +++ b/management/server/migration/migration.go @@ -15,6 +15,7 @@ import ( log "github.com/sirupsen/logrus" "gorm.io/gorm" + "gorm.io/gorm/clause" ) func GetColumnName(db *gorm.DB, column string) string { @@ -466,7 +467,7 @@ func MigrateJsonToTable[T any](ctx context.Context, db *gorm.DB, columnName stri } for _, value := range data { - if err := tx.Create( + if err := tx.Clauses(clause.OnConflict{DoNothing: true}).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) diff --git a/management/server/mock_server/account_mock.go b/management/server/mock_server/account_mock.go index 8c8fd19c9..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 @@ -483,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..1ee8805fc 100644 --- a/management/server/nameserver.go +++ b/management/server/nameserver.go @@ -13,9 +13,9 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/status" ) const domainPattern = `^(?i)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*[*.a-z]{1,}$` @@ -32,7 +32,7 @@ func (am *DefaultAccountManager) GetNameServerGroup(ctx context.Context, account return nil, status.NewPermissionDeniedError() } - return am.Store.GetNameServerGroupByID(ctx, store.LockingStrengthShare, accountID, nsGroupID) + return am.Store.GetNameServerGroupByID(ctx, store.LockingStrengthNone, accountID, nsGroupID) } // CreateNameServerGroup creates and saves a new nameserver group @@ -73,11 +73,11 @@ func (am *DefaultAccountManager) CreateNameServerGroup(ctx context.Context, acco return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.SaveNameServerGroup(ctx, store.LockingStrengthUpdate, newNSGroup) + return transaction.SaveNameServerGroup(ctx, newNSGroup) }) if err != nil { return nil, err @@ -112,7 +112,7 @@ func (am *DefaultAccountManager) SaveNameServerGroup(ctx context.Context, accoun var updateAccountPeers bool err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - oldNSGroup, err := transaction.GetNameServerGroupByID(ctx, store.LockingStrengthShare, accountID, nsGroupToSave.ID) + oldNSGroup, err := transaction.GetNameServerGroupByID(ctx, store.LockingStrengthNone, accountID, nsGroupToSave.ID) if err != nil { return err } @@ -127,11 +127,11 @@ func (am *DefaultAccountManager) SaveNameServerGroup(ctx context.Context, accoun return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.SaveNameServerGroup(ctx, store.LockingStrengthUpdate, nsGroupToSave) + return transaction.SaveNameServerGroup(ctx, nsGroupToSave) }) if err != nil { return err @@ -173,11 +173,11 @@ func (am *DefaultAccountManager) DeleteNameServerGroup(ctx context.Context, acco return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.DeleteNameServerGroup(ctx, store.LockingStrengthUpdate, accountID, nsGroupID) + return transaction.DeleteNameServerGroup(ctx, accountID, nsGroupID) }) if err != nil { return err @@ -202,7 +202,7 @@ func (am *DefaultAccountManager) ListNameServerGroups(ctx context.Context, accou return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountNameServerGroups(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountNameServerGroups(ctx, store.LockingStrengthNone, accountID) } func validateNameServerGroup(ctx context.Context, transaction store.Store, accountID string, nameserverGroup *nbdns.NameServerGroup) error { @@ -216,7 +216,7 @@ func validateNameServerGroup(ctx context.Context, transaction store.Store, accou return err } - nsServerGroups, err := transaction.GetAccountNameServerGroups(ctx, store.LockingStrengthShare, accountID) + nsServerGroups, err := transaction.GetAccountNameServerGroups(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } @@ -226,7 +226,7 @@ func validateNameServerGroup(ctx context.Context, transaction store.Store, accou return err } - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, nameserverGroup.Groups) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, nameserverGroup.Groups) if err != nil { return err } diff --git a/management/server/networks/manager.go b/management/server/networks/manager.go index 1c46e9281..2bab0e289 100644 --- a/management/server/networks/manager.go +++ b/management/server/networks/manager.go @@ -14,8 +14,8 @@ 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/management/server/store" + "github.com/netbirdio/netbird/shared/management/status" ) type Manager interface { @@ -56,7 +56,7 @@ func (m *managerImpl) GetAllNetworks(ctx context.Context, accountID, userID stri return nil, status.NewPermissionDeniedError() } - return m.store.GetAccountNetworks(ctx, store.LockingStrengthShare, accountID) + return m.store.GetAccountNetworks(ctx, store.LockingStrengthNone, accountID) } func (m *managerImpl) CreateNetwork(ctx context.Context, userID string, network *types.Network) (*types.Network, error) { @@ -73,7 +73,7 @@ func (m *managerImpl) CreateNetwork(ctx context.Context, userID string, network unlock := m.store.AcquireWriteLockByUID(ctx, network.AccountID) defer unlock() - err = m.store.SaveNetwork(ctx, store.LockingStrengthUpdate, network) + err = m.store.SaveNetwork(ctx, network) if err != nil { return nil, fmt.Errorf("failed to save network: %w", err) } @@ -92,7 +92,7 @@ func (m *managerImpl) GetNetwork(ctx context.Context, accountID, userID, network return nil, status.NewPermissionDeniedError() } - return m.store.GetNetworkByID(ctx, store.LockingStrengthShare, accountID, networkID) + return m.store.GetNetworkByID(ctx, store.LockingStrengthNone, accountID, networkID) } func (m *managerImpl) UpdateNetwork(ctx context.Context, userID string, network *types.Network) (*types.Network, error) { @@ -114,7 +114,7 @@ func (m *managerImpl) UpdateNetwork(ctx context.Context, userID string, network m.accountManager.StoreEvent(ctx, userID, network.ID, network.AccountID, activity.NetworkUpdated, network.EventMeta()) - return network, m.store.SaveNetwork(ctx, store.LockingStrengthUpdate, network) + return network, m.store.SaveNetwork(ctx, network) } func (m *managerImpl) DeleteNetwork(ctx context.Context, accountID, userID, networkID string) error { @@ -162,12 +162,12 @@ func (m *managerImpl) DeleteNetwork(ctx context.Context, accountID, userID, netw eventsToStore = append(eventsToStore, event) } - err = transaction.DeleteNetwork(ctx, store.LockingStrengthUpdate, accountID, networkID) + err = transaction.DeleteNetwork(ctx, accountID, networkID) if err != nil { return fmt.Errorf("failed to delete network: %w", err) } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID) + err = transaction.IncrementNetworkSerial(ctx, accountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } diff --git a/management/server/networks/resources/manager.go b/management/server/networks/resources/manager.go index 21d1e54de..d0b29075b 100644 --- a/management/server/networks/resources/manager.go +++ b/management/server/networks/resources/manager.go @@ -12,10 +12,10 @@ 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/management/server/store" nbtypes "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/util" + "github.com/netbirdio/netbird/shared/management/status" ) type Manager interface { @@ -57,7 +57,7 @@ func (m *managerImpl) GetAllResourcesInNetwork(ctx context.Context, accountID, u return nil, status.NewPermissionDeniedError() } - return m.store.GetNetworkResourcesByNetID(ctx, store.LockingStrengthShare, accountID, networkID) + return m.store.GetNetworkResourcesByNetID(ctx, store.LockingStrengthNone, accountID, networkID) } func (m *managerImpl) GetAllResourcesInAccount(ctx context.Context, accountID, userID string) ([]*types.NetworkResource, error) { @@ -69,7 +69,7 @@ func (m *managerImpl) GetAllResourcesInAccount(ctx context.Context, accountID, u return nil, status.NewPermissionDeniedError() } - return m.store.GetNetworkResourcesByAccountID(ctx, store.LockingStrengthShare, accountID) + return m.store.GetNetworkResourcesByAccountID(ctx, store.LockingStrengthNone, accountID) } func (m *managerImpl) GetAllResourceIDsInAccount(ctx context.Context, accountID, userID string) (map[string][]string, error) { @@ -81,7 +81,7 @@ func (m *managerImpl) GetAllResourceIDsInAccount(ctx context.Context, accountID, return nil, status.NewPermissionDeniedError() } - resources, err := m.store.GetNetworkResourcesByAccountID(ctx, store.LockingStrengthShare, accountID) + resources, err := m.store.GetNetworkResourcesByAccountID(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("failed to get network resources: %w", err) } @@ -113,7 +113,7 @@ func (m *managerImpl) CreateResource(ctx context.Context, userID string, resourc var eventsToStore []func() err = m.store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - _, err = transaction.GetNetworkResourceByName(ctx, store.LockingStrengthShare, resource.AccountID, resource.Name) + _, err = transaction.GetNetworkResourceByName(ctx, store.LockingStrengthNone, resource.AccountID, resource.Name) if err == nil { return status.Errorf(status.InvalidArgument, "resource with name %s already exists", resource.Name) } @@ -123,7 +123,7 @@ func (m *managerImpl) CreateResource(ctx context.Context, userID string, resourc return fmt.Errorf("failed to get network: %w", err) } - err = transaction.SaveNetworkResource(ctx, store.LockingStrengthUpdate, resource) + err = transaction.SaveNetworkResource(ctx, resource) if err != nil { return fmt.Errorf("failed to save network resource: %w", err) } @@ -145,7 +145,7 @@ func (m *managerImpl) CreateResource(ctx context.Context, userID string, resourc eventsToStore = append(eventsToStore, event) } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, resource.AccountID) + err = transaction.IncrementNetworkSerial(ctx, resource.AccountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -174,7 +174,7 @@ func (m *managerImpl) GetResource(ctx context.Context, accountID, userID, networ return nil, status.NewPermissionDeniedError() } - resource, err := m.store.GetNetworkResourceByID(ctx, store.LockingStrengthShare, accountID, resourceID) + resource, err := m.store.GetNetworkResourceByID(ctx, store.LockingStrengthNone, accountID, resourceID) if err != nil { return nil, fmt.Errorf("failed to get network resource: %w", err) } @@ -218,22 +218,22 @@ func (m *managerImpl) UpdateResource(ctx context.Context, userID string, resourc return status.NewResourceNotPartOfNetworkError(resource.ID, resource.NetworkID) } - _, err = transaction.GetNetworkResourceByID(ctx, store.LockingStrengthShare, resource.AccountID, resource.ID) + _, err = transaction.GetNetworkResourceByID(ctx, store.LockingStrengthNone, resource.AccountID, resource.ID) if err != nil { return fmt.Errorf("failed to get network resource: %w", err) } - oldResource, err := transaction.GetNetworkResourceByName(ctx, store.LockingStrengthShare, resource.AccountID, resource.Name) + oldResource, err := transaction.GetNetworkResourceByName(ctx, store.LockingStrengthNone, resource.AccountID, resource.Name) if err == nil && oldResource.ID != resource.ID { return status.Errorf(status.InvalidArgument, "new resource name already exists") } - oldResource, err = transaction.GetNetworkResourceByID(ctx, store.LockingStrengthShare, resource.AccountID, resource.ID) + oldResource, err = transaction.GetNetworkResourceByID(ctx, store.LockingStrengthNone, resource.AccountID, resource.ID) if err != nil { return fmt.Errorf("failed to get network resource: %w", err) } - err = transaction.SaveNetworkResource(ctx, store.LockingStrengthUpdate, resource) + err = transaction.SaveNetworkResource(ctx, resource) if err != nil { return fmt.Errorf("failed to save network resource: %w", err) } @@ -248,7 +248,7 @@ func (m *managerImpl) UpdateResource(ctx context.Context, userID string, resourc m.accountManager.StoreEvent(ctx, userID, resource.ID, resource.AccountID, activity.NetworkResourceUpdated, resource.EventMeta(network)) }) - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, resource.AccountID) + err = transaction.IncrementNetworkSerial(ctx, resource.AccountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -325,7 +325,7 @@ func (m *managerImpl) DeleteResource(ctx context.Context, accountID, userID, net return fmt.Errorf("failed to delete resource: %w", err) } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID) + err = transaction.IncrementNetworkSerial(ctx, accountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -375,7 +375,7 @@ func (m *managerImpl) DeleteResourceInTransaction(ctx context.Context, transacti eventsToStore = append(eventsToStore, event) } - err = transaction.DeleteNetworkResource(ctx, store.LockingStrengthUpdate, accountID, resourceID) + err = transaction.DeleteNetworkResource(ctx, accountID, resourceID) if err != nil { return nil, fmt.Errorf("failed to delete network resource: %w", err) } 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..ca99e4fd1 100644 --- a/management/server/networks/routers/manager.go +++ b/management/server/networks/routers/manager.go @@ -14,8 +14,8 @@ 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/management/server/store" + "github.com/netbirdio/netbird/shared/management/status" ) type Manager interface { @@ -54,7 +54,7 @@ func (m *managerImpl) GetAllRoutersInNetwork(ctx context.Context, accountID, use return nil, status.NewPermissionDeniedError() } - return m.store.GetNetworkRoutersByNetID(ctx, store.LockingStrengthShare, accountID, networkID) + return m.store.GetNetworkRoutersByNetID(ctx, store.LockingStrengthNone, accountID, networkID) } func (m *managerImpl) GetAllRoutersInAccount(ctx context.Context, accountID, userID string) (map[string][]*types.NetworkRouter, error) { @@ -66,7 +66,7 @@ func (m *managerImpl) GetAllRoutersInAccount(ctx context.Context, accountID, use return nil, status.NewPermissionDeniedError() } - routers, err := m.store.GetNetworkRoutersByAccountID(ctx, store.LockingStrengthShare, accountID) + routers, err := m.store.GetNetworkRoutersByAccountID(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("failed to get network routers: %w", err) } @@ -93,7 +93,7 @@ func (m *managerImpl) CreateRouter(ctx context.Context, userID string, router *t var network *networkTypes.Network err = m.store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - network, err = transaction.GetNetworkByID(ctx, store.LockingStrengthShare, router.AccountID, router.NetworkID) + network, err = transaction.GetNetworkByID(ctx, store.LockingStrengthNone, router.AccountID, router.NetworkID) if err != nil { return fmt.Errorf("failed to get network: %w", err) } @@ -104,12 +104,12 @@ func (m *managerImpl) CreateRouter(ctx context.Context, userID string, router *t router.ID = xid.New().String() - err = transaction.SaveNetworkRouter(ctx, store.LockingStrengthUpdate, router) + err = transaction.SaveNetworkRouter(ctx, router) if err != nil { return fmt.Errorf("failed to create network router: %w", err) } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, router.AccountID) + err = transaction.IncrementNetworkSerial(ctx, router.AccountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -136,7 +136,7 @@ func (m *managerImpl) GetRouter(ctx context.Context, accountID, userID, networkI return nil, status.NewPermissionDeniedError() } - router, err := m.store.GetNetworkRouterByID(ctx, store.LockingStrengthShare, accountID, routerID) + router, err := m.store.GetNetworkRouterByID(ctx, store.LockingStrengthNone, accountID, routerID) if err != nil { return nil, fmt.Errorf("failed to get network router: %w", err) } @@ -162,7 +162,7 @@ func (m *managerImpl) UpdateRouter(ctx context.Context, userID string, router *t var network *networkTypes.Network err = m.store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - network, err = transaction.GetNetworkByID(ctx, store.LockingStrengthShare, router.AccountID, router.NetworkID) + network, err = transaction.GetNetworkByID(ctx, store.LockingStrengthNone, router.AccountID, router.NetworkID) if err != nil { return fmt.Errorf("failed to get network: %w", err) } @@ -171,12 +171,12 @@ func (m *managerImpl) UpdateRouter(ctx context.Context, userID string, router *t return status.NewRouterNotPartOfNetworkError(router.ID, router.NetworkID) } - err = transaction.SaveNetworkRouter(ctx, store.LockingStrengthUpdate, router) + err = transaction.SaveNetworkRouter(ctx, router) if err != nil { return fmt.Errorf("failed to update network router: %w", err) } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, router.AccountID) + err = transaction.IncrementNetworkSerial(ctx, router.AccountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -213,7 +213,7 @@ func (m *managerImpl) DeleteRouter(ctx context.Context, accountID, userID, netwo return fmt.Errorf("failed to delete network router: %w", err) } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID) + err = transaction.IncrementNetworkSerial(ctx, accountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -232,7 +232,7 @@ func (m *managerImpl) DeleteRouter(ctx context.Context, accountID, userID, netwo } func (m *managerImpl) DeleteRouterInTransaction(ctx context.Context, transaction store.Store, accountID, userID, networkID, routerID string) (func(), error) { - network, err := transaction.GetNetworkByID(ctx, store.LockingStrengthShare, accountID, networkID) + network, err := transaction.GetNetworkByID(ctx, store.LockingStrengthNone, accountID, networkID) if err != nil { return nil, fmt.Errorf("failed to get network: %w", err) } @@ -246,7 +246,7 @@ func (m *managerImpl) DeleteRouterInTransaction(ctx context.Context, transaction return nil, status.NewRouterNotPartOfNetworkError(routerID, networkID) } - err = transaction.DeleteNetworkRouter(ctx, store.LockingStrengthUpdate, accountID, routerID) + err = transaction.DeleteNetworkRouter(ctx, accountID, routerID) if err != nil { return nil, fmt.Errorf("failed to delete network router: %w", err) } 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 f954369d8..a1f669f4f 100644 --- a/management/server/peer.go +++ b/management/server/peer.go @@ -17,28 +17,28 @@ import ( "golang.org/x/exp/maps" nbdns "github.com/netbirdio/netbird/dns" - "github.com/netbirdio/netbird/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" "github.com/netbirdio/netbird/management/server/permissions/modules" "github.com/netbirdio/netbird/management/server/permissions/operations" + "github.com/netbirdio/netbird/shared/management/domain" "github.com/netbirdio/netbird/util" "github.com/netbirdio/netbird/management/server/posture" "github.com/netbirdio/netbird/management/server/store" "github.com/netbirdio/netbird/management/server/types" - "github.com/netbirdio/netbird/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/proto" + "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 // the current user is not an admin. func (am *DefaultAccountManager) GetPeers(ctx context.Context, accountID, userID, nameFilter, ipFilter string) ([]*nbpeer.Peer, error) { - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { return nil, err } @@ -48,7 +48,7 @@ func (am *DefaultAccountManager) GetPeers(ctx context.Context, accountID, userID return nil, status.NewPermissionValidationError(err) } - accountPeers, err := am.Store.GetAccountPeers(ctx, store.LockingStrengthShare, accountID, nameFilter, ipFilter) + accountPeers, err := am.Store.GetAccountPeers(ctx, store.LockingStrengthNone, accountID, nameFilter, ipFilter) if err != nil { return nil, err } @@ -58,7 +58,7 @@ func (am *DefaultAccountManager) GetPeers(ctx context.Context, accountID, userID return accountPeers, nil } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("failed to get account settings: %w", err) } @@ -130,7 +130,7 @@ func (am *DefaultAccountManager) MarkPeerConnected(ctx context.Context, peerPubK } if peer.AddedWithSSOLogin() { - settings, err = am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err = am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } @@ -173,7 +173,7 @@ func updatePeerStatusAndLocation(ctx context.Context, geo geolocation.Geolocatio peer.Location.CountryCode = location.Country.ISOCode peer.Location.CityName = location.City.Names.En peer.Location.GeoNameID = location.City.GeonameID - err = transaction.SavePeerLocation(ctx, store.LockingStrengthUpdate, accountID, peer) + err = transaction.SavePeerLocation(ctx, accountID, peer) if err != nil { log.WithContext(ctx).Warnf("could not store location for peer %s: %s", peer.ID, err) } @@ -182,7 +182,7 @@ func updatePeerStatusAndLocation(ctx context.Context, geo geolocation.Geolocatio log.WithContext(ctx).Tracef("saving peer status for peer %s is connected: %t", peer.ID, connected) - err := transaction.SavePeerStatus(ctx, store.LockingStrengthUpdate, accountID, peer.ID, *newStatus) + err := transaction.SavePeerStatus(ctx, accountID, peer.ID, *newStatus) if err != nil { return false, err } @@ -219,7 +219,7 @@ func (am *DefaultAccountManager) UpdatePeer(ctx context.Context, accountID, user return err } - settings, err = transaction.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err = transaction.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } @@ -281,7 +281,7 @@ func (am *DefaultAccountManager) UpdatePeer(ctx context.Context, accountID, user inactivityExpirationChanged = true } - return transaction.SavePeer(ctx, store.LockingStrengthUpdate, accountID, peer) + return transaction.SavePeer(ctx, accountID, peer) }) if err != nil { return nil, err @@ -346,7 +346,7 @@ func (am *DefaultAccountManager) DeletePeer(ctx context.Context, accountID, peer return status.NewPermissionDeniedError() } - peerAccountID, err := am.Store.GetAccountIDByPeerID(ctx, store.LockingStrengthShare, peerID) + peerAccountID, err := am.Store.GetAccountIDByPeerID(ctx, store.LockingStrengthNone, peerID) if err != nil { return err } @@ -383,7 +383,7 @@ func (am *DefaultAccountManager) DeletePeer(ctx context.Context, accountID, peer return fmt.Errorf("failed to delete peer: %w", err) } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -609,7 +609,7 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s newPeer.DNSLabel = freeLabel newPeer.IP = freeIP - unlock := am.Store.AcquireWriteLockByUID(ctx, accountID) + unlock := am.Store.AcquireReadLockByUID(ctx, accountID) defer func() { if unlock != nil { unlock() @@ -617,7 +617,7 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s }() err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - err = transaction.AddPeerToAccount(ctx, store.LockingStrengthUpdate, newPeer) + err = transaction.AddPeerToAccount(ctx, newPeer) if err != nil { return err } @@ -658,7 +658,7 @@ func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID s } } - err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID) + err = transaction.IncrementNetworkSerial(ctx, accountID) if err != nil { return fmt.Errorf("failed to increment network serial: %w", err) } @@ -734,7 +734,7 @@ func (am *DefaultAccountManager) SyncPeer(ctx context.Context, sync types.PeerSy var err error var postureChecks []*posture.Checks - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, nil, nil, err } @@ -746,7 +746,7 @@ func (am *DefaultAccountManager) SyncPeer(ctx context.Context, sync types.PeerSy } if peer.UserID != "" { - user, err := transaction.GetUserByUserID(ctx, store.LockingStrengthShare, peer.UserID) + user, err := transaction.GetUserByUserID(ctx, store.LockingStrengthNone, peer.UserID) if err != nil { return err } @@ -774,7 +774,7 @@ func (am *DefaultAccountManager) SyncPeer(ctx context.Context, sync types.PeerSy if updated { am.metrics.AccountManagerMetrics().CountPeerMetUpdate() log.WithContext(ctx).Tracef("peer %s metadata updated", peer.ID) - if err = transaction.SavePeer(ctx, store.LockingStrengthUpdate, accountID, peer); err != nil { + if err = transaction.SavePeer(ctx, accountID, peer); err != nil { return err } @@ -849,7 +849,7 @@ func (am *DefaultAccountManager) LoginPeer(ctx context.Context, login types.Peer var isPeerUpdated bool var postureChecks []*posture.Checks - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, nil, nil, err } @@ -911,7 +911,7 @@ func (am *DefaultAccountManager) LoginPeer(ctx context.Context, login types.Peer } if shouldStorePeer { - if err = transaction.SavePeer(ctx, store.LockingStrengthUpdate, accountID, peer); err != nil { + if err = transaction.SavePeer(ctx, accountID, peer); err != nil { return err } } @@ -934,7 +934,7 @@ func (am *DefaultAccountManager) LoginPeer(ctx context.Context, login types.Peer // getPeerPostureChecks returns the posture checks for the peer. func getPeerPostureChecks(ctx context.Context, transaction store.Store, accountID, peerID string) ([]*posture.Checks, error) { - policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthShare, accountID) + policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -958,7 +958,7 @@ func getPeerPostureChecks(ctx context.Context, transaction store.Store, accountI peerPostureChecksIDs = append(peerPostureChecksIDs, postureChecksIDs...) } - peerPostureChecks, err := transaction.GetPostureChecksByIDs(ctx, store.LockingStrengthShare, accountID, peerPostureChecksIDs) + peerPostureChecks, err := transaction.GetPostureChecksByIDs(ctx, store.LockingStrengthNone, accountID, peerPostureChecksIDs) if err != nil { return nil, err } @@ -973,7 +973,7 @@ func processPeerPostureChecks(ctx context.Context, transaction store.Store, poli continue } - sourceGroups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, rule.Sources) + sourceGroups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, rule.Sources) if err != nil { return nil, err } @@ -998,7 +998,7 @@ func processPeerPostureChecks(ctx context.Context, transaction store.Store, poli // with no JWT token and usually no setup-key. As the client can send up to two login request to check if it is expired // and before starting the engine, we do the checks without an account lock to avoid piling up requests. func (am *DefaultAccountManager) checkIFPeerNeedsLoginWithoutLock(ctx context.Context, accountID string, login types.PeerLogin) error { - peer, err := am.Store.GetPeerByPeerPubKey(ctx, store.LockingStrengthShare, login.WireGuardPubKey) + peer, err := am.Store.GetPeerByPeerPubKey(ctx, store.LockingStrengthNone, login.WireGuardPubKey) if err != nil { return err } @@ -1009,7 +1009,7 @@ func (am *DefaultAccountManager) checkIFPeerNeedsLoginWithoutLock(ctx context.Co return nil } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } @@ -1080,7 +1080,7 @@ func (am *DefaultAccountManager) handleExpiredPeer(ctx context.Context, transact // If peer was expired before and if it reached this point, it is re-authenticated. // UserID is present, meaning that JWT validation passed successfully in the API layer. peer = peer.UpdateLastLogin() - err = transaction.SavePeer(ctx, store.LockingStrengthUpdate, peer.AccountID, peer) + err = transaction.SavePeer(ctx, peer.AccountID, peer) if err != nil { return err } @@ -1090,7 +1090,7 @@ func (am *DefaultAccountManager) handleExpiredPeer(ctx context.Context, transact log.WithContext(ctx).Debugf("failed to update user last login: %v", err) } - settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthShare, peer.AccountID) + settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthNone, peer.AccountID) if err != nil { return fmt.Errorf("failed to get account settings: %w", err) } @@ -1132,7 +1132,7 @@ func peerLoginExpired(ctx context.Context, peer *nbpeer.Peer, settings *types.Se // GetPeer for a given accountID, peerID and userID error if not found. func (am *DefaultAccountManager) GetPeer(ctx context.Context, accountID, peerID, userID string) (*nbpeer.Peer, error) { - peer, err := am.Store.GetPeerByID(ctx, store.LockingStrengthShare, accountID, peerID) + peer, err := am.Store.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID) if err != nil { return nil, err } @@ -1145,7 +1145,7 @@ func (am *DefaultAccountManager) GetPeer(ctx context.Context, accountID, peerID, return peer, nil } - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { return nil, err } @@ -1171,7 +1171,7 @@ func (am *DefaultAccountManager) checkIfUserOwnsPeer(ctx context.Context, accoun // it is also possible that user doesn't own the peer but some of his peers have access to it, // this is a valid case, show the peer as well. - userPeers, err := am.Store.GetUserPeers(ctx, store.LockingStrengthShare, accountID, userID) + userPeers, err := am.Store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID) if err != nil { return nil, err } @@ -1394,7 +1394,7 @@ func (am *DefaultAccountManager) UpdateAccountPeer(ctx context.Context, accountI // If there is no peer that expires this function returns false and a duration of 0. // This function only considers peers that haven't been expired yet and that are connected. func (am *DefaultAccountManager) getNextPeerExpiration(ctx context.Context, accountID string) (time.Duration, bool) { - peersWithExpiry, err := am.Store.GetAccountPeersWithExpiration(ctx, store.LockingStrengthShare, accountID) + peersWithExpiry, err := am.Store.GetAccountPeersWithExpiration(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("failed to get peers with expiration: %v", err) return peerSchedulerRetryInterval, true @@ -1404,7 +1404,7 @@ func (am *DefaultAccountManager) getNextPeerExpiration(ctx context.Context, acco return 0, false } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("failed to get account settings: %v", err) return peerSchedulerRetryInterval, true @@ -1438,7 +1438,7 @@ func (am *DefaultAccountManager) getNextPeerExpiration(ctx context.Context, acco // If there is no peer that expires this function returns false and a duration of 0. // This function only considers peers that haven't been expired yet and that are not connected. func (am *DefaultAccountManager) getNextInactivePeerExpiration(ctx context.Context, accountID string) (time.Duration, bool) { - peersWithInactivity, err := am.Store.GetAccountPeersWithInactivity(ctx, store.LockingStrengthShare, accountID) + peersWithInactivity, err := am.Store.GetAccountPeersWithInactivity(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("failed to get peers with inactivity: %v", err) return peerSchedulerRetryInterval, true @@ -1448,7 +1448,7 @@ func (am *DefaultAccountManager) getNextInactivePeerExpiration(ctx context.Conte return 0, false } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("failed to get account settings: %v", err) return peerSchedulerRetryInterval, true @@ -1479,12 +1479,12 @@ func (am *DefaultAccountManager) getNextInactivePeerExpiration(ctx context.Conte // getExpiredPeers returns peers that have been expired. func (am *DefaultAccountManager) getExpiredPeers(ctx context.Context, accountID string) ([]*nbpeer.Peer, error) { - peersWithExpiry, err := am.Store.GetAccountPeersWithExpiration(ctx, store.LockingStrengthShare, accountID) + peersWithExpiry, err := am.Store.GetAccountPeersWithExpiration(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -1502,12 +1502,12 @@ func (am *DefaultAccountManager) getExpiredPeers(ctx context.Context, accountID // getInactivePeers returns peers that have been expired by inactivity func (am *DefaultAccountManager) getInactivePeers(ctx context.Context, accountID string) ([]*nbpeer.Peer, error) { - peersWithInactivity, err := am.Store.GetAccountPeersWithInactivity(ctx, store.LockingStrengthShare, accountID) + peersWithInactivity, err := am.Store.GetAccountPeersWithInactivity(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -1525,12 +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) { - return transaction.GetPeerGroupIDs(ctx, store.LockingStrengthShare, accountID, peerID) + return transaction.GetPeerGroupIDs(ctx, store.LockingStrengthNone, accountID, peerID) } // IsPeerInActiveGroup checks if the given peer is part of a group that is used @@ -1548,7 +1548,7 @@ func isPeerInActiveGroup(ctx context.Context, transaction store.Store, accountID func deletePeers(ctx context.Context, am *DefaultAccountManager, transaction store.Store, accountID, userID string, peers []*nbpeer.Peer) ([]func(), error) { var peerDeletedEvents []func() - settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := transaction.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -1568,7 +1568,7 @@ func deletePeers(ctx context.Context, am *DefaultAccountManager, transaction sto return nil, err } - if err = transaction.DeletePeer(ctx, store.LockingStrengthUpdate, accountID, peer.ID); err != nil { + if err = transaction.DeletePeer(ctx, accountID, peer.ID); err != nil { return nil, err } @@ -1624,7 +1624,7 @@ func (am *DefaultAccountManager) validatePeerDelete(ctx context.Context, transac // isPeerLinkedToNetworkRouter checks if a peer is linked to any network router in the account. func isPeerLinkedToNetworkRouter(ctx context.Context, transaction store.Store, accountID string, peerID string) (bool, *routerTypes.NetworkRouter) { - routers, err := transaction.GetNetworkRoutersByAccountID(ctx, store.LockingStrengthShare, accountID) + routers, err := transaction.GetNetworkRoutersByAccountID(ctx, store.LockingStrengthNone, accountID) if err != nil { log.WithContext(ctx).Errorf("error retrieving network routers while checking peer linkage: %v", err) return false, nil diff --git a/management/server/peer_test.go b/management/server/peer_test.go index 947e53a60..d974e7c21 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,6 @@ 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/management/server/activity" nbpeer "github.com/netbirdio/netbird/management/server/peer" "github.com/netbirdio/netbird/management/server/posture" @@ -47,6 +45,8 @@ import ( "github.com/netbirdio/netbird/management/server/telemetry" "github.com/netbirdio/netbird/management/server/types" nbroute "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/domain" + "github.com/netbirdio/netbird/shared/management/proto" ) func TestPeer_LoginExpired(t *testing.T) { @@ -1307,7 +1307,7 @@ func Test_RegisterPeerByUser(t *testing.T) { require.NoError(t, err) assert.Equal(t, newPeer.ExtraDNSLabels, addedPeer.ExtraDNSLabels) - peer, err := s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthShare, addedPeer.Key) + peer, err := s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthNone, addedPeer.Key) require.NoError(t, err) assert.Equal(t, peer.AccountID, existingAccountID) assert.Equal(t, peer.UserID, existingUserID) @@ -1442,7 +1442,7 @@ func Test_RegisterPeerBySetupKey(t *testing.T) { assert.NotNil(t, addedPeer, "addedPeer should not be nil on success") assert.Equal(t, currentPeer.ExtraDNSLabels, addedPeer.ExtraDNSLabels, "ExtraDNSLabels mismatch") - peerFromStore, err := s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthShare, currentPeer.Key) + peerFromStore, err := s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthNone, currentPeer.Key) require.NoError(t, err, "Failed to get peer by pub key: %s", currentPeer.Key) assert.Equal(t, existingAccountID, peerFromStore.AccountID, "AccountID mismatch for peer from store") assert.Equal(t, currentPeer.ExtraDNSLabels, peerFromStore.ExtraDNSLabels, "ExtraDNSLabels mismatch for peer from store") @@ -1476,8 +1476,9 @@ 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 engine == "sqlite" || engine == "mysql" || engine == "" { + // we intentionally disabled foreign keys in mysql + t.Skip("Skipping test because store is not respecting foreign keys") } if runtime.GOOS == "windows" { t.Skip("The SQLite store is not properly supported by Windows yet") @@ -1528,7 +1529,7 @@ func Test_RegisterPeerRollbackOnFailure(t *testing.T) { _, _, _, err = am.AddPeer(context.Background(), faultyKey, "", newPeer) require.Error(t, err) - _, err = s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthShare, newPeer.Key) + _, err = s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthNone, newPeer.Key) require.Error(t, err) account, err := s.GetAccount(context.Background(), existingAccountID) @@ -1699,7 +1700,7 @@ func Test_LoginPeer(t *testing.T) { assert.Equal(t, existingAccountID, loggedinPeer.AccountID, "AccountID mismatch for logged peer") - peerFromStore, err := s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthShare, loginInput.WireGuardPubKey) + peerFromStore, err := s.GetPeerByPeerPubKey(context.Background(), store.LockingStrengthNone, loginInput.WireGuardPubKey) require.NoError(t, err, "Failed to get peer by pub key: %s", loginInput.WireGuardPubKey) assert.Equal(t, existingAccountID, peerFromStore.AccountID, "AccountID mismatch for peer from store") assert.Equal(t, loggedinPeer.ID, peerFromStore.ID, "Peer ID mismatch between loggedinPeer and peerFromStore") @@ -2160,10 +2161,10 @@ func Test_IsUniqueConstraintError(t *testing.T) { } t.Cleanup(cleanup) - err = s.AddPeerToAccount(context.Background(), store.LockingStrengthUpdate, peer) + err = s.AddPeerToAccount(context.Background(), peer) assert.NoError(t, err) - err = s.AddPeerToAccount(context.Background(), store.LockingStrengthUpdate, peer) + err = s.AddPeerToAccount(context.Background(), peer) result := isUniqueConstraintError(err) assert.True(t, result) }) diff --git a/management/server/peers/manager.go b/management/server/peers/manager.go index fe48bf576..50e36a880 100644 --- a/management/server/peers/manager.go +++ b/management/server/peers/manager.go @@ -10,8 +10,8 @@ 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/management/server/store" + "github.com/netbirdio/netbird/shared/management/status" ) type Manager interface { @@ -42,7 +42,7 @@ func (m *managerImpl) GetPeer(ctx context.Context, accountID, userID, peerID str return nil, status.NewPermissionDeniedError() } - return m.store.GetPeerByID(ctx, store.LockingStrengthShare, accountID, peerID) + return m.store.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID) } func (m *managerImpl) GetAllPeers(ctx context.Context, accountID, userID string) ([]*peer.Peer, error) { @@ -52,12 +52,12 @@ func (m *managerImpl) GetAllPeers(ctx context.Context, accountID, userID string) } if !allowed { - return m.store.GetUserPeers(ctx, store.LockingStrengthShare, accountID, userID) + return m.store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID) } - return m.store.GetAccountPeers(ctx, store.LockingStrengthShare, accountID, "", "") + return m.store.GetAccountPeers(ctx, store.LockingStrengthNone, accountID, "", "") } func (m *managerImpl) GetPeerAccountID(ctx context.Context, peerID string) (string, error) { - return m.store.GetAccountIDByPeerID(ctx, store.LockingStrengthShare, peerID) + return m.store.GetAccountIDByPeerID(ctx, store.LockingStrengthNone, peerID) } diff --git a/management/server/permissions/manager.go b/management/server/permissions/manager.go index ebbce5d4a..0ab244243 100644 --- a/management/server/permissions/manager.go +++ b/management/server/permissions/manager.go @@ -11,9 +11,9 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/status" ) type Manager interface { @@ -45,7 +45,7 @@ func (m *managerImpl) ValidateUserPermissions( return true, nil } - user, err := m.store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + user, err := m.store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { return false, err } diff --git a/management/server/policy.go b/management/server/policy.go index 1e9331d43..d5c66e9f8 100644 --- a/management/server/policy.go +++ b/management/server/policy.go @@ -6,15 +6,15 @@ import ( "github.com/rs/xid" - "github.com/netbirdio/netbird/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" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/proto" "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 @@ -27,7 +27,7 @@ func (am *DefaultAccountManager) GetPolicy(ctx context.Context, accountID, polic return nil, status.NewPermissionDeniedError() } - return am.Store.GetPolicyByID(ctx, store.LockingStrengthShare, accountID, policyID) + return am.Store.GetPolicyByID(ctx, store.LockingStrengthNone, accountID, policyID) } // SavePolicy in the store @@ -61,7 +61,7 @@ func (am *DefaultAccountManager) SavePolicy(ctx context.Context, accountID, user return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } @@ -71,7 +71,7 @@ func (am *DefaultAccountManager) SavePolicy(ctx context.Context, accountID, user saveFunc = transaction.SavePolicy } - return saveFunc(ctx, store.LockingStrengthUpdate, policy) + return saveFunc(ctx, policy) }) if err != nil { return nil, err @@ -113,11 +113,11 @@ func (am *DefaultAccountManager) DeletePolicy(ctx context.Context, accountID, po return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.DeletePolicy(ctx, store.LockingStrengthUpdate, accountID, policyID) + return transaction.DeletePolicy(ctx, accountID, policyID) }) if err != nil { return err @@ -142,13 +142,13 @@ func (am *DefaultAccountManager) ListPolicies(ctx context.Context, accountID, us return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountPolicies(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountPolicies(ctx, store.LockingStrengthNone, accountID) } // arePolicyChangesAffectPeers checks if changes to a policy will affect any associated peers. func arePolicyChangesAffectPeers(ctx context.Context, transaction store.Store, accountID string, policy *types.Policy, isUpdate bool) (bool, error) { if isUpdate { - existingPolicy, err := transaction.GetPolicyByID(ctx, store.LockingStrengthShare, accountID, policy.ID) + existingPolicy, err := transaction.GetPolicyByID(ctx, store.LockingStrengthNone, accountID, policy.ID) if err != nil { return false, err } @@ -173,7 +173,7 @@ func arePolicyChangesAffectPeers(ctx context.Context, transaction store.Store, a // validatePolicy validates the policy and its rules. func validatePolicy(ctx context.Context, transaction store.Store, accountID string, policy *types.Policy) error { if policy.ID != "" { - _, err := transaction.GetPolicyByID(ctx, store.LockingStrengthShare, accountID, policy.ID) + _, err := transaction.GetPolicyByID(ctx, store.LockingStrengthNone, accountID, policy.ID) if err != nil { return err } @@ -182,12 +182,12 @@ func validatePolicy(ctx context.Context, transaction store.Store, accountID stri policy.AccountID = accountID } - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, policy.RuleGroups()) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, policy.RuleGroups()) if err != nil { return err } - postureChecks, err := transaction.GetPostureChecksByIDs(ctx, store.LockingStrengthShare, accountID, policy.SourcePostureChecks) + postureChecks, err := transaction.GetPostureChecksByIDs(ctx, store.LockingStrengthNone, accountID, policy.SourcePostureChecks) if err != nil { return err } 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..9414b8065 100644 --- a/management/server/posture_checks.go +++ b/management/server/posture_checks.go @@ -13,9 +13,9 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" + "github.com/netbirdio/netbird/shared/management/status" ) func (am *DefaultAccountManager) GetPostureChecks(ctx context.Context, accountID, postureChecksID, userID string) (*posture.Checks, error) { @@ -27,7 +27,7 @@ func (am *DefaultAccountManager) GetPostureChecks(ctx context.Context, accountID return nil, status.NewPermissionDeniedError() } - return am.Store.GetPostureChecksByID(ctx, store.LockingStrengthShare, accountID, postureChecksID) + return am.Store.GetPostureChecksByID(ctx, store.LockingStrengthNone, accountID, postureChecksID) } // SavePostureChecks saves a posture check. @@ -62,7 +62,7 @@ func (am *DefaultAccountManager) SavePostureChecks(ctx context.Context, accountI return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } @@ -70,7 +70,7 @@ func (am *DefaultAccountManager) SavePostureChecks(ctx context.Context, accountI } postureChecks.AccountID = accountID - return transaction.SavePostureChecks(ctx, store.LockingStrengthUpdate, postureChecks) + return transaction.SavePostureChecks(ctx, postureChecks) }) if err != nil { return nil, err @@ -101,7 +101,7 @@ func (am *DefaultAccountManager) DeletePostureChecks(ctx context.Context, accoun var postureChecks *posture.Checks err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - postureChecks, err = transaction.GetPostureChecksByID(ctx, store.LockingStrengthShare, accountID, postureChecksID) + postureChecks, err = transaction.GetPostureChecksByID(ctx, store.LockingStrengthNone, accountID, postureChecksID) if err != nil { return err } @@ -110,11 +110,11 @@ func (am *DefaultAccountManager) DeletePostureChecks(ctx context.Context, accoun return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.DeletePostureChecks(ctx, store.LockingStrengthUpdate, accountID, postureChecksID) + return transaction.DeletePostureChecks(ctx, accountID, postureChecksID) }) if err != nil { return err @@ -135,7 +135,7 @@ func (am *DefaultAccountManager) ListPostureChecks(ctx context.Context, accountI return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountPostureChecks(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountPostureChecks(ctx, store.LockingStrengthNone, accountID) } // getPeerPostureChecks returns the posture checks applied for a given peer. @@ -161,7 +161,7 @@ func (am *DefaultAccountManager) getPeerPostureChecks(account *types.Account, pe // arePostureCheckChangesAffectPeers checks if the changes in posture checks are affecting peers. func arePostureCheckChangesAffectPeers(ctx context.Context, transaction store.Store, accountID, postureCheckID string) (bool, error) { - policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthShare, accountID) + policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthNone, accountID) if err != nil { return false, err } @@ -190,14 +190,14 @@ func validatePostureChecks(ctx context.Context, transaction store.Store, account // If the posture check already has an ID, verify its existence in the store. if postureChecks.ID != "" { - if _, err := transaction.GetPostureChecksByID(ctx, store.LockingStrengthShare, accountID, postureChecks.ID); err != nil { + if _, err := transaction.GetPostureChecksByID(ctx, store.LockingStrengthNone, accountID, postureChecks.ID); err != nil { return err } return nil } // For new posture checks, ensure no duplicates by name. - checks, err := transaction.GetAccountPostureChecks(ctx, store.LockingStrengthShare, accountID) + checks, err := transaction.GetAccountPostureChecks(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } @@ -259,7 +259,7 @@ func isPeerInPolicySourceGroups(account *types.Account, peerID string, policy *t // isPostureCheckLinkedToPolicy checks whether the posture check is linked to any account policy. func isPostureCheckLinkedToPolicy(ctx context.Context, transaction store.Store, postureChecksID, accountID string) error { - policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthShare, accountID) + policies, err := transaction.GetAccountPolicies(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } diff --git a/management/server/route.go b/management/server/route.go index 32ff39977..6adff56b5 100644 --- a/management/server/route.go +++ b/management/server/route.go @@ -9,15 +9,15 @@ import ( "github.com/rs/xid" - "github.com/netbirdio/netbird/management/domain" - "github.com/netbirdio/netbird/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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/domain" + "github.com/netbirdio/netbird/shared/management/proto" + "github.com/netbirdio/netbird/shared/management/status" ) // GetRoute gets a route object from account and route IDs @@ -30,7 +30,7 @@ func (am *DefaultAccountManager) GetRoute(ctx context.Context, accountID string, return nil, status.NewPermissionDeniedError() } - return am.Store.GetRouteByID(ctx, store.LockingStrengthShare, accountID, string(routeID)) + return am.Store.GetRouteByID(ctx, store.LockingStrengthNone, accountID, string(routeID)) } // checkRoutePrefixOrDomainsExistForPeers checks if a route with a given prefix exists for a single peer or multiple peer groups. @@ -59,7 +59,7 @@ func checkRoutePrefixOrDomainsExistForPeers(ctx context.Context, transaction sto seenPeers[string(prefixRoute.ID)] = true } - peerGroupsMap, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, prefixRoute.PeerGroups) + peerGroupsMap, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, prefixRoute.PeerGroups) if err != nil { return err } @@ -83,7 +83,7 @@ func checkRoutePrefixOrDomainsExistForPeers(ctx context.Context, transaction sto if peerID := checkRoute.Peer; peerID != "" { // check that peerID exists and is not in any route as single peer or part of the group - _, err = transaction.GetPeerByID(context.Background(), store.LockingStrengthShare, accountID, peerID) + _, err = transaction.GetPeerByID(context.Background(), store.LockingStrengthNone, accountID, peerID) if err != nil { return status.Errorf(status.InvalidArgument, "peer with ID %s not found", peerID) } @@ -104,7 +104,7 @@ func checkRoutePrefixOrDomainsExistForPeers(ctx context.Context, transaction sto } // check that the peers from peerGroupIDs groups are not the same peers we saw in routesWithPrefix - peersMap, err := transaction.GetPeersByIDs(ctx, store.LockingStrengthShare, accountID, group.Peers) + peersMap, err := transaction.GetPeersByIDs(ctx, store.LockingStrengthNone, accountID, group.Peers) if err != nil { return err } @@ -181,11 +181,11 @@ func (am *DefaultAccountManager) CreateRoute(ctx context.Context, accountID stri return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.SaveRoute(ctx, store.LockingStrengthUpdate, newRoute) + return transaction.SaveRoute(ctx, newRoute) }) if err != nil { return nil, err @@ -238,11 +238,11 @@ func (am *DefaultAccountManager) SaveRoute(ctx context.Context, accountID, userI } routeToSave.AccountID = accountID - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.SaveRoute(ctx, store.LockingStrengthUpdate, routeToSave) + return transaction.SaveRoute(ctx, routeToSave) }) if err != nil { return err @@ -284,11 +284,11 @@ func (am *DefaultAccountManager) DeleteRoute(ctx context.Context, accountID stri return err } - if err = transaction.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = transaction.IncrementNetworkSerial(ctx, accountID); err != nil { return err } - return transaction.DeleteRoute(ctx, store.LockingStrengthUpdate, accountID, string(routeID)) + return transaction.DeleteRoute(ctx, accountID, string(routeID)) }) am.StoreEvent(ctx, userID, string(route.ID), accountID, activity.RouteRemoved, route.EventMeta()) @@ -310,7 +310,7 @@ func (am *DefaultAccountManager) ListRoutes(ctx context.Context, accountID, user return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountRoutes(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountRoutes(ctx, store.LockingStrengthNone, accountID) } func validateRoute(ctx context.Context, transaction store.Store, accountID string, routeToSave *route.Route) error { @@ -353,7 +353,7 @@ func validateRoute(ctx context.Context, transaction store.Store, accountID strin // validateRouteGroups validates the route groups and returns the validated groups map. func validateRouteGroups(ctx context.Context, transaction store.Store, accountID string, routeToSave *route.Route) (map[string]*types.Group, error) { groupsToValidate := slices.Concat(routeToSave.Groups, routeToSave.PeerGroups, routeToSave.AccessControlGroups) - groupsMap, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, groupsToValidate) + groupsMap, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, groupsToValidate) if err != nil { return nil, err } @@ -494,7 +494,7 @@ func areRouteChangesAffectPeers(ctx context.Context, transaction store.Store, ro // GetRoutesByPrefixOrDomains return list of routes by account and route prefix func getRoutesByPrefixOrDomains(ctx context.Context, transaction store.Store, accountID string, prefix netip.Prefix, domains domain.List) ([]*route.Route, error) { - accountRoutes, err := transaction.GetAccountRoutes(ctx, store.LockingStrengthShare, accountID) + accountRoutes, err := transaction.GetAccountRoutes(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } diff --git a/management/server/route_test.go b/management/server/route_test.go index ffd1a284b..c3eea35ea 100644 --- a/management/server/route_test.go +++ b/management/server/route_test.go @@ -14,7 +14,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/netbirdio/netbird/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" @@ -27,6 +26,7 @@ import ( "github.com/netbirdio/netbird/management/server/telemetry" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/domain" ) const ( @@ -1100,7 +1100,7 @@ func TestGetNetworkMap_RouteSyncPeerGroups(t *testing.T) { require.NoError(t, err) assert.Len(t, peer4Routes.Routes, 1, "HA route should have 1 server route") - groups, err := am.Store.GetAccountGroups(context.Background(), store.LockingStrengthShare, account.Id) + groups, err := am.Store.GetAccountGroups(context.Background(), store.LockingStrengthNone, account.Id) require.NoError(t, err) var groupHA1, groupHA2 *types.Group for _, group := range groups { diff --git a/management/server/settings/manager.go b/management/server/settings/manager.go index 94392ebf7..6d09f1786 100644 --- a/management/server/settings/manager.go +++ b/management/server/settings/manager.go @@ -11,10 +11,10 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/users" + "github.com/netbirdio/netbird/shared/management/status" ) type Manager interface { @@ -60,7 +60,7 @@ func (m *managerImpl) GetSettings(ctx context.Context, accountID, userID string) return nil, fmt.Errorf("get extra settings: %w", err) } - settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("get account settings: %w", err) } @@ -82,7 +82,7 @@ func (m *managerImpl) GetExtraSettings(ctx context.Context, accountID string) (* return nil, fmt.Errorf("get extra settings: %w", err) } - settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("get account settings: %w", err) } diff --git a/management/server/setupkey.go b/management/server/setupkey.go index b0903c8d0..71915b4a2 100644 --- a/management/server/setupkey.go +++ b/management/server/setupkey.go @@ -10,10 +10,10 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/util" + "github.com/netbirdio/netbird/shared/management/status" ) const ( @@ -81,7 +81,7 @@ func (am *DefaultAccountManager) CreateSetupKey(ctx context.Context, accountID s events := am.prepareSetupKeyEvents(ctx, transaction, accountID, userID, autoGroups, nil, setupKey) eventsToStore = append(eventsToStore, events...) - return transaction.SaveSetupKey(ctx, store.LockingStrengthUpdate, setupKey) + return transaction.SaveSetupKey(ctx, setupKey) }) if err != nil { return nil, err @@ -127,7 +127,7 @@ func (am *DefaultAccountManager) SaveSetupKey(ctx context.Context, accountID str return status.Errorf(status.InvalidArgument, "invalid auto groups: %v", err) } - oldKey, err = transaction.GetSetupKeyByID(ctx, store.LockingStrengthShare, accountID, keyToSave.Id) + oldKey, err = transaction.GetSetupKeyByID(ctx, store.LockingStrengthUpdate, accountID, keyToSave.Id) if err != nil { return err } @@ -148,7 +148,7 @@ func (am *DefaultAccountManager) SaveSetupKey(ctx context.Context, accountID str events := am.prepareSetupKeyEvents(ctx, transaction, accountID, userID, addedGroups, removedGroups, oldKey) eventsToStore = append(eventsToStore, events...) - return transaction.SaveSetupKey(ctx, store.LockingStrengthUpdate, newKey) + return transaction.SaveSetupKey(ctx, newKey) }) if err != nil { return nil, err @@ -175,7 +175,7 @@ func (am *DefaultAccountManager) ListSetupKeys(ctx context.Context, accountID, u return nil, status.NewPermissionDeniedError() } - return am.Store.GetAccountSetupKeys(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountSetupKeys(ctx, store.LockingStrengthNone, accountID) } // GetSetupKey looks up a SetupKey by KeyID, returns NotFound error if not found. @@ -188,7 +188,7 @@ func (am *DefaultAccountManager) GetSetupKey(ctx context.Context, accountID, use return nil, status.NewPermissionDeniedError() } - setupKey, err := am.Store.GetSetupKeyByID(ctx, store.LockingStrengthShare, accountID, keyID) + setupKey, err := am.Store.GetSetupKeyByID(ctx, store.LockingStrengthNone, accountID, keyID) if err != nil { return nil, err } @@ -214,12 +214,12 @@ func (am *DefaultAccountManager) DeleteSetupKey(ctx context.Context, accountID, var deletedSetupKey *types.SetupKey err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - deletedSetupKey, err = transaction.GetSetupKeyByID(ctx, store.LockingStrengthShare, accountID, keyID) + deletedSetupKey, err = transaction.GetSetupKeyByID(ctx, store.LockingStrengthUpdate, accountID, keyID) if err != nil { return err } - return transaction.DeleteSetupKey(ctx, store.LockingStrengthUpdate, accountID, keyID) + return transaction.DeleteSetupKey(ctx, accountID, keyID) }) if err != nil { return err @@ -231,7 +231,7 @@ func (am *DefaultAccountManager) DeleteSetupKey(ctx context.Context, accountID, } func validateSetupKeyAutoGroups(ctx context.Context, transaction store.Store, accountID string, autoGroupIDs []string) error { - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, autoGroupIDs) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, autoGroupIDs) if err != nil { return err } @@ -255,7 +255,7 @@ func (am *DefaultAccountManager) prepareSetupKeyEvents(ctx context.Context, tran var eventsToStore []func() modifiedGroups := slices.Concat(addedGroups, removedGroups) - groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthShare, accountID, modifiedGroups) + groups, err := transaction.GetGroupsByIDs(ctx, store.LockingStrengthNone, accountID, modifiedGroups) if err != nil { log.WithContext(ctx).Debugf("failed to get groups for setup key events: %v", err) return nil diff --git a/management/server/store/sql_store.go b/management/server/store/sql_store.go index c2f0dff6d..8aa56f7b0 100644 --- a/management/server/store/sql_store.go +++ b/management/server/store/sql_store.go @@ -24,16 +24,17 @@ import ( "gorm.io/gorm/logger" nbdns "github.com/netbirdio/netbird/dns" + nbcontext "github.com/netbirdio/netbird/management/server/context" 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/management/server/telemetry" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/util" "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/status" ) const ( @@ -76,7 +77,12 @@ func NewSqlStore(ctx context.Context, db *gorm.DB, storeEngine types.Engine, met conns = runtime.NumCPU() } - if storeEngine == types.SqliteStoreEngine { + switch storeEngine { + case types.MysqlStoreEngine: + if err := db.Exec("SET GLOBAL FOREIGN_KEY_CHECKS = 0").Error; err != nil { + return nil, err + } + case types.SqliteStoreEngine: if err == nil { log.WithContext(ctx).Warnf("setting NB_SQL_MAX_OPEN_CONNS is not supported for sqlite, using default value 1") } @@ -142,14 +148,16 @@ func (s *SqlStore) AcquireGlobalLock(ctx context.Context) (unlock func()) { func (s *SqlStore) AcquireWriteLockByUID(ctx context.Context, uniqueID string) (unlock func()) { log.WithContext(ctx).Tracef("acquiring write lock for ID %s", uniqueID) - start := time.Now() + startWait := time.Now() value, _ := s.resourceLocks.LoadOrStore(uniqueID, &sync.RWMutex{}) mtx := value.(*sync.RWMutex) mtx.Lock() + log.WithContext(ctx).Tracef("waiting to acquire write lock for ID %s in %v", uniqueID, time.Since(startWait)) + startHold := time.Now() unlock = func() { mtx.Unlock() - log.WithContext(ctx).Tracef("released write lock for ID %s in %v", uniqueID, time.Since(start)) + log.WithContext(ctx).Tracef("released write lock for ID %s in %v", uniqueID, time.Since(startHold)) } return unlock @@ -159,19 +167,22 @@ func (s *SqlStore) AcquireWriteLockByUID(ctx context.Context, uniqueID string) ( func (s *SqlStore) AcquireReadLockByUID(ctx context.Context, uniqueID string) (unlock func()) { log.WithContext(ctx).Tracef("acquiring read lock for ID %s", uniqueID) - start := time.Now() + startWait := time.Now() value, _ := s.resourceLocks.LoadOrStore(uniqueID, &sync.RWMutex{}) mtx := value.(*sync.RWMutex) mtx.RLock() + log.WithContext(ctx).Tracef("waiting to acquire read lock for ID %s in %v", uniqueID, time.Since(startWait)) + startHold := time.Now() unlock = func() { mtx.RUnlock() - log.WithContext(ctx).Tracef("released read lock for ID %s in %v", uniqueID, time.Since(start)) + log.WithContext(ctx).Tracef("released read lock for ID %s in %v", uniqueID, time.Since(startHold)) } return unlock } +// Deprecated: Full account operations are no longer supported func (s *SqlStore) SaveAccount(ctx context.Context, account *types.Account) error { start := time.Now() defer func() { @@ -270,7 +281,7 @@ func generateAccountSQLTypes(account *types.Account) { func (s *SqlStore) checkAccountDomainBeforeSave(ctx context.Context, accountID, newDomain string) { var acc types.Account var domain string - result := s.db.Model(&acc).Select("domain").Where(idQueryCondition, accountID).First(&domain) + result := s.db.Model(&acc).Select("domain").Where(idQueryCondition, accountID).Take(&domain) if result.Error != nil { if !errors.Is(result.Error, gorm.ErrRecordNotFound) { log.WithContext(ctx).Errorf("error when getting account %s from the store to check domain: %s", accountID, result.Error) @@ -323,23 +334,26 @@ func (s *SqlStore) SaveInstallationID(_ context.Context, ID string) error { func (s *SqlStore) GetInstallationID() string { var installation installation - if result := s.db.First(&installation, idQueryCondition, s.installationPK); result.Error != nil { + if result := s.db.Take(&installation, idQueryCondition, s.installationPK); result.Error != nil { return "" } return installation.InstallationIDValue } -func (s *SqlStore) SavePeer(ctx context.Context, lockStrength LockingStrength, accountID string, peer *nbpeer.Peer) error { +func (s *SqlStore) SavePeer(ctx context.Context, accountID string, peer *nbpeer.Peer) error { // To maintain data integrity, we create a copy of the peer's to prevent unintended updates to other fields. peerCopy := peer.Copy() peerCopy.AccountID = accountID - err := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Transaction(func(tx *gorm.DB) error { + err := s.db.Transaction(func(tx *gorm.DB) error { // check if peer exists before saving var peerID string - result := tx.Model(&nbpeer.Peer{}).Select("id").Find(&peerID, accountAndIDQueryCondition, accountID, peer.ID) + result := tx.Model(&nbpeer.Peer{}).Select("id").Take(&peerID, accountAndIDQueryCondition, accountID, peer.ID) if result.Error != nil { + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + return status.Errorf(status.NotFound, peerNotFoundFMT, peer.ID) + } return result.Error } @@ -385,7 +399,7 @@ func (s *SqlStore) UpdateAccountDomainAttributes(ctx context.Context, accountID return nil } -func (s *SqlStore) SavePeerStatus(ctx context.Context, lockStrength LockingStrength, accountID, peerID string, peerStatus nbpeer.PeerStatus) error { +func (s *SqlStore) SavePeerStatus(ctx context.Context, accountID, peerID string, peerStatus nbpeer.PeerStatus) error { var peerCopy nbpeer.Peer peerCopy.Status = &peerStatus @@ -393,7 +407,7 @@ func (s *SqlStore) SavePeerStatus(ctx context.Context, lockStrength LockingStren "peer_status_last_seen", "peer_status_connected", "peer_status_login_expired", "peer_status_required_approval", } - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Model(&nbpeer.Peer{}). + result := s.db.Model(&nbpeer.Peer{}). Select(fieldsToUpdate). Where(accountAndIDQueryCondition, accountID, peerID). Updates(&peerCopy) @@ -408,14 +422,14 @@ func (s *SqlStore) SavePeerStatus(ctx context.Context, lockStrength LockingStren return nil } -func (s *SqlStore) SavePeerLocation(ctx context.Context, lockStrength LockingStrength, accountID string, peerWithLocation *nbpeer.Peer) error { +func (s *SqlStore) SavePeerLocation(ctx context.Context, accountID string, peerWithLocation *nbpeer.Peer) error { // To maintain data integrity, we create a copy of the peer's location to prevent unintended updates to other fields. var peerCopy nbpeer.Peer // Since the location field has been migrated to JSON serialization, // updating the struct ensures the correct data format is inserted into the database. peerCopy.Location = peerWithLocation.Location - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Model(&nbpeer.Peer{}). + result := s.db.Model(&nbpeer.Peer{}). Where(accountAndIDQueryCondition, accountID, peerWithLocation.ID). Updates(peerCopy) @@ -431,12 +445,12 @@ func (s *SqlStore) SavePeerLocation(ctx context.Context, lockStrength LockingStr } // SaveUsers saves the given list of users to the database. -func (s *SqlStore) SaveUsers(ctx context.Context, lockStrength LockingStrength, users []*types.User) error { +func (s *SqlStore) SaveUsers(ctx context.Context, users []*types.User) error { if len(users) == 0 { return nil } - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}, clause.OnConflict{UpdateAll: true}).Create(&users) + result := s.db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&users) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save users to store: %s", result.Error) return status.Errorf(status.Internal, "failed to save users to store") @@ -445,8 +459,8 @@ func (s *SqlStore) SaveUsers(ctx context.Context, lockStrength LockingStrength, } // SaveUser saves the given user to the database. -func (s *SqlStore) SaveUser(ctx context.Context, lockStrength LockingStrength, user *types.User) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(user) +func (s *SqlStore) SaveUser(ctx context.Context, user *types.User) error { + result := s.db.Save(user) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save user to store: %s", result.Error) return status.Errorf(status.Internal, "failed to save user to store") @@ -455,7 +469,7 @@ func (s *SqlStore) SaveUser(ctx context.Context, lockStrength LockingStrength, u } // 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 { +func (s *SqlStore) CreateGroups(ctx context.Context, accountID string, groups []*types.Group) error { if len(groups) == 0 { return nil } @@ -463,7 +477,6 @@ func (s *SqlStore) CreateGroups(ctx context.Context, lockStrength LockingStrengt 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, @@ -481,7 +494,7 @@ func (s *SqlStore) CreateGroups(ctx context.Context, lockStrength LockingStrengt } // 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 { +func (s *SqlStore) UpdateGroups(ctx context.Context, accountID string, groups []*types.Group) error { if len(groups) == 0 { return nil } @@ -489,7 +502,6 @@ func (s *SqlStore) UpdateGroups(ctx context.Context, lockStrength LockingStrengt 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, @@ -517,7 +529,7 @@ func (s *SqlStore) DeleteTokenID2UserIDIndex(tokenID string) error { } func (s *SqlStore) GetAccountByPrivateDomain(ctx context.Context, domain string) (*types.Account, error) { - accountID, err := s.GetAccountIDByPrivateDomain(ctx, LockingStrengthShare, domain) + accountID, err := s.GetAccountIDByPrivateDomain(ctx, LockingStrengthNone, domain) if err != nil { return nil, err } @@ -536,7 +548,7 @@ func (s *SqlStore) GetAccountIDByPrivateDomain(ctx context.Context, lockStrength result := tx.Model(&types.Account{}).Select("id"). Where("domain = ? and is_domain_primary_account = ? and domain_category = ?", strings.ToLower(domain), true, types.PrivateCategory, - ).First(&accountID) + ).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.Errorf(status.NotFound, "account not found: provided domain is not registered or is not private") @@ -550,7 +562,7 @@ func (s *SqlStore) GetAccountIDByPrivateDomain(ctx context.Context, lockStrength func (s *SqlStore) GetAccountBySetupKey(ctx context.Context, setupKey string) (*types.Account, error) { var key types.SetupKey - result := s.db.Select("account_id").First(&key, GetKeyQueryCondition(s), setupKey) + result := s.db.Select("account_id").Take(&key, GetKeyQueryCondition(s), setupKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewSetupKeyNotFoundError(setupKey) @@ -568,7 +580,7 @@ func (s *SqlStore) GetAccountBySetupKey(ctx context.Context, setupKey string) (* func (s *SqlStore) GetTokenIDByHashedToken(ctx context.Context, hashedToken string) (string, error) { var token types.PersonalAccessToken - result := s.db.First(&token, "hashed_token = ?", hashedToken) + result := s.db.Take(&token, "hashed_token = ?", hashedToken) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.Errorf(status.NotFound, "account not found: index lookup failed") @@ -589,7 +601,7 @@ func (s *SqlStore) GetUserByPATID(ctx context.Context, lockStrength LockingStren var user types.User result := tx. Joins("JOIN personal_access_tokens ON personal_access_tokens.user_id = users.id"). - Where("personal_access_tokens.id = ?", patID).First(&user) + Where("personal_access_tokens.id = ?", patID).Take(&user) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewPATNotFoundError(patID) @@ -602,13 +614,16 @@ func (s *SqlStore) GetUserByPATID(ctx context.Context, lockStrength LockingStren } func (s *SqlStore) GetUserByUserID(ctx context.Context, lockStrength LockingStrength, userID string) (*types.User, error) { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + tx := s.db if lockStrength != LockingStrengthNone { tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) } var user types.User - result := tx.First(&user, idQueryCondition, userID) + result := tx.WithContext(ctx).Take(&user, idQueryCondition, userID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewUserNotFoundError(userID) @@ -619,16 +634,14 @@ func (s *SqlStore) GetUserByUserID(ctx context.Context, lockStrength LockingStre return &user, nil } -func (s *SqlStore) DeleteUser(ctx context.Context, lockStrength LockingStrength, accountID, userID string) error { +func (s *SqlStore) DeleteUser(ctx context.Context, accountID, userID string) error { err := s.db.Transaction(func(tx *gorm.DB) error { - result := tx.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&types.PersonalAccessToken{}, "user_id = ?", userID) + result := tx.Delete(&types.PersonalAccessToken{}, "user_id = ?", userID) if result.Error != nil { return result.Error } - return tx.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&types.User{}, accountAndIDQueryCondition, accountID, userID).Error + return tx.Delete(&types.User{}, accountAndIDQueryCondition, accountID, userID).Error }) if err != nil { log.WithContext(ctx).Errorf("failed to delete user from the store: %s", err) @@ -664,7 +677,7 @@ func (s *SqlStore) GetAccountOwner(ctx context.Context, lockStrength LockingStre } var user types.User - result := tx.First(&user, "account_id = ? AND role = ?", accountID, types.UserRoleOwner) + result := tx.Take(&user, "account_id = ? AND role = ?", accountID, types.UserRoleOwner) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.Errorf(status.NotFound, "account owner not found: index lookup failed") @@ -761,7 +774,7 @@ func (s *SqlStore) GetAccountMeta(ctx context.Context, lockStrength LockingStren var accountMeta types.AccountMeta result := tx.Model(&types.Account{}). - First(&accountMeta, idQueryCondition, accountID) + Take(&accountMeta, idQueryCondition, accountID) if result.Error != nil { log.WithContext(ctx).Errorf("error when getting account meta %s from the store: %s", accountID, result.Error) if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -776,7 +789,7 @@ func (s *SqlStore) GetAccountMeta(ctx context.Context, lockStrength LockingStren // GetAccountOnboarding retrieves the onboarding information for a specific account. func (s *SqlStore) GetAccountOnboarding(ctx context.Context, accountID string) (*types.AccountOnboarding, error) { var accountOnboarding types.AccountOnboarding - result := s.db.Model(&accountOnboarding).First(&accountOnboarding, accountIDCondition, accountID) + result := s.db.Model(&accountOnboarding).Take(&accountOnboarding, accountIDCondition, accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewAccountOnboardingNotFoundError(accountID) @@ -813,7 +826,7 @@ func (s *SqlStore) GetAccount(ctx context.Context, accountID string) (*types.Acc Omit("GroupsG"). Preload("UsersG.PATsG"). // have to be specifies as this is nester reference Preload(clause.Associations). - First(&account, idQueryCondition, accountID) + Take(&account, idQueryCondition, accountID) if result.Error != nil { log.WithContext(ctx).Errorf("error when getting account %s from the store: %s", accountID, result.Error) if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -888,7 +901,7 @@ func (s *SqlStore) GetAccount(ctx context.Context, accountID string) (*types.Acc func (s *SqlStore) GetAccountByUser(ctx context.Context, userID string) (*types.Account, error) { var user types.User - result := s.db.Select("account_id").First(&user, idQueryCondition, userID) + result := s.db.Select("account_id").Take(&user, idQueryCondition, userID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.Errorf(status.NotFound, "account not found: index lookup failed") @@ -905,7 +918,7 @@ func (s *SqlStore) GetAccountByUser(ctx context.Context, userID string) (*types. func (s *SqlStore) GetAccountByPeerID(ctx context.Context, peerID string) (*types.Account, error) { var peer nbpeer.Peer - result := s.db.Select("account_id").First(&peer, idQueryCondition, peerID) + result := s.db.Select("account_id").Take(&peer, idQueryCondition, peerID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.Errorf(status.NotFound, "account not found: index lookup failed") @@ -922,7 +935,7 @@ func (s *SqlStore) GetAccountByPeerID(ctx context.Context, peerID string) (*type func (s *SqlStore) GetAccountByPeerPubKey(ctx context.Context, peerKey string) (*types.Account, error) { var peer nbpeer.Peer - result := s.db.Select("account_id").First(&peer, GetKeyQueryCondition(s), peerKey) + result := s.db.Select("account_id").Take(&peer, GetKeyQueryCondition(s), peerKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -954,7 +967,7 @@ func (s *SqlStore) GetAnyAccountID(ctx context.Context) (string, error) { func (s *SqlStore) GetAccountIDByPeerPubKey(ctx context.Context, peerKey string) (string, error) { var peer nbpeer.Peer var accountID string - result := s.db.Model(&peer).Select("account_id").Where(GetKeyQueryCondition(s), peerKey).First(&accountID) + result := s.db.Model(&peer).Select("account_id").Where(GetKeyQueryCondition(s), peerKey).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.Errorf(status.NotFound, "account not found: index lookup failed") @@ -973,7 +986,7 @@ func (s *SqlStore) GetAccountIDByUserID(ctx context.Context, lockStrength Lockin var accountID string result := tx.Model(&types.User{}). - Select("account_id").Where(idQueryCondition, userID).First(&accountID) + Select("account_id").Where(idQueryCondition, userID).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.Errorf(status.NotFound, "account not found: index lookup failed") @@ -992,7 +1005,7 @@ func (s *SqlStore) GetAccountIDByPeerID(ctx context.Context, lockStrength Lockin var accountID string result := tx.Model(&nbpeer.Peer{}). - Select("account_id").Where(idQueryCondition, peerID).First(&accountID) + Select("account_id").Where(idQueryCondition, peerID).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.Errorf(status.NotFound, "peer %s account not found", peerID) @@ -1005,7 +1018,7 @@ func (s *SqlStore) GetAccountIDByPeerID(ctx context.Context, lockStrength Lockin func (s *SqlStore) GetAccountIDBySetupKey(ctx context.Context, setupKey string) (string, error) { var accountID string - result := s.db.Model(&types.SetupKey{}).Select("account_id").Where(GetKeyQueryCondition(s), setupKey).First(&accountID) + result := s.db.Model(&types.SetupKey{}).Select("account_id").Where(GetKeyQueryCondition(s), setupKey).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.NewSetupKeyNotFoundError(setupKey) @@ -1076,13 +1089,16 @@ func (s *SqlStore) GetPeerLabelsInAccount(ctx context.Context, lockStrength Lock } func (s *SqlStore) GetAccountNetwork(ctx context.Context, lockStrength LockingStrength, accountID string) (*types.Network, error) { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + tx := s.db if lockStrength != LockingStrengthNone { tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) } var accountNetwork types.AccountNetwork - if err := tx.Model(&types.Account{}).Where(idQueryCondition, accountID).First(&accountNetwork).Error; err != nil { + if err := tx.WithContext(ctx).Model(&types.Account{}).Where(idQueryCondition, accountID).Take(&accountNetwork).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.NewAccountNotFoundError(accountID) } @@ -1092,13 +1108,16 @@ func (s *SqlStore) GetAccountNetwork(ctx context.Context, lockStrength LockingSt } func (s *SqlStore) GetPeerByPeerPubKey(ctx context.Context, lockStrength LockingStrength, peerKey string) (*nbpeer.Peer, error) { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + tx := s.db if lockStrength != LockingStrengthNone { tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) } var peer nbpeer.Peer - result := tx.First(&peer, GetKeyQueryCondition(s), peerKey) + result := tx.WithContext(ctx).Take(&peer, GetKeyQueryCondition(s), peerKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -1117,7 +1136,7 @@ func (s *SqlStore) GetAccountSettings(ctx context.Context, lockStrength LockingS } var accountSettings types.AccountSettings - if err := tx.Model(&types.Account{}).Where(idQueryCondition, accountID).First(&accountSettings).Error; err != nil { + if err := tx.Model(&types.Account{}).Where(idQueryCondition, accountID).Take(&accountSettings).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.Errorf(status.NotFound, "settings not found") } @@ -1134,7 +1153,7 @@ func (s *SqlStore) GetAccountCreatedBy(ctx context.Context, lockStrength Locking var createdBy string result := tx.Model(&types.Account{}). - Select("created_by").First(&createdBy, idQueryCondition, accountID) + Select("created_by").Take(&createdBy, idQueryCondition, accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.NewAccountNotFoundError(accountID) @@ -1147,8 +1166,11 @@ func (s *SqlStore) GetAccountCreatedBy(ctx context.Context, lockStrength Locking // SaveUserLastLogin stores the last login time for a user in DB. func (s *SqlStore) SaveUserLastLogin(ctx context.Context, accountID, userID string, lastLogin time.Time) error { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + var user types.User - result := s.db.First(&user, accountAndIDQueryCondition, accountID, userID) + result := s.db.WithContext(ctx).Take(&user, accountAndIDQueryCondition, accountID, userID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return status.NewUserNotFoundError(userID) @@ -1171,7 +1193,7 @@ func (s *SqlStore) GetPostureCheckByChecksDefinition(accountID string, checks *p } var postureCheck posture.Checks - err = s.db.Where("account_id = ? AND checks = ?", accountID, string(definitionJSON)).First(&postureCheck).Error + err = s.db.Where("account_id = ? AND checks = ?", accountID, string(definitionJSON)).Take(&postureCheck).Error if err != nil { return nil, err } @@ -1329,14 +1351,17 @@ func NewMysqlStoreFromSqlStore(ctx context.Context, sqliteStore *SqlStore, dsn s } func (s *SqlStore) GetSetupKeyBySecret(ctx context.Context, lockStrength LockingStrength, key string) (*types.SetupKey, error) { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + tx := s.db if lockStrength != LockingStrengthNone { tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) } var setupKey types.SetupKey - result := tx. - First(&setupKey, GetKeyQueryCondition(s), key) + result := tx.WithContext(ctx). + Take(&setupKey, GetKeyQueryCondition(s), key) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -1349,7 +1374,10 @@ func (s *SqlStore) GetSetupKeyBySecret(ctx context.Context, lockStrength Locking } func (s *SqlStore) IncrementSetupKeyUsage(ctx context.Context, setupKeyID string) error { - result := s.db.Model(&types.SetupKey{}). + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + + result := s.db.WithContext(ctx).Model(&types.SetupKey{}). Where(idQueryCondition, setupKeyID). Updates(map[string]interface{}{ "used_times": gorm.Expr("used_times + 1"), @@ -1369,8 +1397,11 @@ 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, accountID string, peerID string) error { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + var groupID string - _ = s.db.Model(types.Group{}). + _ = s.db.WithContext(ctx).Model(types.Group{}). Select("id"). Where("account_id = ? AND name = ?", accountID, "All"). Limit(1). @@ -1398,13 +1429,16 @@ func (s *SqlStore) AddPeerToAllGroup(ctx context.Context, accountID string, peer // AddPeerToGroup adds a peer to a group func (s *SqlStore) AddPeerToGroup(ctx context.Context, accountID, peerID, groupID string) error { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + peer := &types.GroupPeer{ AccountID: accountID, GroupID: groupID, PeerID: peerID, } - err := s.db.Clauses(clause.OnConflict{ + err := s.db.WithContext(ctx).Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "group_id"}, {Name: "peer_id"}}, DoNothing: true, }).Create(peer).Error @@ -1446,7 +1480,7 @@ func (s *SqlStore) RemovePeerFromAllGroups(ctx context.Context, peerID string) e // AddResourceToGroup adds a resource to a group. Method always needs to run n a transaction func (s *SqlStore) AddResourceToGroup(ctx context.Context, accountId string, groupID string, resource *types.Resource) error { var group types.Group - result := s.db.Where(accountAndIDQueryCondition, accountId, groupID).First(&group) + result := s.db.Where(accountAndIDQueryCondition, accountId, groupID).Take(&group) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return status.NewGroupNotFoundError(groupID) @@ -1473,7 +1507,7 @@ func (s *SqlStore) AddResourceToGroup(ctx context.Context, accountId string, gro // RemoveResourceFromGroup removes a resource from a group. Method always needs to run in a transaction func (s *SqlStore) RemoveResourceFromGroup(ctx context.Context, accountId string, groupID string, resourceID string) error { var group types.Group - result := s.db.Where(accountAndIDQueryCondition, accountId, groupID).First(&group) + result := s.db.Where(accountAndIDQueryCondition, accountId, groupID).Take(&group) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return status.NewGroupNotFoundError(groupID) @@ -1593,8 +1627,11 @@ func (s *SqlStore) GetUserPeers(ctx context.Context, lockStrength LockingStrengt return peers, nil } -func (s *SqlStore) AddPeerToAccount(ctx context.Context, lockStrength LockingStrength, peer *nbpeer.Peer) error { - if err := s.db.Create(peer).Error; err != nil { +func (s *SqlStore) AddPeerToAccount(ctx context.Context, peer *nbpeer.Peer) error { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + + if err := s.db.WithContext(ctx).Create(peer).Error; err != nil { return status.Errorf(status.Internal, "issue adding peer to account: %s", err) } @@ -1610,7 +1647,7 @@ func (s *SqlStore) GetPeerByID(ctx context.Context, lockStrength LockingStrength var peer *nbpeer.Peer result := tx. - First(&peer, accountAndIDQueryCondition, accountID, peerID) + Take(&peer, accountAndIDQueryCondition, accountID, peerID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewPeerNotFoundError(peerID) @@ -1705,9 +1742,8 @@ func (s *SqlStore) GetAllEphemeralPeers(ctx context.Context, lockStrength Lockin } // DeletePeer removes a peer from the store. -func (s *SqlStore) DeletePeer(ctx context.Context, lockStrength LockingStrength, accountID string, peerID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&nbpeer.Peer{}, accountAndIDQueryCondition, accountID, peerID) +func (s *SqlStore) DeletePeer(ctx context.Context, accountID string, peerID string) error { + result := s.db.Delete(&nbpeer.Peer{}, accountAndIDQueryCondition, accountID, peerID) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to delete peer from the store: %s", err) return status.Errorf(status.Internal, "failed to delete peer from store") @@ -1720,9 +1756,11 @@ func (s *SqlStore) DeletePeer(ctx context.Context, lockStrength LockingStrength, return nil } -func (s *SqlStore) IncrementNetworkSerial(ctx context.Context, lockStrength LockingStrength, accountId string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Model(&types.Account{}).Where(idQueryCondition, accountId).Update("network_serial", gorm.Expr("network_serial + 1")) +func (s *SqlStore) IncrementNetworkSerial(ctx context.Context, accountId string) error { + ctx, cancel := getDebuggingCtx(ctx) + defer cancel() + + result := s.db.WithContext(ctx).Model(&types.Account{}).Where(idQueryCondition, accountId).Update("network_serial", gorm.Expr("network_serial + 1")) if result.Error != nil { log.WithContext(ctx).Errorf("failed to increment network serial count in store: %v", result.Error) return status.Errorf(status.Internal, "failed to increment network serial count in store") @@ -1772,7 +1810,7 @@ func (s *SqlStore) GetAccountDNSSettings(ctx context.Context, lockStrength Locki var accountDNSSettings types.AccountDNSSettings result := tx.Model(&types.Account{}). - First(&accountDNSSettings, idQueryCondition, accountID) + Take(&accountDNSSettings, idQueryCondition, accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewAccountNotFoundError(accountID) @@ -1792,7 +1830,7 @@ func (s *SqlStore) AccountExists(ctx context.Context, lockStrength LockingStreng var accountID string result := tx.Model(&types.Account{}). - Select("id").First(&accountID, idQueryCondition, id) + Select("id").Take(&accountID, idQueryCondition, id) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return false, nil @@ -1812,7 +1850,7 @@ func (s *SqlStore) GetAccountDomainAndCategory(ctx context.Context, lockStrength var account types.Account result := tx.Model(&types.Account{}).Select("domain", "domain_category"). - Where(idQueryCondition, accountID).First(&account) + Where(idQueryCondition, accountID).Take(&account) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", "", status.Errorf(status.NotFound, "account not found") @@ -1831,7 +1869,7 @@ func (s *SqlStore) GetGroupByID(ctx context.Context, lockStrength LockingStrengt } var group *types.Group - result := tx.Preload(clause.Associations).First(&group, accountAndIDQueryCondition, accountID, groupID) + result := tx.Preload(clause.Associations).Take(&group, accountAndIDQueryCondition, accountID, groupID) if err := result.Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.NewGroupNotFoundError(groupID) @@ -1900,7 +1938,7 @@ func (s *SqlStore) GetGroupsByIDs(ctx context.Context, lockStrength LockingStren } // CreateGroup creates a group in the store. -func (s *SqlStore) CreateGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error { +func (s *SqlStore) CreateGroup(ctx context.Context, group *types.Group) error { if group == nil { return status.Errorf(status.InvalidArgument, "group is nil") } @@ -1914,7 +1952,7 @@ func (s *SqlStore) CreateGroup(ctx context.Context, lockStrength LockingStrength } // UpdateGroup updates a group in the store. -func (s *SqlStore) UpdateGroup(ctx context.Context, lockStrength LockingStrength, group *types.Group) error { +func (s *SqlStore) UpdateGroup(ctx context.Context, group *types.Group) error { if group == nil { return status.Errorf(status.InvalidArgument, "group is nil") } @@ -1928,9 +1966,8 @@ func (s *SqlStore) UpdateGroup(ctx context.Context, lockStrength LockingStrength } // 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). +func (s *SqlStore) DeleteGroup(ctx context.Context, accountID, groupID string) error { + result := s.db.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) @@ -1945,9 +1982,8 @@ 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). +func (s *SqlStore) DeleteGroups(ctx context.Context, accountID string, groupIDs []string) error { + result := s.db.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) @@ -1985,7 +2021,7 @@ func (s *SqlStore) GetPolicyByID(ctx context.Context, lockStrength LockingStreng var policy *types.Policy result := tx.Preload(clause.Associations). - First(&policy, accountAndIDQueryCondition, accountID, policyID) + Take(&policy, accountAndIDQueryCondition, accountID, policyID) if err := result.Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.NewPolicyNotFoundError(policyID) @@ -1997,8 +2033,8 @@ func (s *SqlStore) GetPolicyByID(ctx context.Context, lockStrength LockingStreng return policy, nil } -func (s *SqlStore) CreatePolicy(ctx context.Context, lockStrength LockingStrength, policy *types.Policy) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Create(policy) +func (s *SqlStore) CreatePolicy(ctx context.Context, policy *types.Policy) error { + result := s.db.Create(policy) if result.Error != nil { log.WithContext(ctx).Errorf("failed to create policy in store: %s", result.Error) return status.Errorf(status.Internal, "failed to create policy in store") @@ -2008,9 +2044,8 @@ func (s *SqlStore) CreatePolicy(ctx context.Context, lockStrength LockingStrengt } // SavePolicy saves a policy to the database. -func (s *SqlStore) SavePolicy(ctx context.Context, lockStrength LockingStrength, policy *types.Policy) error { - result := s.db.Session(&gorm.Session{FullSaveAssociations: true}). - Clauses(clause.Locking{Strength: string(lockStrength)}).Save(policy) +func (s *SqlStore) SavePolicy(ctx context.Context, policy *types.Policy) error { + result := s.db.Session(&gorm.Session{FullSaveAssociations: true}).Save(policy) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to save policy to the store: %s", err) return status.Errorf(status.Internal, "failed to save policy to store") @@ -2018,13 +2053,13 @@ func (s *SqlStore) SavePolicy(ctx context.Context, lockStrength LockingStrength, return nil } -func (s *SqlStore) DeletePolicy(ctx context.Context, lockStrength LockingStrength, accountID, policyID string) error { +func (s *SqlStore) DeletePolicy(ctx context.Context, accountID, policyID string) error { return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if err := tx.Where("policy_id = ?", policyID).Delete(&types.PolicyRule{}).Error; err != nil { return fmt.Errorf("delete policy rules: %w", err) } - result := tx.Clauses(clause.Locking{Strength: string(lockStrength)}). + result := tx. Where(accountAndIDQueryCondition, accountID, policyID). Delete(&types.Policy{}) @@ -2067,7 +2102,7 @@ func (s *SqlStore) GetPostureChecksByID(ctx context.Context, lockStrength Lockin var postureCheck *posture.Checks result := tx. - First(&postureCheck, accountAndIDQueryCondition, accountID, postureChecksID) + Take(&postureCheck, accountAndIDQueryCondition, accountID, postureChecksID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewPostureChecksNotFoundError(postureChecksID) @@ -2102,8 +2137,8 @@ func (s *SqlStore) GetPostureChecksByIDs(ctx context.Context, lockStrength Locki } // SavePostureChecks saves a posture checks to the database. -func (s *SqlStore) SavePostureChecks(ctx context.Context, lockStrength LockingStrength, postureCheck *posture.Checks) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(postureCheck) +func (s *SqlStore) SavePostureChecks(ctx context.Context, postureCheck *posture.Checks) error { + result := s.db.Save(postureCheck) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save posture checks to store: %s", result.Error) return status.Errorf(status.Internal, "failed to save posture checks to store") @@ -2113,9 +2148,8 @@ func (s *SqlStore) SavePostureChecks(ctx context.Context, lockStrength LockingSt } // DeletePostureChecks deletes a posture checks from the database. -func (s *SqlStore) DeletePostureChecks(ctx context.Context, lockStrength LockingStrength, accountID, postureChecksID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&posture.Checks{}, accountAndIDQueryCondition, accountID, postureChecksID) +func (s *SqlStore) DeletePostureChecks(ctx context.Context, accountID, postureChecksID string) error { + result := s.db.Delete(&posture.Checks{}, accountAndIDQueryCondition, accountID, postureChecksID) if result.Error != nil { log.WithContext(ctx).Errorf("failed to delete posture checks from store: %s", result.Error) return status.Errorf(status.Internal, "failed to delete posture checks from store") @@ -2130,9 +2164,13 @@ func (s *SqlStore) DeletePostureChecks(ctx context.Context, lockStrength Locking // GetAccountRoutes retrieves network routes for an account. func (s *SqlStore) GetAccountRoutes(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*route.Route, error) { + tx := s.db + if lockStrength != LockingStrengthNone { + tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) + } + var routes []*route.Route - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Find(&routes, accountIDCondition, accountID) + result := tx.Find(&routes, accountIDCondition, accountID) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to get routes from the store: %s", err) return nil, status.Errorf(status.Internal, "failed to get routes from store") @@ -2143,9 +2181,13 @@ func (s *SqlStore) GetAccountRoutes(ctx context.Context, lockStrength LockingStr // GetRouteByID retrieves a route by its ID and account ID. func (s *SqlStore) GetRouteByID(ctx context.Context, lockStrength LockingStrength, accountID string, routeID string) (*route.Route, error) { + tx := s.db + if lockStrength != LockingStrengthNone { + tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) + } + var route *route.Route - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - First(&route, accountAndIDQueryCondition, accountID, routeID) + result := tx.Take(&route, accountAndIDQueryCondition, accountID, routeID) if err := result.Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.NewRouteNotFoundError(routeID) @@ -2158,8 +2200,8 @@ func (s *SqlStore) GetRouteByID(ctx context.Context, lockStrength LockingStrengt } // SaveRoute saves a route to the database. -func (s *SqlStore) SaveRoute(ctx context.Context, lockStrength LockingStrength, route *route.Route) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(route) +func (s *SqlStore) SaveRoute(ctx context.Context, route *route.Route) error { + result := s.db.Save(route) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to save route to the store: %s", err) return status.Errorf(status.Internal, "failed to save route to store") @@ -2169,9 +2211,8 @@ func (s *SqlStore) SaveRoute(ctx context.Context, lockStrength LockingStrength, } // DeleteRoute deletes a route from the database. -func (s *SqlStore) DeleteRoute(ctx context.Context, lockStrength LockingStrength, accountID, routeID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&route.Route{}, accountAndIDQueryCondition, accountID, routeID) +func (s *SqlStore) DeleteRoute(ctx context.Context, accountID, routeID string) error { + result := s.db.Delete(&route.Route{}, accountAndIDQueryCondition, accountID, routeID) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to delete route from the store: %s", err) return status.Errorf(status.Internal, "failed to delete route from store") @@ -2210,8 +2251,7 @@ func (s *SqlStore) GetSetupKeyByID(ctx context.Context, lockStrength LockingStre } var setupKey *types.SetupKey - result := tx.Clauses(clause.Locking{Strength: string(lockStrength)}). - First(&setupKey, accountAndIDQueryCondition, accountID, setupKeyID) + result := tx.Take(&setupKey, accountAndIDQueryCondition, accountID, setupKeyID) if err := result.Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.NewSetupKeyNotFoundError(setupKeyID) @@ -2224,8 +2264,8 @@ func (s *SqlStore) GetSetupKeyByID(ctx context.Context, lockStrength LockingStre } // SaveSetupKey saves a setup key to the database. -func (s *SqlStore) SaveSetupKey(ctx context.Context, lockStrength LockingStrength, setupKey *types.SetupKey) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(setupKey) +func (s *SqlStore) SaveSetupKey(ctx context.Context, setupKey *types.SetupKey) error { + result := s.db.Save(setupKey) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save setup key to store: %s", result.Error) return status.Errorf(status.Internal, "failed to save setup key to store") @@ -2235,8 +2275,8 @@ func (s *SqlStore) SaveSetupKey(ctx context.Context, lockStrength LockingStrengt } // DeleteSetupKey deletes a setup key from the database. -func (s *SqlStore) DeleteSetupKey(ctx context.Context, lockStrength LockingStrength, accountID, keyID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Delete(&types.SetupKey{}, accountAndIDQueryCondition, accountID, keyID) +func (s *SqlStore) DeleteSetupKey(ctx context.Context, accountID, keyID string) error { + result := s.db.Delete(&types.SetupKey{}, accountAndIDQueryCondition, accountID, keyID) if result.Error != nil { log.WithContext(ctx).Errorf("failed to delete setup key from store: %s", result.Error) return status.Errorf(status.Internal, "failed to delete setup key from store") @@ -2275,7 +2315,7 @@ func (s *SqlStore) GetNameServerGroupByID(ctx context.Context, lockStrength Lock var nsGroup *nbdns.NameServerGroup result := tx. - First(&nsGroup, accountAndIDQueryCondition, accountID, nsGroupID) + Take(&nsGroup, accountAndIDQueryCondition, accountID, nsGroupID) if err := result.Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.NewNameServerGroupNotFoundError(nsGroupID) @@ -2288,8 +2328,8 @@ func (s *SqlStore) GetNameServerGroupByID(ctx context.Context, lockStrength Lock } // SaveNameServerGroup saves a name server group to the database. -func (s *SqlStore) SaveNameServerGroup(ctx context.Context, lockStrength LockingStrength, nameServerGroup *nbdns.NameServerGroup) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(nameServerGroup) +func (s *SqlStore) SaveNameServerGroup(ctx context.Context, nameServerGroup *nbdns.NameServerGroup) error { + result := s.db.Save(nameServerGroup) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to save name server group to the store: %s", err) return status.Errorf(status.Internal, "failed to save name server group to store") @@ -2298,8 +2338,8 @@ func (s *SqlStore) SaveNameServerGroup(ctx context.Context, lockStrength Locking } // DeleteNameServerGroup deletes a name server group from the database. -func (s *SqlStore) DeleteNameServerGroup(ctx context.Context, lockStrength LockingStrength, accountID, nsGroupID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Delete(&nbdns.NameServerGroup{}, accountAndIDQueryCondition, accountID, nsGroupID) +func (s *SqlStore) DeleteNameServerGroup(ctx context.Context, accountID, nsGroupID string) error { + result := s.db.Delete(&nbdns.NameServerGroup{}, accountAndIDQueryCondition, accountID, nsGroupID) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to delete name server group from the store: %s", err) return status.Errorf(status.Internal, "failed to delete name server group from store") @@ -2313,8 +2353,8 @@ func (s *SqlStore) DeleteNameServerGroup(ctx context.Context, lockStrength Locki } // SaveDNSSettings saves the DNS settings to the store. -func (s *SqlStore) SaveDNSSettings(ctx context.Context, lockStrength LockingStrength, accountID string, settings *types.DNSSettings) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Model(&types.Account{}). +func (s *SqlStore) SaveDNSSettings(ctx context.Context, accountID string, settings *types.DNSSettings) error { + result := s.db.Model(&types.Account{}). Where(idQueryCondition, accountID).Updates(&types.AccountDNSSettings{DNSSettings: *settings}) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save dns settings to store: %v", result.Error) @@ -2329,8 +2369,8 @@ func (s *SqlStore) SaveDNSSettings(ctx context.Context, lockStrength LockingStre } // SaveAccountSettings stores the account settings in DB. -func (s *SqlStore) SaveAccountSettings(ctx context.Context, lockStrength LockingStrength, accountID string, settings *types.Settings) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Model(&types.Account{}). +func (s *SqlStore) SaveAccountSettings(ctx context.Context, accountID string, settings *types.Settings) error { + result := s.db.Model(&types.Account{}). Select("*").Where(idQueryCondition, accountID).Updates(&types.AccountSettings{Settings: settings}) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save account settings to store: %v", result.Error) @@ -2367,8 +2407,7 @@ func (s *SqlStore) GetNetworkByID(ctx context.Context, lockStrength LockingStren } var network *networkTypes.Network - result := tx. - First(&network, accountAndIDQueryCondition, accountID, networkID) + result := tx.Take(&network, accountAndIDQueryCondition, accountID, networkID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewNetworkNotFoundError(networkID) @@ -2381,8 +2420,8 @@ func (s *SqlStore) GetNetworkByID(ctx context.Context, lockStrength LockingStren return network, nil } -func (s *SqlStore) SaveNetwork(ctx context.Context, lockStrength LockingStrength, network *networkTypes.Network) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(network) +func (s *SqlStore) SaveNetwork(ctx context.Context, network *networkTypes.Network) error { + result := s.db.Save(network) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save network to store: %v", result.Error) return status.Errorf(status.Internal, "failed to save network to store") @@ -2391,9 +2430,8 @@ func (s *SqlStore) SaveNetwork(ctx context.Context, lockStrength LockingStrength return nil } -func (s *SqlStore) DeleteNetwork(ctx context.Context, lockStrength LockingStrength, accountID, networkID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&networkTypes.Network{}, accountAndIDQueryCondition, accountID, networkID) +func (s *SqlStore) DeleteNetwork(ctx context.Context, accountID, networkID string) error { + result := s.db.Delete(&networkTypes.Network{}, accountAndIDQueryCondition, accountID, networkID) if result.Error != nil { log.WithContext(ctx).Errorf("failed to delete network from store: %v", result.Error) return status.Errorf(status.Internal, "failed to delete network from store") @@ -2448,7 +2486,7 @@ func (s *SqlStore) GetNetworkRouterByID(ctx context.Context, lockStrength Lockin var netRouter *routerTypes.NetworkRouter result := tx. - First(&netRouter, accountAndIDQueryCondition, accountID, routerID) + Take(&netRouter, accountAndIDQueryCondition, accountID, routerID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewNetworkRouterNotFoundError(routerID) @@ -2460,8 +2498,8 @@ func (s *SqlStore) GetNetworkRouterByID(ctx context.Context, lockStrength Lockin return netRouter, nil } -func (s *SqlStore) SaveNetworkRouter(ctx context.Context, lockStrength LockingStrength, router *routerTypes.NetworkRouter) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(router) +func (s *SqlStore) SaveNetworkRouter(ctx context.Context, router *routerTypes.NetworkRouter) error { + result := s.db.Save(router) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save network router to store: %v", result.Error) return status.Errorf(status.Internal, "failed to save network router to store") @@ -2470,9 +2508,8 @@ func (s *SqlStore) SaveNetworkRouter(ctx context.Context, lockStrength LockingSt return nil } -func (s *SqlStore) DeleteNetworkRouter(ctx context.Context, lockStrength LockingStrength, accountID, routerID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&routerTypes.NetworkRouter{}, accountAndIDQueryCondition, accountID, routerID) +func (s *SqlStore) DeleteNetworkRouter(ctx context.Context, accountID, routerID string) error { + result := s.db.Delete(&routerTypes.NetworkRouter{}, accountAndIDQueryCondition, accountID, routerID) if result.Error != nil { log.WithContext(ctx).Errorf("failed to delete network router from store: %v", result.Error) return status.Errorf(status.Internal, "failed to delete network router from store") @@ -2527,7 +2564,7 @@ func (s *SqlStore) GetNetworkResourceByID(ctx context.Context, lockStrength Lock var netResources *resourceTypes.NetworkResource result := tx. - First(&netResources, accountAndIDQueryCondition, accountID, resourceID) + Take(&netResources, accountAndIDQueryCondition, accountID, resourceID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewNetworkResourceNotFoundError(resourceID) @@ -2547,7 +2584,7 @@ func (s *SqlStore) GetNetworkResourceByName(ctx context.Context, lockStrength Lo var netResources *resourceTypes.NetworkResource result := tx. - First(&netResources, "account_id = ? AND name = ?", accountID, resourceName) + Take(&netResources, "account_id = ? AND name = ?", accountID, resourceName) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewNetworkResourceNotFoundError(resourceName) @@ -2559,8 +2596,8 @@ func (s *SqlStore) GetNetworkResourceByName(ctx context.Context, lockStrength Lo return netResources, nil } -func (s *SqlStore) SaveNetworkResource(ctx context.Context, lockStrength LockingStrength, resource *resourceTypes.NetworkResource) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(resource) +func (s *SqlStore) SaveNetworkResource(ctx context.Context, resource *resourceTypes.NetworkResource) error { + result := s.db.Save(resource) if result.Error != nil { log.WithContext(ctx).Errorf("failed to save network resource to store: %v", result.Error) return status.Errorf(status.Internal, "failed to save network resource to store") @@ -2569,9 +2606,8 @@ func (s *SqlStore) SaveNetworkResource(ctx context.Context, lockStrength Locking return nil } -func (s *SqlStore) DeleteNetworkResource(ctx context.Context, lockStrength LockingStrength, accountID, resourceID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&resourceTypes.NetworkResource{}, accountAndIDQueryCondition, accountID, resourceID) +func (s *SqlStore) DeleteNetworkResource(ctx context.Context, accountID, resourceID string) error { + result := s.db.Delete(&resourceTypes.NetworkResource{}, accountAndIDQueryCondition, accountID, resourceID) if result.Error != nil { log.WithContext(ctx).Errorf("failed to delete network resource from store: %v", result.Error) return status.Errorf(status.Internal, "failed to delete network resource from store") @@ -2592,7 +2628,7 @@ func (s *SqlStore) GetPATByHashedToken(ctx context.Context, lockStrength Locking } var pat types.PersonalAccessToken - result := tx.First(&pat, "hashed_token = ?", hashedToken) + result := tx.Take(&pat, "hashed_token = ?", hashedToken) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewPATNotFoundError(hashedToken) @@ -2613,7 +2649,7 @@ func (s *SqlStore) GetPATByID(ctx context.Context, lockStrength LockingStrength, var pat types.PersonalAccessToken result := tx. - First(&pat, "id = ? AND user_id = ?", patID, userID) + Take(&pat, "id = ? AND user_id = ?", patID, userID) if err := result.Error; err != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewPATNotFoundError(patID) @@ -2643,13 +2679,13 @@ func (s *SqlStore) GetUserPATs(ctx context.Context, lockStrength LockingStrength } // MarkPATUsed marks a personal access token as used. -func (s *SqlStore) MarkPATUsed(ctx context.Context, lockStrength LockingStrength, patID string) error { +func (s *SqlStore) MarkPATUsed(ctx context.Context, patID string) error { patCopy := types.PersonalAccessToken{ LastUsed: util.ToPtr(time.Now().UTC()), } fieldsToUpdate := []string{"last_used"} - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Select(fieldsToUpdate). + result := s.db.Select(fieldsToUpdate). Where(idQueryCondition, patID).Updates(&patCopy) if result.Error != nil { log.WithContext(ctx).Errorf("failed to mark pat as used: %s", result.Error) @@ -2664,8 +2700,8 @@ func (s *SqlStore) MarkPATUsed(ctx context.Context, lockStrength LockingStrength } // SavePAT saves a personal access token to the database. -func (s *SqlStore) SavePAT(ctx context.Context, lockStrength LockingStrength, pat *types.PersonalAccessToken) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}).Save(pat) +func (s *SqlStore) SavePAT(ctx context.Context, pat *types.PersonalAccessToken) error { + result := s.db.Save(pat) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to save pat to the store: %s", err) return status.Errorf(status.Internal, "failed to save pat to store") @@ -2675,9 +2711,8 @@ func (s *SqlStore) SavePAT(ctx context.Context, lockStrength LockingStrength, pa } // DeletePAT deletes a personal access token from the database. -func (s *SqlStore) DeletePAT(ctx context.Context, lockStrength LockingStrength, userID, patID string) error { - result := s.db.Clauses(clause.Locking{Strength: string(lockStrength)}). - Delete(&types.PersonalAccessToken{}, "user_id = ? AND id = ?", userID, patID) +func (s *SqlStore) DeletePAT(ctx context.Context, userID, patID string) error { + result := s.db.Delete(&types.PersonalAccessToken{}, "user_id = ? AND id = ?", userID, patID) if err := result.Error; err != nil { log.WithContext(ctx).Errorf("failed to delete pat from the store: %s", err) return status.Errorf(status.Internal, "failed to delete pat from store") @@ -2700,7 +2735,7 @@ func (s *SqlStore) GetPeerByIP(ctx context.Context, lockStrength LockingStrength var peer nbpeer.Peer result := tx. - First(&peer, "account_id = ? AND ip = ?", accountID, jsonValue) + Take(&peer, "account_id = ? AND ip = ?", accountID, jsonValue) if result.Error != nil { // no logging here return nil, status.Errorf(status.Internal, "failed to get peer from store") @@ -2767,3 +2802,33 @@ func (s *SqlStore) GetAccountGroupPeers(ctx context.Context, lockStrength Lockin return groupPeers, nil } + +func getDebuggingCtx(grpcCtx context.Context) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + userID, ok := grpcCtx.Value(nbcontext.UserIDKey).(string) + if ok { + //nolint + ctx = context.WithValue(ctx, nbcontext.UserIDKey, userID) + } + + requestID, ok := grpcCtx.Value(nbcontext.RequestIDKey).(string) + if ok { + //nolint + ctx = context.WithValue(ctx, nbcontext.RequestIDKey, requestID) + } + + accountID, ok := grpcCtx.Value(nbcontext.AccountIDKey).(string) + if ok { + //nolint + ctx = context.WithValue(ctx, nbcontext.AccountIDKey, accountID) + } + + go func() { + select { + case <-ctx.Done(): + case <-grpcCtx.Done(): + log.WithContext(grpcCtx).Warnf("grpc context ended early, error: %v", grpcCtx.Err()) + } + }() + return ctx, cancel +} diff --git a/management/server/store/sql_store_test.go b/management/server/store/sql_store_test.go index 44bb3f599..935b0a595 100644 --- a/management/server/store/sql_store_test.go +++ b/management/server/store/sql_store_test.go @@ -27,11 +27,11 @@ 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/management/server/types" "github.com/netbirdio/netbird/management/server/util" nbroute "github.com/netbirdio/netbird/route" route2 "github.com/netbirdio/netbird/route" + "github.com/netbirdio/netbird/shared/management/status" ) func runTestForAllEngines(t *testing.T, testDataFile string, f func(t *testing.T, store Store)) { @@ -401,11 +401,11 @@ func TestSqlite_DeleteAccount(t *testing.T) { } for _, network := range account.Networks { - routers, err := store.GetNetworkRoutersByNetID(context.Background(), LockingStrengthShare, account.Id, network.ID) + routers, err := store.GetNetworkRoutersByNetID(context.Background(), LockingStrengthNone, account.Id, network.ID) require.NoError(t, err, "expecting no error after removing DeleteAccount when searching for network routers") require.Len(t, routers, 0, "expecting no network routers to be found after DeleteAccount") - resources, err := store.GetNetworkResourcesByNetID(context.Background(), LockingStrengthShare, account.Id, network.ID) + resources, err := store.GetNetworkResourcesByNetID(context.Background(), LockingStrengthNone, account.Id, network.ID) require.NoError(t, err, "expecting no error after removing DeleteAccount when searching for network resources") require.Len(t, resources, 0, "expecting no network resources to be found after DeleteAccount") } @@ -459,7 +459,7 @@ func TestSqlStore_SavePeer(t *testing.T) { CreatedAt: time.Now().UTC(), } ctx := context.Background() - err = store.SavePeer(ctx, LockingStrengthUpdate, account.Id, peer) + err = store.SavePeer(ctx, account.Id, peer) assert.Error(t, err) parsedErr, ok := status.FromError(err) require.True(t, ok) @@ -475,7 +475,7 @@ func TestSqlStore_SavePeer(t *testing.T) { updatedPeer.Status.Connected = false updatedPeer.Meta.Hostname = "updatedpeer" - err = store.SavePeer(ctx, LockingStrengthUpdate, account.Id, updatedPeer) + err = store.SavePeer(ctx, account.Id, updatedPeer) require.NoError(t, err) account, err = store.GetAccount(context.Background(), account.Id) @@ -499,7 +499,7 @@ func TestSqlStore_SavePeerStatus(t *testing.T) { // save status of non-existing peer newStatus := nbpeer.PeerStatus{Connected: false, LastSeen: time.Now().UTC()} - err = store.SavePeerStatus(context.Background(), LockingStrengthUpdate, account.Id, "non-existing-peer", newStatus) + err = store.SavePeerStatus(context.Background(), account.Id, "non-existing-peer", newStatus) assert.Error(t, err) parsedErr, ok := status.FromError(err) require.True(t, ok) @@ -518,7 +518,7 @@ func TestSqlStore_SavePeerStatus(t *testing.T) { err = store.SaveAccount(context.Background(), account) require.NoError(t, err) - err = store.SavePeerStatus(context.Background(), LockingStrengthUpdate, account.Id, "testpeer", newStatus) + err = store.SavePeerStatus(context.Background(), account.Id, "testpeer", newStatus) require.NoError(t, err) account, err = store.GetAccount(context.Background(), account.Id) @@ -532,7 +532,7 @@ func TestSqlStore_SavePeerStatus(t *testing.T) { newStatus.Connected = true - err = store.SavePeerStatus(context.Background(), LockingStrengthUpdate, account.Id, "testpeer", newStatus) + err = store.SavePeerStatus(context.Background(), account.Id, "testpeer", newStatus) require.NoError(t, err) account, err = store.GetAccount(context.Background(), account.Id) @@ -566,7 +566,7 @@ func TestSqlStore_SavePeerLocation(t *testing.T) { Meta: nbpeer.PeerSystemMeta{}, } // error is expected as peer is not in store yet - err = store.SavePeerLocation(context.Background(), LockingStrengthUpdate, account.Id, peer) + err = store.SavePeerLocation(context.Background(), account.Id, peer) assert.Error(t, err) account.Peers[peer.ID] = peer @@ -578,7 +578,7 @@ func TestSqlStore_SavePeerLocation(t *testing.T) { peer.Location.CityName = "Berlin" peer.Location.GeoNameID = 2950159 - err = store.SavePeerLocation(context.Background(), LockingStrengthUpdate, account.Id, account.Peers[peer.ID]) + err = store.SavePeerLocation(context.Background(), account.Id, account.Peers[peer.ID]) assert.NoError(t, err) account, err = store.GetAccount(context.Background(), account.Id) @@ -588,7 +588,7 @@ func TestSqlStore_SavePeerLocation(t *testing.T) { assert.Equal(t, peer.Location, actual) peer.ID = "non-existing-peer" - err = store.SavePeerLocation(context.Background(), LockingStrengthUpdate, account.Id, peer) + err = store.SavePeerLocation(context.Background(), account.Id, peer) assert.Error(t, err) parsedErr, ok := status.FromError(err) require.True(t, ok) @@ -961,7 +961,7 @@ func TestSqlite_GetTakenIPs(t *testing.T) { _, err = store.GetAccount(context.Background(), existingAccountID) require.NoError(t, err) - takenIPs, err := store.GetTakenIPs(context.Background(), LockingStrengthShare, existingAccountID) + takenIPs, err := store.GetTakenIPs(context.Background(), LockingStrengthNone, existingAccountID) require.NoError(t, err) assert.Equal(t, []net.IP{}, takenIPs) @@ -971,10 +971,10 @@ func TestSqlite_GetTakenIPs(t *testing.T) { DNSLabel: "peer1", IP: net.IP{1, 1, 1, 1}, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer1) + err = store.AddPeerToAccount(context.Background(), peer1) require.NoError(t, err) - takenIPs, err = store.GetTakenIPs(context.Background(), LockingStrengthShare, existingAccountID) + takenIPs, err = store.GetTakenIPs(context.Background(), LockingStrengthNone, existingAccountID) require.NoError(t, err) ip1 := net.IP{1, 1, 1, 1}.To16() assert.Equal(t, []net.IP{ip1}, takenIPs) @@ -985,10 +985,10 @@ func TestSqlite_GetTakenIPs(t *testing.T) { DNSLabel: "peer1-1", IP: net.IP{2, 2, 2, 2}, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer2) + err = store.AddPeerToAccount(context.Background(), peer2) require.NoError(t, err) - takenIPs, err = store.GetTakenIPs(context.Background(), LockingStrengthShare, existingAccountID) + takenIPs, err = store.GetTakenIPs(context.Background(), LockingStrengthNone, existingAccountID) require.NoError(t, err) ip2 := net.IP{2, 2, 2, 2}.To16() assert.Equal(t, []net.IP{ip1, ip2}, takenIPs) @@ -1002,7 +1002,7 @@ func TestSqlite_GetPeerLabelsInAccount(t *testing.T) { _, err := store.GetAccount(context.Background(), existingAccountID) require.NoError(t, err) - labels, err := store.GetPeerLabelsInAccount(context.Background(), LockingStrengthShare, existingAccountID, peerHostname) + labels, err := store.GetPeerLabelsInAccount(context.Background(), LockingStrengthNone, existingAccountID, peerHostname) require.NoError(t, err) assert.Equal(t, []string{}, labels) @@ -1012,10 +1012,10 @@ func TestSqlite_GetPeerLabelsInAccount(t *testing.T) { DNSLabel: "peer1", IP: net.IP{1, 1, 1, 1}, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer1) + err = store.AddPeerToAccount(context.Background(), peer1) require.NoError(t, err) - labels, err = store.GetPeerLabelsInAccount(context.Background(), LockingStrengthShare, existingAccountID, peerHostname) + labels, err = store.GetPeerLabelsInAccount(context.Background(), LockingStrengthNone, existingAccountID, peerHostname) require.NoError(t, err) assert.Equal(t, []string{"peer1"}, labels) @@ -1025,10 +1025,10 @@ func TestSqlite_GetPeerLabelsInAccount(t *testing.T) { DNSLabel: "peer1-1", IP: net.IP{2, 2, 2, 2}, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer2) + err = store.AddPeerToAccount(context.Background(), peer2) require.NoError(t, err) - labels, err = store.GetPeerLabelsInAccount(context.Background(), LockingStrengthShare, existingAccountID, peerHostname) + labels, err = store.GetPeerLabelsInAccount(context.Background(), LockingStrengthNone, existingAccountID, peerHostname) require.NoError(t, err) expected := []string{"peer1", "peer1-1"} @@ -1050,7 +1050,7 @@ func Test_AddPeerWithSameDnsLabel(t *testing.T) { AccountID: existingAccountID, DNSLabel: "peer1.domain.test", } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer1) + err = store.AddPeerToAccount(context.Background(), peer1) require.NoError(t, err) peer2 := &nbpeer.Peer{ @@ -1058,7 +1058,7 @@ func Test_AddPeerWithSameDnsLabel(t *testing.T) { AccountID: existingAccountID, DNSLabel: "peer1.domain.test", } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer2) + err = store.AddPeerToAccount(context.Background(), peer2) require.Error(t, err) }) } @@ -1075,7 +1075,7 @@ func Test_AddPeerWithSameIP(t *testing.T) { AccountID: existingAccountID, IP: net.IP{1, 1, 1, 1}, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer1) + err = store.AddPeerToAccount(context.Background(), peer1) require.NoError(t, err) peer2 := &nbpeer.Peer{ @@ -1083,7 +1083,7 @@ func Test_AddPeerWithSameIP(t *testing.T) { AccountID: existingAccountID, IP: net.IP{1, 1, 1, 1}, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer2) + err = store.AddPeerToAccount(context.Background(), peer2) require.Error(t, err) }) } @@ -1101,7 +1101,7 @@ func TestSqlite_GetAccountNetwork(t *testing.T) { _, err = store.GetAccount(context.Background(), existingAccountID) require.NoError(t, err) - network, err := store.GetAccountNetwork(context.Background(), LockingStrengthShare, existingAccountID) + network, err := store.GetAccountNetwork(context.Background(), LockingStrengthNone, existingAccountID) require.NoError(t, err) ip := net.IP{100, 64, 0, 0}.To16() assert.Equal(t, ip, network.Net.IP) @@ -1128,7 +1128,7 @@ func TestSqlite_GetSetupKeyBySecret(t *testing.T) { _, err = store.GetAccount(context.Background(), existingAccountID) require.NoError(t, err) - setupKey, err := store.GetSetupKeyBySecret(context.Background(), LockingStrengthShare, encodedHashedKey) + setupKey, err := store.GetSetupKeyBySecret(context.Background(), LockingStrengthNone, encodedHashedKey) require.NoError(t, err) assert.Equal(t, encodedHashedKey, setupKey.Key) assert.Equal(t, types.HiddenKey(plainKey, 4), setupKey.KeySecret) @@ -1153,21 +1153,21 @@ func TestSqlite_incrementSetupKeyUsage(t *testing.T) { _, err = store.GetAccount(context.Background(), existingAccountID) require.NoError(t, err) - setupKey, err := store.GetSetupKeyBySecret(context.Background(), LockingStrengthShare, encodedHashedKey) + setupKey, err := store.GetSetupKeyBySecret(context.Background(), LockingStrengthNone, encodedHashedKey) require.NoError(t, err) assert.Equal(t, 0, setupKey.UsedTimes) err = store.IncrementSetupKeyUsage(context.Background(), setupKey.Id) require.NoError(t, err) - setupKey, err = store.GetSetupKeyBySecret(context.Background(), LockingStrengthShare, encodedHashedKey) + setupKey, err = store.GetSetupKeyBySecret(context.Background(), LockingStrengthNone, encodedHashedKey) require.NoError(t, err) assert.Equal(t, 1, setupKey.UsedTimes) err = store.IncrementSetupKeyUsage(context.Background(), setupKey.Id) require.NoError(t, err) - setupKey, err = store.GetSetupKeyBySecret(context.Background(), LockingStrengthShare, encodedHashedKey) + setupKey, err = store.GetSetupKeyBySecret(context.Background(), LockingStrengthNone, encodedHashedKey) require.NoError(t, err) assert.Equal(t, 2, setupKey.UsedTimes) } @@ -1188,7 +1188,7 @@ func TestSqlite_CreateAndGetObjectInTransaction(t *testing.T) { Peers: nil, } err = store.ExecuteInTransaction(context.Background(), func(transaction Store) error { - err := transaction.CreateGroup(context.Background(), LockingStrengthUpdate, group) + err := transaction.CreateGroup(context.Background(), group) if err != nil { t.Fatal("failed to save group") return err @@ -1213,7 +1213,7 @@ func TestSqlStore_GetAccountUsers(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" account, err := store.GetAccount(context.Background(), accountID) require.NoError(t, err) - users, err := store.GetAccountUsers(context.Background(), LockingStrengthShare, accountID) + users, err := store.GetAccountUsers(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Len(t, users, len(account.Users)) } @@ -1272,7 +1272,7 @@ func TestSqlite_GetGroupByName(t *testing.T) { } accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" - group, err := store.GetGroupByName(context.Background(), LockingStrengthShare, accountID, "All") + group, err := store.GetGroupByName(context.Background(), LockingStrengthNone, accountID, "All") require.NoError(t, err) require.True(t, group.IsGroupAll()) } @@ -1286,10 +1286,10 @@ func Test_DeleteSetupKeySuccessfully(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" setupKeyID := "A2C8E62B-38F5-4553-B31E-DD66C696CEBB" - err = store.DeleteSetupKey(context.Background(), LockingStrengthUpdate, accountID, setupKeyID) + err = store.DeleteSetupKey(context.Background(), accountID, setupKeyID) require.NoError(t, err) - _, err = store.GetSetupKeyByID(context.Background(), LockingStrengthShare, setupKeyID, accountID) + _, err = store.GetSetupKeyByID(context.Background(), LockingStrengthNone, setupKeyID, accountID) require.Error(t, err) } @@ -1302,7 +1302,7 @@ func Test_DeleteSetupKeyFailsForNonExistingKey(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" nonExistingKeyID := "non-existing-key-id" - err = store.DeleteSetupKey(context.Background(), LockingStrengthUpdate, accountID, nonExistingKeyID) + err = store.DeleteSetupKey(context.Background(), accountID, nonExistingKeyID) require.Error(t, err) } @@ -1342,7 +1342,7 @@ func TestSqlStore_GetGroupsByIDs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - groups, err := store.GetGroupsByIDs(context.Background(), LockingStrengthShare, accountID, tt.groupIDs) + groups, err := store.GetGroupsByIDs(context.Background(), LockingStrengthNone, accountID, tt.groupIDs) require.NoError(t, err) require.Len(t, groups, tt.expectedCount) }) @@ -1365,10 +1365,10 @@ func TestSqlStore_CreateGroup(t *testing.T) { Resources: []types.Resource{}, GroupPeers: []types.GroupPeer{}, } - err = store.CreateGroup(context.Background(), LockingStrengthUpdate, group) + err = store.CreateGroup(context.Background(), group) require.NoError(t, err) - savedGroup, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, "group-id") + savedGroup, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, "group-id") require.NoError(t, err) require.Equal(t, savedGroup, group) } @@ -1398,14 +1398,14 @@ func TestSqlStore_CreateUpdateGroups(t *testing.T) { GroupPeers: []types.GroupPeer{}, }, } - err = store.CreateGroups(context.Background(), LockingStrengthUpdate, accountID, groups) + err = store.CreateGroups(context.Background(), accountID, groups) require.NoError(t, err) groups[1].Peers = []string{} - err = store.UpdateGroups(context.Background(), LockingStrengthUpdate, accountID, groups) + err = store.UpdateGroups(context.Background(), accountID, groups) require.NoError(t, err) - group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groups[1].ID) + group, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groups[1].ID) require.NoError(t, err) require.Equal(t, groups[1], group) } @@ -1441,7 +1441,7 @@ func TestSqlStore_DeleteGroup(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := store.DeleteGroup(context.Background(), LockingStrengthUpdate, accountID, tt.groupID) + err := store.DeleteGroup(context.Background(), accountID, tt.groupID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -1450,7 +1450,7 @@ func TestSqlStore_DeleteGroup(t *testing.T) { } else { require.NoError(t, err) - group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, tt.groupID) + group, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, tt.groupID) require.Error(t, err) require.Nil(t, group) } @@ -1489,14 +1489,14 @@ func TestSqlStore_DeleteGroups(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := store.DeleteGroups(context.Background(), LockingStrengthUpdate, accountID, tt.groupIDs) + err := store.DeleteGroups(context.Background(), accountID, tt.groupIDs) if tt.expectError { require.Error(t, err) } else { require.NoError(t, err) for _, groupID := range tt.groupIDs { - group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID) + group, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.Error(t, err) require.Nil(t, group) } @@ -1535,7 +1535,7 @@ func TestSqlStore_GetPeerByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peer, err := store.GetPeerByID(context.Background(), LockingStrengthShare, accountID, tt.peerID) + peer, err := store.GetPeerByID(context.Background(), LockingStrengthNone, accountID, tt.peerID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -1586,7 +1586,7 @@ func TestSqlStore_GetPeersByIDs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetPeersByIDs(context.Background(), LockingStrengthShare, accountID, tt.peerIDs) + peers, err := store.GetPeersByIDs(context.Background(), LockingStrengthNone, accountID, tt.peerIDs) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -1623,7 +1623,7 @@ func TestSqlStore_GetPostureChecksByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - postureChecks, err := store.GetPostureChecksByID(context.Background(), LockingStrengthShare, accountID, tt.postureChecksID) + postureChecks, err := store.GetPostureChecksByID(context.Background(), LockingStrengthNone, accountID, tt.postureChecksID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -1675,7 +1675,7 @@ func TestSqlStore_GetPostureChecksByIDs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - groups, err := store.GetPostureChecksByIDs(context.Background(), LockingStrengthShare, accountID, tt.postureCheckIDs) + groups, err := store.GetPostureChecksByIDs(context.Background(), LockingStrengthNone, accountID, tt.postureCheckIDs) require.NoError(t, err) require.Len(t, groups, tt.expectedCount) }) @@ -1715,10 +1715,10 @@ func TestSqlStore_SavePostureChecks(t *testing.T) { }, }, } - err = store.SavePostureChecks(context.Background(), LockingStrengthUpdate, postureChecks) + err = store.SavePostureChecks(context.Background(), postureChecks) require.NoError(t, err) - savePostureChecks, err := store.GetPostureChecksByID(context.Background(), LockingStrengthShare, accountID, "posture-checks-id") + savePostureChecks, err := store.GetPostureChecksByID(context.Background(), LockingStrengthNone, accountID, "posture-checks-id") require.NoError(t, err) require.Equal(t, savePostureChecks, postureChecks) } @@ -1754,7 +1754,7 @@ func TestSqlStore_DeletePostureChecks(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err = store.DeletePostureChecks(context.Background(), LockingStrengthUpdate, accountID, tt.postureChecksID) + err = store.DeletePostureChecks(context.Background(), accountID, tt.postureChecksID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -1762,7 +1762,7 @@ func TestSqlStore_DeletePostureChecks(t *testing.T) { require.Equal(t, sErr.Type(), status.NotFound) } else { require.NoError(t, err) - group, err := store.GetPostureChecksByID(context.Background(), LockingStrengthShare, accountID, tt.postureChecksID) + group, err := store.GetPostureChecksByID(context.Background(), LockingStrengthNone, accountID, tt.postureChecksID) require.Error(t, err) require.Nil(t, group) } @@ -1800,7 +1800,7 @@ func TestSqlStore_GetPolicyByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - policy, err := store.GetPolicyByID(context.Background(), LockingStrengthShare, accountID, tt.policyID) + policy, err := store.GetPolicyByID(context.Background(), LockingStrengthNone, accountID, tt.policyID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -1837,10 +1837,10 @@ func TestSqlStore_CreatePolicy(t *testing.T) { }, }, } - err = store.CreatePolicy(context.Background(), LockingStrengthUpdate, policy) + err = store.CreatePolicy(context.Background(), policy) require.NoError(t, err) - savePolicy, err := store.GetPolicyByID(context.Background(), LockingStrengthShare, accountID, policy.ID) + savePolicy, err := store.GetPolicyByID(context.Background(), LockingStrengthNone, accountID, policy.ID) require.NoError(t, err) require.Equal(t, savePolicy, policy) @@ -1854,17 +1854,17 @@ func TestSqlStore_SavePolicy(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" policyID := "cs1tnh0hhcjnqoiuebf0" - policy, err := store.GetPolicyByID(context.Background(), LockingStrengthShare, accountID, policyID) + policy, err := store.GetPolicyByID(context.Background(), LockingStrengthNone, accountID, policyID) require.NoError(t, err) policy.Enabled = false policy.Description = "policy" policy.Rules[0].Sources = []string{"group"} policy.Rules[0].Ports = []string{"80", "443"} - err = store.SavePolicy(context.Background(), LockingStrengthUpdate, policy) + err = store.SavePolicy(context.Background(), policy) require.NoError(t, err) - savePolicy, err := store.GetPolicyByID(context.Background(), LockingStrengthShare, accountID, policy.ID) + savePolicy, err := store.GetPolicyByID(context.Background(), LockingStrengthNone, accountID, policy.ID) require.NoError(t, err) require.Equal(t, savePolicy, policy) } @@ -1877,10 +1877,10 @@ func TestSqlStore_DeletePolicy(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" policyID := "cs1tnh0hhcjnqoiuebf0" - err = store.DeletePolicy(context.Background(), LockingStrengthShare, accountID, policyID) + err = store.DeletePolicy(context.Background(), accountID, policyID) require.NoError(t, err) - policy, err := store.GetPolicyByID(context.Background(), LockingStrengthShare, accountID, policyID) + policy, err := store.GetPolicyByID(context.Background(), LockingStrengthNone, accountID, policyID) require.Error(t, err) require.Nil(t, policy) } @@ -1914,7 +1914,7 @@ func TestSqlStore_GetDNSSettings(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - dnsSettings, err := store.GetAccountDNSSettings(context.Background(), LockingStrengthShare, tt.accountID) + dnsSettings, err := store.GetAccountDNSSettings(context.Background(), LockingStrengthNone, tt.accountID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -1936,14 +1936,14 @@ func TestSqlStore_SaveDNSSettings(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" - dnsSettings, err := store.GetAccountDNSSettings(context.Background(), LockingStrengthShare, accountID) + dnsSettings, err := store.GetAccountDNSSettings(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) dnsSettings.DisabledManagementGroups = []string{"groupA", "groupB"} - err = store.SaveDNSSettings(context.Background(), LockingStrengthUpdate, accountID, dnsSettings) + err = store.SaveDNSSettings(context.Background(), accountID, dnsSettings) require.NoError(t, err) - saveDNSSettings, err := store.GetAccountDNSSettings(context.Background(), LockingStrengthShare, accountID) + saveDNSSettings, err := store.GetAccountDNSSettings(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Equal(t, saveDNSSettings, dnsSettings) } @@ -1977,7 +1977,7 @@ func TestSqlStore_GetAccountNameServerGroups(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetAccountNameServerGroups(context.Background(), LockingStrengthShare, tt.accountID) + peers, err := store.GetAccountNameServerGroups(context.Background(), LockingStrengthNone, tt.accountID) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -2015,7 +2015,7 @@ func TestSqlStore_GetNameServerByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - nsGroup, err := store.GetNameServerGroupByID(context.Background(), LockingStrengthShare, accountID, tt.nsGroupID) + nsGroup, err := store.GetNameServerGroupByID(context.Background(), LockingStrengthNone, accountID, tt.nsGroupID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -2055,10 +2055,10 @@ func TestSqlStore_SaveNameServerGroup(t *testing.T) { SearchDomainsEnabled: false, } - err = store.SaveNameServerGroup(context.Background(), LockingStrengthUpdate, nsGroup) + err = store.SaveNameServerGroup(context.Background(), nsGroup) require.NoError(t, err) - saveNSGroup, err := store.GetNameServerGroupByID(context.Background(), LockingStrengthShare, accountID, nsGroup.ID) + saveNSGroup, err := store.GetNameServerGroupByID(context.Background(), LockingStrengthNone, accountID, nsGroup.ID) require.NoError(t, err) require.Equal(t, saveNSGroup, nsGroup) } @@ -2071,10 +2071,10 @@ func TestSqlStore_DeleteNameServerGroup(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" nsGroupID := "csqdelq7qv97ncu7d9t0" - err = store.DeleteNameServerGroup(context.Background(), LockingStrengthShare, accountID, nsGroupID) + err = store.DeleteNameServerGroup(context.Background(), accountID, nsGroupID) require.NoError(t, err) - nsGroup, err := store.GetNameServerGroupByID(context.Background(), LockingStrengthShare, accountID, nsGroupID) + nsGroup, err := store.GetNameServerGroupByID(context.Background(), LockingStrengthNone, accountID, nsGroupID) require.Error(t, err) require.Nil(t, nsGroup) } @@ -2154,7 +2154,7 @@ func TestSqlStore_GetAccountNetworks(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - networks, err := store.GetAccountNetworks(context.Background(), LockingStrengthShare, tt.accountID) + networks, err := store.GetAccountNetworks(context.Background(), LockingStrengthNone, tt.accountID) require.NoError(t, err) require.Len(t, networks, tt.expectedCount) }) @@ -2191,7 +2191,7 @@ func TestSqlStore_GetNetworkByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - network, err := store.GetNetworkByID(context.Background(), LockingStrengthShare, accountID, tt.networkID) + network, err := store.GetNetworkByID(context.Background(), LockingStrengthNone, accountID, tt.networkID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -2219,10 +2219,10 @@ func TestSqlStore_SaveNetwork(t *testing.T) { Name: "net", } - err = store.SaveNetwork(context.Background(), LockingStrengthUpdate, network) + err = store.SaveNetwork(context.Background(), network) require.NoError(t, err) - savedNet, err := store.GetNetworkByID(context.Background(), LockingStrengthShare, accountID, network.ID) + savedNet, err := store.GetNetworkByID(context.Background(), LockingStrengthNone, accountID, network.ID) require.NoError(t, err) require.Equal(t, network, savedNet) } @@ -2235,10 +2235,10 @@ func TestSqlStore_DeleteNetwork(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" networkID := "ct286bi7qv930dsrrug0" - err = store.DeleteNetwork(context.Background(), LockingStrengthUpdate, accountID, networkID) + err = store.DeleteNetwork(context.Background(), accountID, networkID) require.NoError(t, err) - network, err := store.GetNetworkByID(context.Background(), LockingStrengthShare, accountID, networkID) + network, err := store.GetNetworkByID(context.Background(), LockingStrengthNone, accountID, networkID) require.Error(t, err) sErr, ok := status.FromError(err) require.True(t, ok) @@ -2272,7 +2272,7 @@ func TestSqlStore_GetNetworkRoutersByNetID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - routers, err := store.GetNetworkRoutersByNetID(context.Background(), LockingStrengthShare, accountID, tt.networkID) + routers, err := store.GetNetworkRoutersByNetID(context.Background(), LockingStrengthNone, accountID, tt.networkID) require.NoError(t, err) require.Len(t, routers, tt.expectedCount) }) @@ -2309,7 +2309,7 @@ func TestSqlStore_GetNetworkRouterByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - networkRouter, err := store.GetNetworkRouterByID(context.Background(), LockingStrengthShare, accountID, tt.networkRouterID) + networkRouter, err := store.GetNetworkRouterByID(context.Background(), LockingStrengthNone, accountID, tt.networkRouterID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -2336,10 +2336,10 @@ func TestSqlStore_SaveNetworkRouter(t *testing.T) { netRouter, err := routerTypes.NewNetworkRouter(accountID, networkID, "", []string{"net-router-grp"}, true, 0, true) require.NoError(t, err) - err = store.SaveNetworkRouter(context.Background(), LockingStrengthUpdate, netRouter) + err = store.SaveNetworkRouter(context.Background(), netRouter) require.NoError(t, err) - savedNetRouter, err := store.GetNetworkRouterByID(context.Background(), LockingStrengthShare, accountID, netRouter.ID) + savedNetRouter, err := store.GetNetworkRouterByID(context.Background(), LockingStrengthNone, accountID, netRouter.ID) require.NoError(t, err) require.Equal(t, netRouter, savedNetRouter) } @@ -2352,10 +2352,10 @@ func TestSqlStore_DeleteNetworkRouter(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" netRouterID := "ctc20ji7qv9ck2sebc80" - err = store.DeleteNetworkRouter(context.Background(), LockingStrengthUpdate, accountID, netRouterID) + err = store.DeleteNetworkRouter(context.Background(), accountID, netRouterID) require.NoError(t, err) - netRouter, err := store.GetNetworkByID(context.Background(), LockingStrengthShare, accountID, netRouterID) + netRouter, err := store.GetNetworkByID(context.Background(), LockingStrengthNone, accountID, netRouterID) require.Error(t, err) sErr, ok := status.FromError(err) require.True(t, ok) @@ -2389,7 +2389,7 @@ func TestSqlStore_GetNetworkResourcesByNetID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - netResources, err := store.GetNetworkResourcesByNetID(context.Background(), LockingStrengthShare, accountID, tt.networkID) + netResources, err := store.GetNetworkResourcesByNetID(context.Background(), LockingStrengthNone, accountID, tt.networkID) require.NoError(t, err) require.Len(t, netResources, tt.expectedCount) }) @@ -2426,7 +2426,7 @@ func TestSqlStore_GetNetworkResourceByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - netResource, err := store.GetNetworkResourceByID(context.Background(), LockingStrengthShare, accountID, tt.netResourceID) + netResource, err := store.GetNetworkResourceByID(context.Background(), LockingStrengthNone, accountID, tt.netResourceID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -2453,10 +2453,10 @@ func TestSqlStore_SaveNetworkResource(t *testing.T) { netResource, err := resourceTypes.NewNetworkResource(accountID, networkID, "resource-name", "", "example.com", []string{}, true) require.NoError(t, err) - err = store.SaveNetworkResource(context.Background(), LockingStrengthUpdate, netResource) + err = store.SaveNetworkResource(context.Background(), netResource) require.NoError(t, err) - savedNetResource, err := store.GetNetworkResourceByID(context.Background(), LockingStrengthShare, accountID, netResource.ID) + savedNetResource, err := store.GetNetworkResourceByID(context.Background(), LockingStrengthNone, accountID, netResource.ID) require.NoError(t, err) require.Equal(t, netResource.ID, savedNetResource.ID) require.Equal(t, netResource.Name, savedNetResource.Name) @@ -2475,10 +2475,10 @@ func TestSqlStore_DeleteNetworkResource(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" netResourceID := "ctc4nci7qv9061u6ilfg" - err = store.DeleteNetworkResource(context.Background(), LockingStrengthUpdate, accountID, netResourceID) + err = store.DeleteNetworkResource(context.Background(), accountID, netResourceID) require.NoError(t, err) - netResource, err := store.GetNetworkByID(context.Background(), LockingStrengthShare, accountID, netResourceID) + netResource, err := store.GetNetworkByID(context.Background(), LockingStrengthNone, accountID, netResourceID) require.Error(t, err) sErr, ok := status.FromError(err) require.True(t, ok) @@ -2502,18 +2502,18 @@ func TestSqlStore_AddAndRemoveResourceFromGroup(t *testing.T) { err = store.AddResourceToGroup(context.Background(), accountID, groupID, res) require.NoError(t, err) - group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID) + group, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.NoError(t, err) require.Contains(t, group.Resources, *res) - groups, err := store.GetResourceGroups(context.Background(), LockingStrengthShare, accountID, resourceId) + groups, err := store.GetResourceGroups(context.Background(), LockingStrengthNone, accountID, resourceId) require.NoError(t, err) require.Len(t, groups, 1) err = store.RemoveResourceFromGroup(context.Background(), accountID, groupID, res.ID) require.NoError(t, err) - group, err = store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID) + group, err = store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.NoError(t, err) require.NotContains(t, group.Resources, *res) } @@ -2527,14 +2527,14 @@ func TestSqlStore_AddPeerToGroup(t *testing.T) { peerID := "cfefqs706sqkneg59g4g" groupID := "cfefqs706sqkneg59g4h" - group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID) + group, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.NoError(t, err, "failed to get group") require.Len(t, group.Peers, 0, "group should have 0 peers") 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) + group, err = store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.NoError(t, err, "failed to get group") require.Len(t, group.Peers, 1, "group should have 1 peers") require.Contains(t, group.Peers, peerID) @@ -2554,18 +2554,18 @@ func TestSqlStore_AddPeerToAllGroup(t *testing.T) { DNSLabel: "peer1.domain.test", } - group, err := store.GetGroupByID(context.Background(), LockingStrengthShare, accountID, groupID) + group, err := store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.NoError(t, err, "failed to get group") require.Len(t, group.Peers, 2, "group should have 2 peers") require.NotContains(t, group.Peers, peer.ID) - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer) + err = store.AddPeerToAccount(context.Background(), peer) require.NoError(t, err, "failed to add peer to account") 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) + group, err = store.GetGroupByID(context.Background(), LockingStrengthNone, accountID, groupID) require.NoError(t, err, "failed to get group") require.Len(t, group.Peers, 3, "group should have peers") require.Contains(t, group.Peers, peer.ID) @@ -2609,10 +2609,10 @@ func TestSqlStore_AddPeerToAccount(t *testing.T) { CreatedAt: time.Now().UTC(), Ephemeral: true, } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer) + err = store.AddPeerToAccount(context.Background(), peer) require.NoError(t, err, "failed to add peer to account") - storedPeer, err := store.GetPeerByID(context.Background(), LockingStrengthShare, accountID, peer.ID) + storedPeer, err := store.GetPeerByID(context.Background(), LockingStrengthNone, accountID, peer.ID) require.NoError(t, err, "failed to get peer") assert.Equal(t, peer.ID, storedPeer.ID) @@ -2643,7 +2643,7 @@ func TestSqlStore_GetPeerGroups(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" peerID := "cfefqs706sqkneg59g4g" - groups, err := store.GetPeerGroups(context.Background(), LockingStrengthShare, accountID, peerID) + groups, err := store.GetPeerGroups(context.Background(), LockingStrengthNone, accountID, peerID) require.NoError(t, err) assert.Len(t, groups, 1) assert.Equal(t, groups[0].Name, "All") @@ -2651,7 +2651,7 @@ func TestSqlStore_GetPeerGroups(t *testing.T) { err = store.AddPeerToGroup(context.Background(), accountID, peerID, "cfefqs706sqkneg59g4h") require.NoError(t, err) - groups, err = store.GetPeerGroups(context.Background(), LockingStrengthShare, accountID, peerID) + groups, err = store.GetPeerGroups(context.Background(), LockingStrengthNone, accountID, peerID) require.NoError(t, err) assert.Len(t, groups, 2) } @@ -2705,7 +2705,7 @@ func TestSqlStore_GetAccountPeers(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetAccountPeers(context.Background(), LockingStrengthShare, tt.accountID, tt.nameFilter, tt.ipFilter) + peers, err := store.GetAccountPeers(context.Background(), LockingStrengthNone, tt.accountID, tt.nameFilter, tt.ipFilter) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -2742,7 +2742,7 @@ func TestSqlStore_GetAccountPeersWithExpiration(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetAccountPeersWithExpiration(context.Background(), LockingStrengthShare, tt.accountID) + peers, err := store.GetAccountPeersWithExpiration(context.Background(), LockingStrengthNone, tt.accountID) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -2778,7 +2778,7 @@ func TestSqlStore_GetAccountPeersWithInactivity(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetAccountPeersWithInactivity(context.Background(), LockingStrengthShare, tt.accountID) + peers, err := store.GetAccountPeersWithInactivity(context.Background(), LockingStrengthNone, tt.accountID) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -2790,7 +2790,7 @@ func TestSqlStore_GetAllEphemeralPeers(t *testing.T) { t.Cleanup(cleanup) require.NoError(t, err) - peers, err := store.GetAllEphemeralPeers(context.Background(), LockingStrengthShare) + peers, err := store.GetAllEphemeralPeers(context.Background(), LockingStrengthNone) require.NoError(t, err) require.Len(t, peers, 1) require.True(t, peers[0].Ephemeral) @@ -2841,7 +2841,7 @@ func TestSqlStore_GetUserPeers(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetUserPeers(context.Background(), LockingStrengthShare, tt.accountID, tt.userID) + peers, err := store.GetUserPeers(context.Background(), LockingStrengthNone, tt.accountID, tt.userID) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -2856,10 +2856,10 @@ func TestSqlStore_DeletePeer(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" peerID := "csrnkiq7qv9d8aitqd50" - err = store.DeletePeer(context.Background(), LockingStrengthUpdate, accountID, peerID) + err = store.DeletePeer(context.Background(), accountID, peerID) require.NoError(t, err) - peer, err := store.GetPeerByID(context.Background(), LockingStrengthShare, accountID, peerID) + peer, err := store.GetPeerByID(context.Background(), LockingStrengthNone, accountID, peerID) require.Error(t, err) require.Nil(t, peer) } @@ -2888,7 +2888,7 @@ func TestSqlStore_DatabaseBlocking(t *testing.T) { <-start err := store.ExecuteInTransaction(context.Background(), func(tx Store) error { - _, err := tx.GetAccountIDByPeerID(context.Background(), LockingStrengthShare, "cfvprsrlo1hqoo49ohog") + _, err := tx.GetAccountIDByPeerID(context.Background(), LockingStrengthNone, "cfvprsrlo1hqoo49ohog") return err }) if err != nil { @@ -2906,7 +2906,7 @@ func TestSqlStore_DatabaseBlocking(t *testing.T) { t.Logf("Entered routine 2-%d", i) <-start - _, err := store.GetAccountIDByPeerID(context.Background(), LockingStrengthShare, "cfvprsrlo1hqoo49ohog") + _, err := store.GetAccountIDByPeerID(context.Background(), LockingStrengthNone, "cfvprsrlo1hqoo49ohog") if err != nil { t.Errorf("Failed, got error: %v", err) return @@ -2965,7 +2965,7 @@ func TestSqlStore_GetAccountCreatedBy(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - createdBy, err := store.GetAccountCreatedBy(context.Background(), LockingStrengthShare, tt.accountID) + createdBy, err := store.GetAccountCreatedBy(context.Background(), LockingStrengthNone, tt.accountID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -3011,7 +3011,7 @@ func TestSqlStore_GetUserByUserID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - user, err := store.GetUserByUserID(context.Background(), LockingStrengthShare, tt.userID) + user, err := store.GetUserByUserID(context.Background(), LockingStrengthNone, tt.userID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -3034,7 +3034,7 @@ func TestSqlStore_GetUserByPATID(t *testing.T) { id := "9dj38s35-63fb-11ec-90d6-0242ac120003" - user, err := store.GetUserByPATID(context.Background(), LockingStrengthShare, id) + user, err := store.GetUserByPATID(context.Background(), LockingStrengthNone, id) require.NoError(t, err) require.Equal(t, "f4f6d672-63fb-11ec-90d6-0242ac120003", user.Id) } @@ -3057,10 +3057,10 @@ func TestSqlStore_SaveUser(t *testing.T) { CreatedAt: time.Now().UTC().Add(-time.Hour), Issued: types.UserIssuedIntegration, } - err = store.SaveUser(context.Background(), LockingStrengthUpdate, user) + err = store.SaveUser(context.Background(), user) require.NoError(t, err) - saveUser, err := store.GetUserByUserID(context.Background(), LockingStrengthShare, user.Id) + saveUser, err := store.GetUserByUserID(context.Background(), LockingStrengthNone, user.Id) require.NoError(t, err) require.Equal(t, user.Id, saveUser.Id) require.Equal(t, user.AccountID, saveUser.AccountID) @@ -3080,7 +3080,7 @@ func TestSqlStore_SaveUsers(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" - accountUsers, err := store.GetAccountUsers(context.Background(), LockingStrengthShare, accountID) + accountUsers, err := store.GetAccountUsers(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Len(t, accountUsers, 2) @@ -3098,18 +3098,18 @@ func TestSqlStore_SaveUsers(t *testing.T) { AutoGroups: []string{"groupA"}, }, } - err = store.SaveUsers(context.Background(), LockingStrengthUpdate, users) + err = store.SaveUsers(context.Background(), users) require.NoError(t, err) - accountUsers, err = store.GetAccountUsers(context.Background(), LockingStrengthShare, accountID) + accountUsers, err = store.GetAccountUsers(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Len(t, accountUsers, 4) users[1].AutoGroups = []string{"groupA", "groupC"} - err = store.SaveUsers(context.Background(), LockingStrengthUpdate, users) + err = store.SaveUsers(context.Background(), users) require.NoError(t, err) - user, err := store.GetUserByUserID(context.Background(), LockingStrengthShare, users[1].Id) + user, err := store.GetUserByUserID(context.Background(), LockingStrengthNone, users[1].Id) require.NoError(t, err) require.Equal(t, users[1].AutoGroups, user.AutoGroups) } @@ -3122,14 +3122,14 @@ func TestSqlStore_DeleteUser(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" userID := "f4f6d672-63fb-11ec-90d6-0242ac120003" - err = store.DeleteUser(context.Background(), LockingStrengthUpdate, accountID, userID) + err = store.DeleteUser(context.Background(), accountID, userID) require.NoError(t, err) - user, err := store.GetUserByUserID(context.Background(), LockingStrengthShare, userID) + user, err := store.GetUserByUserID(context.Background(), LockingStrengthNone, userID) require.Error(t, err) require.Nil(t, user) - userPATs, err := store.GetUserPATs(context.Background(), LockingStrengthShare, userID) + userPATs, err := store.GetUserPATs(context.Background(), LockingStrengthNone, userID) require.NoError(t, err) require.Len(t, userPATs, 0) } @@ -3165,7 +3165,7 @@ func TestSqlStore_GetPATByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - pat, err := store.GetPATByID(context.Background(), LockingStrengthShare, userID, tt.patID) + pat, err := store.GetPATByID(context.Background(), LockingStrengthNone, userID, tt.patID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -3186,7 +3186,7 @@ func TestSqlStore_GetUserPATs(t *testing.T) { t.Cleanup(cleanup) require.NoError(t, err) - userPATs, err := store.GetUserPATs(context.Background(), LockingStrengthShare, "f4f6d672-63fb-11ec-90d6-0242ac120003") + userPATs, err := store.GetUserPATs(context.Background(), LockingStrengthNone, "f4f6d672-63fb-11ec-90d6-0242ac120003") require.NoError(t, err) require.Len(t, userPATs, 1) } @@ -3196,7 +3196,7 @@ func TestSqlStore_GetPATByHashedToken(t *testing.T) { t.Cleanup(cleanup) require.NoError(t, err) - pat, err := store.GetPATByHashedToken(context.Background(), LockingStrengthShare, "SoMeHaShEdToKeN") + pat, err := store.GetPATByHashedToken(context.Background(), LockingStrengthNone, "SoMeHaShEdToKeN") require.NoError(t, err) require.Equal(t, "9dj38s35-63fb-11ec-90d6-0242ac120003", pat.ID) } @@ -3209,10 +3209,10 @@ func TestSqlStore_MarkPATUsed(t *testing.T) { userID := "f4f6d672-63fb-11ec-90d6-0242ac120003" patID := "9dj38s35-63fb-11ec-90d6-0242ac120003" - err = store.MarkPATUsed(context.Background(), LockingStrengthUpdate, patID) + err = store.MarkPATUsed(context.Background(), patID) require.NoError(t, err) - pat, err := store.GetPATByID(context.Background(), LockingStrengthShare, userID, patID) + pat, err := store.GetPATByID(context.Background(), LockingStrengthNone, userID, patID) require.NoError(t, err) now := time.Now().UTC() require.WithinRange(t, pat.LastUsed.UTC(), now.Add(-15*time.Second), now, "LastUsed should be within 1 second of now") @@ -3235,10 +3235,10 @@ func TestSqlStore_SavePAT(t *testing.T) { CreatedAt: time.Now().UTC().Add(time.Hour), LastUsed: util.ToPtr(time.Now().UTC().Add(-15 * time.Minute)), } - err = store.SavePAT(context.Background(), LockingStrengthUpdate, pat) + err = store.SavePAT(context.Background(), pat) require.NoError(t, err) - savePAT, err := store.GetPATByID(context.Background(), LockingStrengthShare, userID, pat.ID) + savePAT, err := store.GetPATByID(context.Background(), LockingStrengthNone, userID, pat.ID) require.NoError(t, err) require.Equal(t, pat.ID, savePAT.ID) require.Equal(t, pat.UserID, savePAT.UserID) @@ -3257,10 +3257,10 @@ func TestSqlStore_DeletePAT(t *testing.T) { userID := "f4f6d672-63fb-11ec-90d6-0242ac120003" patID := "9dj38s35-63fb-11ec-90d6-0242ac120003" - err = store.DeletePAT(context.Background(), LockingStrengthUpdate, userID, patID) + err = store.DeletePAT(context.Background(), userID, patID) require.NoError(t, err) - pat, err := store.GetPATByID(context.Background(), LockingStrengthShare, userID, patID) + pat, err := store.GetPATByID(context.Background(), LockingStrengthNone, userID, patID) require.Error(t, err) require.Nil(t, pat) } @@ -3272,7 +3272,7 @@ func TestSqlStore_SaveUsers_LargeBatch(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" - accountUsers, err := store.GetAccountUsers(context.Background(), LockingStrengthShare, accountID) + accountUsers, err := store.GetAccountUsers(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Len(t, accountUsers, 2) @@ -3286,10 +3286,10 @@ func TestSqlStore_SaveUsers_LargeBatch(t *testing.T) { }) } - err = store.SaveUsers(context.Background(), LockingStrengthUpdate, usersToSave) + err = store.SaveUsers(context.Background(), usersToSave) require.NoError(t, err) - accountUsers, err = store.GetAccountUsers(context.Background(), LockingStrengthShare, accountID) + accountUsers, err = store.GetAccountUsers(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Equal(t, 8002, len(accountUsers)) } @@ -3301,7 +3301,7 @@ func TestSqlStore_SaveGroups_LargeBatch(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" - accountGroups, err := store.GetAccountGroups(context.Background(), LockingStrengthShare, accountID) + accountGroups, err := store.GetAccountGroups(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Len(t, accountGroups, 3) @@ -3315,10 +3315,10 @@ func TestSqlStore_SaveGroups_LargeBatch(t *testing.T) { }) } - err = store.CreateGroups(context.Background(), LockingStrengthUpdate, accountID, groupsToSave) + err = store.CreateGroups(context.Background(), accountID, groupsToSave) require.NoError(t, err) - accountGroups, err = store.GetAccountGroups(context.Background(), LockingStrengthShare, accountID) + accountGroups, err = store.GetAccountGroups(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.Equal(t, 8003, len(accountGroups)) } @@ -3351,7 +3351,7 @@ func TestSqlStore_GetAccountRoutes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - routes, err := store.GetAccountRoutes(context.Background(), LockingStrengthShare, tt.accountID) + routes, err := store.GetAccountRoutes(context.Background(), LockingStrengthNone, tt.accountID) require.NoError(t, err) require.Len(t, routes, tt.expectedCount) }) @@ -3388,7 +3388,7 @@ func TestSqlStore_GetRouteByID(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - route, err := store.GetRouteByID(context.Background(), LockingStrengthShare, accountID, tt.routeID) + route, err := store.GetRouteByID(context.Background(), LockingStrengthNone, accountID, tt.routeID) if tt.expectError { require.Error(t, err) sErr, ok := status.FromError(err) @@ -3424,10 +3424,10 @@ func TestSqlStore_SaveRoute(t *testing.T) { Groups: []string{"groupA"}, AccessControlGroups: []string{}, } - err = store.SaveRoute(context.Background(), LockingStrengthUpdate, route) + err = store.SaveRoute(context.Background(), route) require.NoError(t, err) - saveRoute, err := store.GetRouteByID(context.Background(), LockingStrengthShare, accountID, string(route.ID)) + saveRoute, err := store.GetRouteByID(context.Background(), LockingStrengthNone, accountID, string(route.ID)) require.NoError(t, err) require.Equal(t, route, saveRoute) @@ -3441,10 +3441,10 @@ func TestSqlStore_DeleteRoute(t *testing.T) { accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" routeID := "ct03t427qv97vmtmglog" - err = store.DeleteRoute(context.Background(), LockingStrengthUpdate, accountID, routeID) + err = store.DeleteRoute(context.Background(), accountID, routeID) require.NoError(t, err) - route, err := store.GetRouteByID(context.Background(), LockingStrengthShare, accountID, routeID) + route, err := store.GetRouteByID(context.Background(), LockingStrengthNone, accountID, routeID) require.Error(t, err) require.Nil(t, route) } @@ -3455,7 +3455,7 @@ func TestSqlStore_GetAccountMeta(t *testing.T) { require.NoError(t, err) accountID := "bf1c8084-ba50-4ce7-9439-34653001fc3b" - accountMeta, err := store.GetAccountMeta(context.Background(), LockingStrengthShare, accountID) + accountMeta, err := store.GetAccountMeta(context.Background(), LockingStrengthNone, accountID) require.NoError(t, err) require.NotNil(t, accountMeta) require.Equal(t, accountID, accountMeta.AccountID) @@ -3567,7 +3567,7 @@ func BenchmarkGetAccountPeers(b *testing.B) { DNSLabel: fmt.Sprintf("peer%d.example.com", i), IP: intToIPv4(uint32(i)), } - err = store.AddPeerToAccount(context.Background(), LockingStrengthUpdate, peer) + err = store.AddPeerToAccount(context.Background(), peer) if err != nil { b.Fatalf("Failed to add peer: %v", err) } @@ -3580,7 +3580,7 @@ func BenchmarkGetAccountPeers(b *testing.B) { ID: groupID, AccountID: accountID, } - err = store.CreateGroup(context.Background(), LockingStrengthUpdate, group) + err = store.CreateGroup(context.Background(), group) if err != nil { b.Fatalf("Failed to create group: %v", err) } @@ -3595,7 +3595,7 @@ func BenchmarkGetAccountPeers(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - _, err := store.GetPeerGroups(context.Background(), LockingStrengthShare, accountID, peers[i%numberOfPeers].ID) + _, err := store.GetPeerGroups(context.Background(), LockingStrengthNone, accountID, peers[i%numberOfPeers].ID) if err != nil { b.Fatal(err) } diff --git a/management/server/store/store.go b/management/server/store/store.go index 912939bc2..da4459256 100644 --- a/management/server/store/store.go +++ b/management/server/store/store.go @@ -72,8 +72,8 @@ type Store interface { SaveAccount(ctx context.Context, account *types.Account) error DeleteAccount(ctx context.Context, account *types.Account) error UpdateAccountDomainAttributes(ctx context.Context, accountID string, domain string, category string, isPrimaryDomain bool) error - SaveDNSSettings(ctx context.Context, lockStrength LockingStrength, accountID string, settings *types.DNSSettings) error - SaveAccountSettings(ctx context.Context, lockStrength LockingStrength, accountID string, settings *types.Settings) error + SaveDNSSettings(ctx context.Context, accountID string, settings *types.DNSSettings) error + SaveAccountSettings(ctx context.Context, accountID string, settings *types.Settings) error CountAccountsByPrivateDomain(ctx context.Context, domain string) (int64, error) SaveAccountOnboarding(ctx context.Context, onboarding *types.AccountOnboarding) error @@ -81,10 +81,10 @@ type Store interface { GetUserByUserID(ctx context.Context, lockStrength LockingStrength, userID string) (*types.User, error) GetAccountUsers(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*types.User, error) GetAccountOwner(ctx context.Context, lockStrength LockingStrength, accountID string) (*types.User, error) - SaveUsers(ctx context.Context, lockStrength LockingStrength, users []*types.User) error - SaveUser(ctx context.Context, lockStrength LockingStrength, user *types.User) error + SaveUsers(ctx context.Context, users []*types.User) error + SaveUser(ctx context.Context, user *types.User) error SaveUserLastLogin(ctx context.Context, accountID, userID string, lastLogin time.Time) error - DeleteUser(ctx context.Context, lockStrength LockingStrength, accountID, userID string) error + DeleteUser(ctx context.Context, accountID, userID string) error GetTokenIDByHashedToken(ctx context.Context, secret string) (string, error) DeleteHashedPAT2TokenIDIndex(hashedToken string) error DeleteTokenID2UserIDIndex(tokenID string) error @@ -92,34 +92,34 @@ type Store interface { GetPATByID(ctx context.Context, lockStrength LockingStrength, userID, patID string) (*types.PersonalAccessToken, error) GetUserPATs(ctx context.Context, lockStrength LockingStrength, userID string) ([]*types.PersonalAccessToken, error) GetPATByHashedToken(ctx context.Context, lockStrength LockingStrength, hashedToken string) (*types.PersonalAccessToken, error) - MarkPATUsed(ctx context.Context, lockStrength LockingStrength, patID string) error - SavePAT(ctx context.Context, strength LockingStrength, pat *types.PersonalAccessToken) error - DeletePAT(ctx context.Context, strength LockingStrength, userID, patID string) error + MarkPATUsed(ctx context.Context, patID string) error + SavePAT(ctx context.Context, pat *types.PersonalAccessToken) error + DeletePAT(ctx context.Context, userID, patID string) error GetAccountGroups(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*types.Group, error) GetResourceGroups(ctx context.Context, lockStrength LockingStrength, accountID, resourceID string) ([]*types.Group, error) 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) - 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 + CreateGroups(ctx context.Context, accountID string, groups []*types.Group) error + UpdateGroups(ctx context.Context, accountID string, groups []*types.Group) error + CreateGroup(ctx context.Context, group *types.Group) error + UpdateGroup(ctx context.Context, group *types.Group) error + DeleteGroup(ctx context.Context, accountID, groupID string) error + DeleteGroups(ctx context.Context, accountID string, groupIDs []string) error GetAccountPolicies(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*types.Policy, error) GetPolicyByID(ctx context.Context, lockStrength LockingStrength, accountID, policyID string) (*types.Policy, error) - CreatePolicy(ctx context.Context, lockStrength LockingStrength, policy *types.Policy) error - SavePolicy(ctx context.Context, lockStrength LockingStrength, policy *types.Policy) error - DeletePolicy(ctx context.Context, lockStrength LockingStrength, accountID, policyID string) error + CreatePolicy(ctx context.Context, policy *types.Policy) error + SavePolicy(ctx context.Context, policy *types.Policy) error + DeletePolicy(ctx context.Context, accountID, policyID string) error GetPostureCheckByChecksDefinition(accountID string, checks *posture.ChecksDefinition) (*posture.Checks, error) GetAccountPostureChecks(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*posture.Checks, error) GetPostureChecksByID(ctx context.Context, lockStrength LockingStrength, accountID, postureCheckID string) (*posture.Checks, error) GetPostureChecksByIDs(ctx context.Context, lockStrength LockingStrength, accountID string, postureChecksIDs []string) (map[string]*posture.Checks, error) - SavePostureChecks(ctx context.Context, lockStrength LockingStrength, postureCheck *posture.Checks) error - DeletePostureChecks(ctx context.Context, lockStrength LockingStrength, accountID, postureChecksID string) error + SavePostureChecks(ctx context.Context, postureCheck *posture.Checks) error + DeletePostureChecks(ctx context.Context, accountID, postureChecksID string) error GetPeerLabelsInAccount(ctx context.Context, lockStrength LockingStrength, accountId string, hostname string) ([]string, error) AddPeerToAllGroup(ctx context.Context, accountID string, peerID string) error @@ -130,7 +130,7 @@ type Store interface { 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 + AddPeerToAccount(ctx context.Context, peer *nbpeer.Peer) error GetPeerByPeerPubKey(ctx context.Context, lockStrength LockingStrength, peerKey string) (*nbpeer.Peer, error) GetAccountPeers(ctx context.Context, lockStrength LockingStrength, accountID, nameFilter, ipFilter string) ([]*nbpeer.Peer, error) GetUserPeers(ctx context.Context, lockStrength LockingStrength, accountID, userID string) ([]*nbpeer.Peer, error) @@ -139,30 +139,30 @@ type Store interface { GetAccountPeersWithExpiration(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*nbpeer.Peer, error) GetAccountPeersWithInactivity(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*nbpeer.Peer, error) GetAllEphemeralPeers(ctx context.Context, lockStrength LockingStrength) ([]*nbpeer.Peer, error) - SavePeer(ctx context.Context, lockStrength LockingStrength, accountID string, peer *nbpeer.Peer) error - SavePeerStatus(ctx context.Context, lockStrength LockingStrength, accountID, peerID string, status nbpeer.PeerStatus) error - SavePeerLocation(ctx context.Context, lockStrength LockingStrength, accountID string, peer *nbpeer.Peer) error - DeletePeer(ctx context.Context, lockStrength LockingStrength, accountID string, peerID string) error + SavePeer(ctx context.Context, accountID string, peer *nbpeer.Peer) error + SavePeerStatus(ctx context.Context, accountID, peerID string, status nbpeer.PeerStatus) error + SavePeerLocation(ctx context.Context, accountID string, peer *nbpeer.Peer) error + DeletePeer(ctx context.Context, accountID string, peerID string) error GetSetupKeyBySecret(ctx context.Context, lockStrength LockingStrength, key string) (*types.SetupKey, error) IncrementSetupKeyUsage(ctx context.Context, setupKeyID string) error GetAccountSetupKeys(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*types.SetupKey, error) GetSetupKeyByID(ctx context.Context, lockStrength LockingStrength, accountID, setupKeyID string) (*types.SetupKey, error) - SaveSetupKey(ctx context.Context, lockStrength LockingStrength, setupKey *types.SetupKey) error - DeleteSetupKey(ctx context.Context, lockStrength LockingStrength, accountID, keyID string) error + SaveSetupKey(ctx context.Context, setupKey *types.SetupKey) error + DeleteSetupKey(ctx context.Context, accountID, keyID string) error GetAccountRoutes(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*route.Route, error) GetRouteByID(ctx context.Context, lockStrength LockingStrength, accountID, routeID string) (*route.Route, error) - SaveRoute(ctx context.Context, lockStrength LockingStrength, route *route.Route) error - DeleteRoute(ctx context.Context, lockStrength LockingStrength, accountID, routeID string) error + SaveRoute(ctx context.Context, route *route.Route) error + DeleteRoute(ctx context.Context, accountID, routeID string) error GetAccountNameServerGroups(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*dns.NameServerGroup, error) GetNameServerGroupByID(ctx context.Context, lockStrength LockingStrength, nameServerGroupID string, accountID string) (*dns.NameServerGroup, error) - SaveNameServerGroup(ctx context.Context, lockStrength LockingStrength, nameServerGroup *dns.NameServerGroup) error - DeleteNameServerGroup(ctx context.Context, lockStrength LockingStrength, accountID, nameServerGroupID string) error + SaveNameServerGroup(ctx context.Context, nameServerGroup *dns.NameServerGroup) error + DeleteNameServerGroup(ctx context.Context, accountID, nameServerGroupID string) error GetTakenIPs(ctx context.Context, lockStrength LockingStrength, accountId string) ([]net.IP, error) - IncrementNetworkSerial(ctx context.Context, lockStrength LockingStrength, accountId string) error + IncrementNetworkSerial(ctx context.Context, accountId string) error GetAccountNetwork(ctx context.Context, lockStrength LockingStrength, accountId string) (*types.Network, error) GetInstallationID() string @@ -184,21 +184,21 @@ type Store interface { GetAccountNetworks(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*networkTypes.Network, error) GetNetworkByID(ctx context.Context, lockStrength LockingStrength, accountID, networkID string) (*networkTypes.Network, error) - SaveNetwork(ctx context.Context, lockStrength LockingStrength, network *networkTypes.Network) error - DeleteNetwork(ctx context.Context, lockStrength LockingStrength, accountID, networkID string) error + SaveNetwork(ctx context.Context, network *networkTypes.Network) error + DeleteNetwork(ctx context.Context, accountID, networkID string) error GetNetworkRoutersByNetID(ctx context.Context, lockStrength LockingStrength, accountID, netID string) ([]*routerTypes.NetworkRouter, error) GetNetworkRoutersByAccountID(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*routerTypes.NetworkRouter, error) GetNetworkRouterByID(ctx context.Context, lockStrength LockingStrength, accountID, routerID string) (*routerTypes.NetworkRouter, error) - SaveNetworkRouter(ctx context.Context, lockStrength LockingStrength, router *routerTypes.NetworkRouter) error - DeleteNetworkRouter(ctx context.Context, lockStrength LockingStrength, accountID, routerID string) error + SaveNetworkRouter(ctx context.Context, router *routerTypes.NetworkRouter) error + DeleteNetworkRouter(ctx context.Context, accountID, routerID string) error GetNetworkResourcesByNetID(ctx context.Context, lockStrength LockingStrength, accountID, netID string) ([]*resourceTypes.NetworkResource, error) GetNetworkResourcesByAccountID(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*resourceTypes.NetworkResource, error) GetNetworkResourceByID(ctx context.Context, lockStrength LockingStrength, accountID, resourceID string) (*resourceTypes.NetworkResource, error) GetNetworkResourceByName(ctx context.Context, lockStrength LockingStrength, accountID, resourceName string) (*resourceTypes.NetworkResource, error) - SaveNetworkResource(ctx context.Context, lockStrength LockingStrength, resource *resourceTypes.NetworkResource) error - DeleteNetworkResource(ctx context.Context, lockStrength LockingStrength, accountID, resourceID string) error + SaveNetworkResource(ctx context.Context, resource *resourceTypes.NetworkResource) error + DeleteNetworkResource(ctx context.Context, 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) 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 a3a7ce305..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" 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/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/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 a0f4c4a6c..ba1835f22 100644 --- a/management/server/user.go +++ b/management/server/user.go @@ -17,11 +17,11 @@ 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/management/server/store" "github.com/netbirdio/netbird/management/server/types" "github.com/netbirdio/netbird/management/server/users" "github.com/netbirdio/netbird/management/server/util" + "github.com/netbirdio/netbird/shared/management/status" ) // createServiceUser creates a new service user under the given account. @@ -46,7 +46,7 @@ func (am *DefaultAccountManager) createServiceUser(ctx context.Context, accountI newUser.AccountID = accountID log.WithContext(ctx).Debugf("New User: %v", newUser) - if err = am.Store.SaveUser(ctx, store.LockingStrengthUpdate, newUser); err != nil { + if err = am.Store.SaveUser(ctx, newUser); err != nil { return nil, err } @@ -95,14 +95,14 @@ func (am *DefaultAccountManager) inviteNewUser(ctx context.Context, accountID, u return nil, status.NewPermissionDeniedError() } - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { return nil, err } inviterID := userID if initiatorUser.IsServiceUser { - createdBy, err := am.Store.GetAccountCreatedBy(ctx, store.LockingStrengthShare, accountID) + createdBy, err := am.Store.GetAccountCreatedBy(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -124,7 +124,7 @@ func (am *DefaultAccountManager) inviteNewUser(ctx context.Context, accountID, u CreatedAt: time.Now().UTC(), } - if err = am.Store.SaveUser(ctx, store.LockingStrengthUpdate, newUser); err != nil { + if err = am.Store.SaveUser(ctx, newUser); err != nil { return nil, err } @@ -178,13 +178,13 @@ func (am *DefaultAccountManager) createNewIdpUser(ctx context.Context, accountID } func (am *DefaultAccountManager) GetUserByID(ctx context.Context, id string) (*types.User, error) { - return am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, id) + return am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, id) } // GetUser looks up a user by provided nbContext.UserAuths. // Expects account to have been created already. func (am *DefaultAccountManager) GetUserFromUserAuth(ctx context.Context, userAuth nbContext.UserAuth) (*types.User, error) { - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userAuth.UserId) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userAuth.UserId) if err != nil { return nil, err } @@ -209,11 +209,11 @@ func (am *DefaultAccountManager) GetUserFromUserAuth(ctx context.Context, userAu // ListUsers returns lists of all users under the account. // It doesn't populate user information such as email or name. func (am *DefaultAccountManager) ListUsers(ctx context.Context, accountID string) ([]*types.User, error) { - return am.Store.GetAccountUsers(ctx, store.LockingStrengthShare, accountID) + return am.Store.GetAccountUsers(ctx, store.LockingStrengthNone, accountID) } func (am *DefaultAccountManager) deleteServiceUser(ctx context.Context, accountID string, initiatorUserID string, targetUser *types.User) error { - if err := am.Store.DeleteUser(ctx, store.LockingStrengthUpdate, accountID, targetUser.Id); err != nil { + if err := am.Store.DeleteUser(ctx, accountID, targetUser.Id); err != nil { return err } meta := map[string]any{"name": targetUser.ServiceUserName, "created_at": targetUser.CreatedAt} @@ -230,7 +230,7 @@ func (am *DefaultAccountManager) DeleteUser(ctx context.Context, accountID, init unlock := am.Store.AcquireWriteLockByUID(ctx, accountID) defer unlock() - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return err } @@ -243,7 +243,7 @@ func (am *DefaultAccountManager) DeleteUser(ctx context.Context, accountID, init return status.NewPermissionDeniedError() } - targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserID) + targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, targetUserID) if err != nil { return err } @@ -347,12 +347,12 @@ func (am *DefaultAccountManager) CreatePAT(ctx context.Context, accountID string return nil, status.NewPermissionDeniedError() } - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return nil, err } - targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserID) + targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, targetUserID) if err != nil { return nil, err } @@ -367,7 +367,7 @@ func (am *DefaultAccountManager) CreatePAT(ctx context.Context, accountID string return nil, status.Errorf(status.Internal, "failed to create PAT: %v", err) } - if err = am.Store.SavePAT(ctx, store.LockingStrengthUpdate, &pat.PersonalAccessToken); err != nil { + if err = am.Store.SavePAT(ctx, &pat.PersonalAccessToken); err != nil { return nil, err } @@ -390,12 +390,12 @@ func (am *DefaultAccountManager) DeletePAT(ctx context.Context, accountID string return status.NewPermissionDeniedError() } - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return err } - targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserID) + targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, targetUserID) if err != nil { return err } @@ -404,12 +404,12 @@ func (am *DefaultAccountManager) DeletePAT(ctx context.Context, accountID string return status.NewAdminPermissionError() } - pat, err := am.Store.GetPATByID(ctx, store.LockingStrengthShare, targetUserID, tokenID) + pat, err := am.Store.GetPATByID(ctx, store.LockingStrengthNone, targetUserID, tokenID) if err != nil { return err } - if err = am.Store.DeletePAT(ctx, store.LockingStrengthUpdate, targetUserID, tokenID); err != nil { + if err = am.Store.DeletePAT(ctx, targetUserID, tokenID); err != nil { return err } @@ -429,12 +429,12 @@ func (am *DefaultAccountManager) GetPAT(ctx context.Context, accountID string, i return nil, status.NewPermissionDeniedError() } - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return nil, err } - targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserID) + targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, targetUserID) if err != nil { return nil, err } @@ -443,7 +443,7 @@ func (am *DefaultAccountManager) GetPAT(ctx context.Context, accountID string, i return nil, status.NewAdminPermissionError() } - return am.Store.GetPATByID(ctx, store.LockingStrengthShare, targetUserID, tokenID) + return am.Store.GetPATByID(ctx, store.LockingStrengthNone, targetUserID, tokenID) } // GetAllPATs returns all PATs for a user @@ -456,12 +456,12 @@ func (am *DefaultAccountManager) GetAllPATs(ctx context.Context, accountID strin return nil, status.NewPermissionDeniedError() } - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return nil, err } - targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserID) + targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, targetUserID) if err != nil { return nil, err } @@ -470,7 +470,7 @@ func (am *DefaultAccountManager) GetAllPATs(ctx context.Context, accountID strin return nil, status.NewAdminPermissionError() } - return am.Store.GetUserPATs(ctx, store.LockingStrengthShare, targetUserID) + return am.Store.GetUserPATs(ctx, store.LockingStrengthNone, targetUserID) } // SaveUser saves updates to the given user. If the user doesn't exist, it will throw status.NotFound error. @@ -511,7 +511,7 @@ func (am *DefaultAccountManager) SaveOrAddUsers(ctx context.Context, accountID, if !allowed { return nil, status.NewPermissionDeniedError() } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -521,7 +521,7 @@ func (am *DefaultAccountManager) SaveOrAddUsers(ctx context.Context, accountID, var addUserEvents []func() var usersToSave = make([]*types.User, 0, len(updates)) - groups, err := am.Store.GetAccountGroups(ctx, store.LockingStrengthShare, accountID) + groups, err := am.Store.GetAccountGroups(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, fmt.Errorf("error getting account groups: %w", err) } @@ -533,7 +533,7 @@ func (am *DefaultAccountManager) SaveOrAddUsers(ctx context.Context, accountID, var initiatorUser *types.User if initiatorUserID != activity.SystemInitiator { - result, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + result, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return nil, err } @@ -560,7 +560,7 @@ func (am *DefaultAccountManager) SaveOrAddUsers(ctx context.Context, accountID, updateAccountPeers = true } } - return transaction.SaveUsers(ctx, store.LockingStrengthUpdate, usersToSave) + return transaction.SaveUsers(ctx, usersToSave) }) if err != nil { return nil, err @@ -593,7 +593,7 @@ func (am *DefaultAccountManager) SaveOrAddUsers(ctx context.Context, accountID, } if settings.GroupsPropagationEnabled && updateAccountPeers { - if err = am.Store.IncrementNetworkSerial(ctx, store.LockingStrengthUpdate, accountID); err != nil { + if err = am.Store.IncrementNetworkSerial(ctx, accountID); err != nil { return nil, fmt.Errorf("failed to increment network serial: %w", err) } am.UpdateAccountPeers(ctx, accountID) @@ -700,7 +700,7 @@ func (am *DefaultAccountManager) processUserUpdate(ctx context.Context, transact // getUserOrCreateIfNotExists retrieves the existing user or creates a new one if it doesn't exist. func getUserOrCreateIfNotExists(ctx context.Context, transaction store.Store, accountID string, update *types.User, addIfNotExists bool) (*types.User, error) { - existingUser, err := transaction.GetUserByUserID(ctx, store.LockingStrengthShare, update.Id) + existingUser, err := transaction.GetUserByUserID(ctx, store.LockingStrengthNone, update.Id) if err != nil { if sErr, ok := status.FromError(err); ok && sErr.Type() == status.NotFound { if !addIfNotExists { @@ -724,7 +724,7 @@ func handleOwnerRoleTransfer(ctx context.Context, transaction store.Store, initi newInitiatorUser := initiatorUser.Copy() newInitiatorUser.Role = types.UserRoleAdmin - if err := transaction.SaveUser(ctx, store.LockingStrengthUpdate, newInitiatorUser); err != nil { + if err := transaction.SaveUser(ctx, newInitiatorUser); err != nil { return false, err } return true, nil @@ -835,7 +835,7 @@ func (am *DefaultAccountManager) GetUsersFromAccount(ctx context.Context, accoun var user *types.User if initiatorUserID != activity.SystemInitiator { - result, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + result, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return nil, fmt.Errorf("failed to get user: %w", err) } @@ -845,7 +845,7 @@ func (am *DefaultAccountManager) GetUsersFromAccount(ctx context.Context, accoun accountUsers := []*types.User{} switch { case allowed: - accountUsers, err = am.Store.GetAccountUsers(ctx, store.LockingStrengthShare, accountID) + accountUsers, err = am.Store.GetAccountUsers(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -938,7 +938,8 @@ 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 { - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + log.WithContext(ctx).Debugf("Expiring %d peers for account %s", len(peers), accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return err } @@ -955,7 +956,7 @@ func (am *DefaultAccountManager) expireAndUpdatePeers(ctx context.Context, accou peerIDs = append(peerIDs, peer.ID) peer.MarkLoginExpired(true) - if err := am.Store.SavePeerStatus(ctx, store.LockingStrengthUpdate, accountID, peer.ID, *peer.Status); err != nil { + if err := am.Store.SavePeerStatus(ctx, accountID, peer.ID, *peer.Status); err != nil { return err } am.StoreEvent( @@ -968,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 } @@ -1008,7 +1009,7 @@ func (am *DefaultAccountManager) DeleteRegularUsers(ctx context.Context, account return status.NewPermissionDeniedError() } - initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, initiatorUserID) + initiatorUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, initiatorUserID) if err != nil { return err } @@ -1022,7 +1023,7 @@ func (am *DefaultAccountManager) DeleteRegularUsers(ctx context.Context, account continue } - targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserID) + targetUser, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, targetUserID) if err != nil { allErrors = errors.Join(allErrors, err) continue @@ -1086,12 +1087,12 @@ func (am *DefaultAccountManager) deleteRegularUser(ctx context.Context, accountI var err error err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error { - targetUser, err = transaction.GetUserByUserID(ctx, store.LockingStrengthShare, targetUserInfo.ID) + targetUser, err = transaction.GetUserByUserID(ctx, store.LockingStrengthUpdate, targetUserInfo.ID) if err != nil { return fmt.Errorf("failed to get user to delete: %w", err) } - userPeers, err := transaction.GetUserPeers(ctx, store.LockingStrengthShare, accountID, targetUserInfo.ID) + userPeers, err := transaction.GetUserPeers(ctx, store.LockingStrengthNone, accountID, targetUserInfo.ID) if err != nil { return fmt.Errorf("failed to get user peers: %w", err) } @@ -1104,7 +1105,7 @@ func (am *DefaultAccountManager) deleteRegularUser(ctx context.Context, accountI } } - if err = transaction.DeleteUser(ctx, store.LockingStrengthUpdate, accountID, targetUserInfo.ID); err != nil { + if err = transaction.DeleteUser(ctx, accountID, targetUserInfo.ID); err != nil { return fmt.Errorf("failed to delete user: %s %w", targetUserInfo.ID, err) } @@ -1125,7 +1126,7 @@ func (am *DefaultAccountManager) deleteRegularUser(ctx context.Context, accountI // GetOwnerInfo retrieves the owner information for a given account ID. func (am *DefaultAccountManager) GetOwnerInfo(ctx context.Context, accountID string) (*types.UserInfo, error) { - owner, err := am.Store.GetAccountOwner(ctx, store.LockingStrengthShare, accountID) + owner, err := am.Store.GetAccountOwner(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } @@ -1175,7 +1176,7 @@ func validateUserInvite(invite *types.UserInfo) error { func (am *DefaultAccountManager) GetCurrentUserInfo(ctx context.Context, userAuth nbcontext.UserAuth) (*users.UserInfoWithPermissions, error) { accountID, userID := userAuth.AccountId, userAuth.UserId - user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + user, err := am.Store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) if err != nil { return nil, err } @@ -1192,7 +1193,7 @@ func (am *DefaultAccountManager) GetCurrentUserInfo(ctx context.Context, userAut return nil, err } - settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthShare, accountID) + settings, err := am.Store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) if err != nil { return nil, err } diff --git a/management/server/user_test.go b/management/server/user_test.go index 8ab6584cf..8ab0c1565 100644 --- a/management/server/user_test.go +++ b/management/server/user_test.go @@ -15,9 +15,9 @@ 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/management/server/users" "github.com/netbirdio/netbird/management/server/util" + "github.com/netbirdio/netbird/shared/management/status" nbpeer "github.com/netbirdio/netbird/management/server/peer" "github.com/netbirdio/netbird/management/server/store" @@ -88,7 +88,7 @@ func TestUser_CreatePAT_ForSameUser(t *testing.T) { assert.Equal(t, pat.ID, tokenID) - user, err := am.Store.GetUserByPATID(context.Background(), store.LockingStrengthShare, tokenID) + user, err := am.Store.GetUserByPATID(context.Background(), store.LockingStrengthNone, tokenID) if err != nil { t.Fatalf("Error when getting user by token ID: %s", err) } @@ -1521,7 +1521,7 @@ func TestSaveOrAddUser_PreventAccountSwitch(t *testing.T) { _, err = am.SaveOrAddUser(context.Background(), "account2", "ownerAccount2", account1.Users[targetId], true) assert.Error(t, err, "update user to another account should fail") - user, err := s.GetUserByUserID(context.Background(), store.LockingStrengthShare, targetId) + user, err := s.GetUserByUserID(context.Background(), store.LockingStrengthNone, targetId) require.NoError(t, err) assert.Equal(t, account1.Users[targetId].Id, user.Id) assert.Equal(t, account1.Users[targetId].AccountID, user.AccountID) diff --git a/management/server/users/manager.go b/management/server/users/manager.go index 718eb6190..e07f28706 100644 --- a/management/server/users/manager.go +++ b/management/server/users/manager.go @@ -26,7 +26,7 @@ func NewManager(store store.Store) Manager { } func (m *managerImpl) GetUser(ctx context.Context, userID string) (*types.User, error) { - return m.store.GetUserByUserID(ctx, store.LockingStrengthShare, userID) + return m.store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) } func NewManagerMock() Manager { 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/pprof.go b/relay/cmd/pprof.go new file mode 100644 index 000000000..37efd35f0 --- /dev/null +++ b/relay/cmd/pprof.go @@ -0,0 +1,33 @@ +//go:build pprof +// +build pprof + +package cmd + +import ( + "net/http" + _ "net/http/pprof" + "os" + + log "github.com/sirupsen/logrus" +) + +func init() { + addr := pprofAddr() + go pprof(addr) +} + +func pprofAddr() string { + listenAddr := os.Getenv("NB_PPROF_ADDR") + if listenAddr == "" { + return "localhost:6969" + } + + return listenAddr +} + +func pprof(listenAddr string) { + log.Infof("listening pprof on: %s\n", listenAddr) + if err := http.ListenAndServe(listenAddr, nil); err != nil { + log.Fatalf("Failed to start pprof: %v", err) + } +} 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..dc26253e9 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*15) + 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 eff1ccb87..184666575 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 2ff84e460..c7ae1444f 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/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 }