Compare commits
265
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
437c778ee9 | ||
|
|
34448bc9fa | ||
|
|
cc05f4582b | ||
|
|
9dc47d462c | ||
|
|
6ebcc7e135 | ||
|
|
04b9de0775 | ||
|
|
3971d2f4fd | ||
|
|
a718d6ede2 | ||
|
|
f296956c6f | ||
|
|
cc5800f46d | ||
|
|
7e062d6c68 | ||
|
|
95ba4dcee4 | ||
|
|
0331d68a36 | ||
|
|
fef41f0fe4 | ||
|
|
97a561c56b | ||
|
|
d690e981b6 | ||
|
|
63ad313ff6 | ||
|
|
0a884d839e | ||
|
|
c4bfbbaa52 | ||
|
|
e4e9998e40 | ||
|
|
4efea823bf | ||
|
|
3508144575 | ||
|
|
0254a380e7 | ||
|
|
f103fc45cb | ||
|
|
26d3dd7605 | ||
|
|
c009055693 | ||
|
|
14181c909c | ||
|
|
a05dc3823d | ||
|
|
7d19bdf085 | ||
|
|
a1b048f2ad | ||
|
|
0bd227196e | ||
|
|
eea7687ddf | ||
|
|
57d3ee5aac | ||
|
|
cfdfdecc14 | ||
|
|
ac995bae6d | ||
|
|
41a5509ce0 | ||
|
|
db5e26db94 | ||
|
|
fe975fb834 | ||
|
|
e368d2995b | ||
|
|
a3241d8376 | ||
|
|
6dfc5772ba | ||
|
|
f70925178c | ||
|
|
9554934b92 | ||
|
|
7fdb824a37 | ||
|
|
412407adc0 | ||
|
|
e0874d7de7 | ||
|
|
8df1536cbb | ||
|
|
fcbacc62ec | ||
|
|
ee2ae45653 | ||
|
|
6f2f0f9ae4 | ||
|
|
c37ebc6fb3 | ||
|
|
23abb5743c | ||
|
|
b87aa0bc15 | ||
|
|
f1a65d732d | ||
|
|
a3c0ea3e71 | ||
|
|
abaf061c2a | ||
|
|
e531fb54b1 | ||
|
|
5fcfed5b16 | ||
|
|
5f43449f67 | ||
|
|
6796601aa6 | ||
|
|
1fc25c301b | ||
|
|
08ae281b2d | ||
|
|
bd47f44c63 | ||
|
|
381260911b | ||
|
|
38db42e7d6 | ||
|
|
5d606d909d | ||
|
|
d689718b50 | ||
|
|
54a73c6649 | ||
|
|
418377842e | ||
|
|
15ef56e03d | ||
|
|
917035f8e8 | ||
|
|
963e3f5457 | ||
|
|
e20b969188 | ||
|
|
1c7059ee67 | ||
|
|
22a3365658 | ||
|
|
08ab1e3478 | ||
|
|
ebb1f4007d | ||
|
|
acb53ece93 | ||
|
|
e020950cfd | ||
|
|
9dba262a20 | ||
|
|
5bcdf36377 | ||
|
|
1ffe8deb10 | ||
|
|
d069145bd1 | ||
|
|
f3493ee042 | ||
|
|
bf48044e5c | ||
|
|
fb4cc37a4a | ||
|
|
55b8d89a79 | ||
|
|
6968a32a5a | ||
|
|
cfe6753349 | ||
|
|
5ae15b3af3 | ||
|
|
b79adb706c | ||
|
|
f22497d5da | ||
|
|
95d672c9df | ||
|
|
7d08a609e6 | ||
|
|
eea6120cd0 | ||
|
|
0cb02bd906 | ||
|
|
08d3867f41 | ||
|
|
b16d63643c | ||
|
|
940d01bdea | ||
|
|
ba9158d159 | ||
|
|
ca9a7e11ef | ||
|
|
a803f47685 | ||
|
|
79fed32f01 | ||
|
|
6b00bb0a66 | ||
|
|
e2adef1eea | ||
|
|
9e5fa11792 | ||
|
|
1ff75acb31 | ||
|
|
1754160686 | ||
|
|
423f6266fb | ||
|
|
16d1b4a14a | ||
|
|
7c14056faf | ||
|
|
62e37dc2e2 | ||
|
|
6a08695ee8 | ||
|
|
9a67a8e427 | ||
|
|
73aa0785ba | ||
|
|
53c1016a8e | ||
|
|
fd442138e6 | ||
|
|
be5f30225a | ||
|
|
7467e9fb8c | ||
|
|
2390c2e46e | ||
|
|
778c223176 | ||
|
|
36cd0dd85c | ||
|
|
09a1d5a02d | ||
|
|
7c996ac9b5 | ||
|
|
cf9fd5d960 | ||
|
|
1c5ab7cb8f | ||
|
|
aaad3b25a7 | ||
|
|
9904235a2f | ||
|
|
780e9f57a5 | ||
|
|
a8db73285b | ||
|
|
3b43c00d12 | ||
|
|
2f390e1794 | ||
|
|
3630ebb3ae | ||
|
|
260c46df04 | ||
|
|
7f11e3205d | ||
|
|
1c8f92a96f | ||
|
|
7b6294b624 | ||
|
|
156d0b1fef | ||
|
|
2cf00dba58 | ||
|
|
d2a7f3ae36 | ||
|
|
6a64d4e4dd | ||
|
|
51e63c246b | ||
|
|
99e6b1eda4 | ||
|
|
dc26a5a436 | ||
|
|
3883b2fb41 | ||
|
|
ed58659a01 | ||
|
|
5190923c70 | ||
|
|
7c647dd160 | ||
|
|
07e59b2708 | ||
|
|
0a3a9f977d | ||
|
|
2f263bf7e6 | ||
|
|
f65f4fc280 | ||
|
|
adbd7ab4c3 | ||
|
|
0419834482 | ||
|
|
f797d2d9cb | ||
|
|
5ae7efe8f7 | ||
|
|
d6e35bd0fe | ||
|
|
0e00f1c8f7 | ||
|
|
4433f44a12 | ||
|
|
7504e718d7 | ||
|
|
9b0387e7ee | ||
|
|
5ccce1ab3f | ||
|
|
e366fe340e | ||
|
|
b01809f8e3 | ||
|
|
790ef39187 | ||
|
|
3af16cf333 | ||
|
|
d09c69f303 | ||
|
|
096d4ac529 | ||
|
|
8fafde614a | ||
|
|
694ae13418 | ||
|
|
b5b7dd4f53 | ||
|
|
476785b122 | ||
|
|
907677f835 | ||
|
|
7d844b9410 | ||
|
|
eeabc64a73 | ||
|
|
5da2b0fdcc | ||
|
|
a0005a604e | ||
|
|
a89bb807a6 | ||
|
|
28f3354ffa | ||
|
|
562923c600 | ||
|
|
0dd0c67b3b | ||
|
|
ca33849f31 | ||
|
|
18cd0f1480 | ||
|
|
b02982f6b1 | ||
|
|
4d89ae27ef | ||
|
|
733ea77c5c | ||
|
|
92f72bfce6 | ||
|
|
bffb25bea7 | ||
|
|
3af4543e80 | ||
|
|
146774860b | ||
|
|
5243481316 | ||
|
|
76a39c1dcb | ||
|
|
02ce918114 | ||
|
|
30cfc22cb6 | ||
|
|
3168afbfcb | ||
|
|
a73ee47557 | ||
|
|
fa6ff005f2 | ||
|
|
095379fa60 | ||
|
|
30572fe1b8 | ||
|
|
3a6f364b03 | ||
|
|
5345d716ee | ||
|
|
f882c36e0a | ||
|
|
e95cfa1a00 | ||
|
|
0d480071b6 | ||
|
|
8e0b7b6c25 | ||
|
|
f204da0d68 | ||
|
|
7d74904d62 | ||
|
|
760ac5e07d | ||
|
|
4352228797 | ||
|
|
74c770609c | ||
|
|
f4ca36ed7e | ||
|
|
c86da92fc6 | ||
|
|
3f0c577456 | ||
|
|
717da8c7b7 | ||
|
|
a0a61d4f47 | ||
|
|
5b1fced872 | ||
|
|
c98dcf5ef9 | ||
|
|
57cb6bfccb | ||
|
|
95bf97dc3c | ||
|
|
3d116c9d33 | ||
|
|
a9ce9f8d5a | ||
|
|
10b981a855 | ||
|
|
7700b4333d | ||
|
|
7d0131111e | ||
|
|
1daea35e4b | ||
|
|
f97544af0d | ||
|
|
231e80cc15 | ||
|
|
a4c1362bff | ||
|
|
b611d4a751 | ||
|
|
2c9decfa55 | ||
|
|
3c5ac17e2f | ||
|
|
ae42bbb898 | ||
|
|
b86722394b | ||
|
|
a103f69767 | ||
|
|
73fbb3fc62 | ||
|
|
7b3523e25e | ||
|
|
6e4e1386e7 | ||
|
|
671e9af6eb | ||
|
|
50f42caf94 | ||
|
|
b7eeefc102 | ||
|
|
8dd22f3a4f | ||
|
|
4b89427447 | ||
|
|
b71e2860cf | ||
|
|
160b27bc60 | ||
|
|
c084386b88 | ||
|
|
6889047350 | ||
|
|
245bbb4acf | ||
|
|
2b2fc02d83 | ||
|
|
703ef29199 | ||
|
|
b0b60b938a | ||
|
|
e3a026bf1c | ||
|
|
94503465ee | ||
|
|
8d959b0abc | ||
|
|
1d8390b935 | ||
|
|
2851e38a1f | ||
|
|
51261fe7a9 | ||
|
|
304321d019 | ||
|
|
f8c3295645 | ||
|
|
183619d1e1 | ||
|
|
3b832d1f21 | ||
|
|
fcb849698f | ||
|
|
7527e0ebdb | ||
|
|
ed5f98da5b | ||
|
|
12b38e25da | ||
|
|
626e892e3b |
No files matched your search
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: codespell
|
||||
uses: codespell-project/actions-codespell@v2
|
||||
with:
|
||||
ignore_words_list: erro,clienta,hastable,iif,groupd,testin,groupe,cros,ans,deriver
|
||||
ignore_words_list: erro,clienta,hastable,iif,groupd,testin,groupe,cros,ans
|
||||
skip: go.mod,go.sum,**/proxy/web/**
|
||||
golangci:
|
||||
strategy:
|
||||
|
||||
@@ -160,7 +160,7 @@ jobs:
|
||||
username: ${{ secrets.DOCKER_USER }}
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
- name: Log in to the GitHub container registry
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
@@ -176,7 +176,6 @@ jobs:
|
||||
- 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
|
||||
id: goreleaser
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
version: ${{ env.GORELEASER_VER }}
|
||||
@@ -186,19 +185,6 @@ jobs:
|
||||
HOMEBREW_TAP_GITHUB_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
|
||||
UPLOAD_DEBIAN_SECRET: ${{ secrets.PKG_UPLOAD_SECRET }}
|
||||
UPLOAD_YUM_SECRET: ${{ secrets.PKG_UPLOAD_SECRET }}
|
||||
- name: Tag and push PR images (amd64 only)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
run: |
|
||||
PR_TAG="pr-${{ github.event.pull_request.number }}"
|
||||
echo '${{ steps.goreleaser.outputs.artifacts }}' | \
|
||||
jq -r '.[] | select(.type == "Docker Image") | select(.goarch == "amd64") | .name' | \
|
||||
grep '^ghcr.io/' | while read -r SRC; do
|
||||
IMG_NAME="${SRC%%:*}"
|
||||
DST="${IMG_NAME}:${PR_TAG}"
|
||||
echo "Tagging ${SRC} -> ${DST}"
|
||||
docker tag "$SRC" "$DST"
|
||||
docker push "$DST"
|
||||
done
|
||||
- name: upload non tags for debug purposes
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -140,20 +140,6 @@ 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-proxy
|
||||
dir: proxy/cmd/proxy
|
||||
env: [CGO_ENABLED=0]
|
||||
binary: netbird-proxy
|
||||
goos:
|
||||
- linux
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- arm
|
||||
ldflags:
|
||||
- -s -w -X main.Version={{.Version}} -X main.Commit={{.Commit}} -X main.BuildDate={{.CommitDate}}
|
||||
mod_timestamp: "{{ .CommitTimestamp }}"
|
||||
|
||||
universal_binaries:
|
||||
- id: netbird
|
||||
|
||||
@@ -603,55 +589,6 @@ dockers:
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/netbirdio/{{.ProjectName}}"
|
||||
- "--label=maintainer=dev@netbird.io"
|
||||
- image_templates:
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-amd64
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-amd64
|
||||
ids:
|
||||
- netbird-proxy
|
||||
goarch: amd64
|
||||
use: buildx
|
||||
dockerfile: proxy/Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/amd64"
|
||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/netbirdio/{{.ProjectName}}"
|
||||
- "--label=maintainer=dev@netbird.io"
|
||||
- image_templates:
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-arm64v8
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-arm64v8
|
||||
ids:
|
||||
- netbird-proxy
|
||||
goarch: arm64
|
||||
use: buildx
|
||||
dockerfile: proxy/Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm64"
|
||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/netbirdio/{{.ProjectName}}"
|
||||
- "--label=maintainer=dev@netbird.io"
|
||||
- image_templates:
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-arm
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-arm
|
||||
ids:
|
||||
- netbird-proxy
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
use: buildx
|
||||
dockerfile: proxy/Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm"
|
||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/netbirdio/{{.ProjectName}}"
|
||||
- "--label=maintainer=dev@netbird.io"
|
||||
docker_manifests:
|
||||
- name_template: netbirdio/netbird:{{ .Version }}
|
||||
image_templates:
|
||||
@@ -832,30 +769,6 @@ docker_manifests:
|
||||
- ghcr.io/netbirdio/netbird-server:{{ .Version }}-arm
|
||||
- ghcr.io/netbirdio/netbird-server:{{ .Version }}-amd64
|
||||
|
||||
- name_template: netbirdio/reverse-proxy:{{ .Version }}
|
||||
image_templates:
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-arm64v8
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-arm
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-amd64
|
||||
|
||||
- name_template: netbirdio/reverse-proxy:latest
|
||||
image_templates:
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-arm64v8
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-arm
|
||||
- netbirdio/reverse-proxy:{{ .Version }}-amd64
|
||||
|
||||
- name_template: ghcr.io/netbirdio/reverse-proxy:{{ .Version }}
|
||||
image_templates:
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-arm64v8
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-arm
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-amd64
|
||||
|
||||
- name_template: ghcr.io/netbirdio/reverse-proxy:latest
|
||||
image_templates:
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-arm64v8
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-arm
|
||||
- ghcr.io/netbirdio/reverse-proxy:{{ .Version }}-amd64
|
||||
|
||||
brews:
|
||||
- ids:
|
||||
- default
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
package android
|
||||
|
||||
import (
|
||||
"github.com/netbirdio/netbird/client/internal/lazyconn"
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
)
|
||||
import "github.com/netbirdio/netbird/client/internal/peer"
|
||||
|
||||
var (
|
||||
// EnvKeyNBForceRelay Exported for Android java client to force relay connections
|
||||
// EnvKeyNBForceRelay Exported for Android java client
|
||||
EnvKeyNBForceRelay = peer.EnvKeyNBForceRelay
|
||||
|
||||
// EnvKeyNBLazyConn Exported for Android java client to configure lazy connection
|
||||
EnvKeyNBLazyConn = lazyconn.EnvEnableLazyConn
|
||||
|
||||
// EnvKeyNBInactivityThreshold Exported for Android java client to configure connection inactivity threshold
|
||||
EnvKeyNBInactivityThreshold = lazyconn.EnvInactivityThreshold
|
||||
)
|
||||
|
||||
// EnvList wraps a Go map for export to Java
|
||||
|
||||
@@ -42,8 +42,6 @@ const (
|
||||
dnsPolicyConfigConfigOptionsKey = "ConfigOptions"
|
||||
dnsPolicyConfigConfigOptionsValue = 0x8
|
||||
|
||||
nrptMaxDomainsPerRule = 50
|
||||
|
||||
interfaceConfigPath = `SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces`
|
||||
interfaceConfigNameServerKey = "NameServer"
|
||||
interfaceConfigSearchListKey = "SearchList"
|
||||
@@ -200,11 +198,10 @@ func (r *registryConfigurator) applyDNSConfig(config HostDNSConfig, stateManager
|
||||
|
||||
if len(matchDomains) != 0 {
|
||||
count, err := r.addDNSMatchPolicy(matchDomains, config.ServerIP)
|
||||
// Update count even on error to ensure cleanup covers partially created rules
|
||||
r.nrptEntryCount = count
|
||||
if err != nil {
|
||||
return fmt.Errorf("add dns match policy: %w", err)
|
||||
}
|
||||
r.nrptEntryCount = count
|
||||
} else {
|
||||
r.nrptEntryCount = 0
|
||||
}
|
||||
@@ -242,33 +239,23 @@ func (r *registryConfigurator) addDNSSetupForAll(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
|
||||
for i, domain := range domains {
|
||||
localPath := fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i)
|
||||
gpoPath := fmt.Sprintf("%s-%d", gpoDnsPolicyConfigMatchPath, i)
|
||||
|
||||
// We need to batch domains into chunks and create one NRPT rule per batch.
|
||||
ruleIndex := 0
|
||||
for i := 0; i < len(domains); i += nrptMaxDomainsPerRule {
|
||||
end := i + nrptMaxDomainsPerRule
|
||||
if end > len(domains) {
|
||||
end = len(domains)
|
||||
singleDomain := []string{domain}
|
||||
|
||||
if err := r.configureDNSPolicy(localPath, singleDomain, ip); err != nil {
|
||||
return i, fmt.Errorf("configure DNS Local policy for domain %s: %w", domain, err)
|
||||
}
|
||||
batchDomains := domains[i:end]
|
||||
|
||||
localPath := fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, ruleIndex)
|
||||
gpoPath := fmt.Sprintf("%s-%d", gpoDnsPolicyConfigMatchPath, ruleIndex)
|
||||
|
||||
if err := r.configureDNSPolicy(localPath, batchDomains, ip); err != nil {
|
||||
return ruleIndex, fmt.Errorf("configure DNS Local policy for rule %d: %w", ruleIndex, err)
|
||||
}
|
||||
|
||||
// Increment immediately so the caller's cleanup path knows about this rule
|
||||
ruleIndex++
|
||||
|
||||
if r.gpo {
|
||||
if err := r.configureDNSPolicy(gpoPath, batchDomains, ip); err != nil {
|
||||
return ruleIndex, fmt.Errorf("configure gpo DNS policy for rule %d: %w", ruleIndex-1, err)
|
||||
if err := r.configureDNSPolicy(gpoPath, singleDomain, ip); err != nil {
|
||||
return i, fmt.Errorf("configure gpo DNS policy: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Debugf("added NRPT rule %d with %d domains", ruleIndex-1, len(batchDomains))
|
||||
log.Debugf("added NRPT entry for domain: %s", domain)
|
||||
}
|
||||
|
||||
if r.gpo {
|
||||
@@ -277,8 +264,8 @@ func (r *registryConfigurator) addDNSMatchPolicy(domains []string, ip netip.Addr
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("added %d NRPT rules for %d domains. Domain list: %v", ruleIndex, len(domains), domains)
|
||||
return ruleIndex, nil
|
||||
log.Infof("added %d separate NRPT entries. Domain list: %s", len(domains), domains)
|
||||
return len(domains), nil
|
||||
}
|
||||
|
||||
func (r *registryConfigurator) configureDNSPolicy(policyPath string, domains []string, ip netip.Addr) error {
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
// TestNRPTEntriesCleanupOnConfigChange tests that old NRPT entries are properly cleaned up
|
||||
// when the number of match domains decreases between configuration changes.
|
||||
// With batching enabled (50 domains per rule), we need enough domains to create multiple rules.
|
||||
func TestNRPTEntriesCleanupOnConfigChange(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping registry integration test in short mode")
|
||||
@@ -38,60 +37,51 @@ func TestNRPTEntriesCleanupOnConfigChange(t *testing.T) {
|
||||
gpo: false,
|
||||
}
|
||||
|
||||
// Create 125 domains which will result in 3 NRPT rules (50+50+25)
|
||||
domains125 := make([]DomainConfig, 125)
|
||||
for i := 0; i < 125; i++ {
|
||||
domains125[i] = DomainConfig{
|
||||
Domain: fmt.Sprintf("domain%d.com", i+1),
|
||||
MatchOnly: true,
|
||||
}
|
||||
}
|
||||
|
||||
config125 := HostDNSConfig{
|
||||
config5 := HostDNSConfig{
|
||||
ServerIP: testIP,
|
||||
Domains: domains125,
|
||||
Domains: []DomainConfig{
|
||||
{Domain: "domain1.com", MatchOnly: true},
|
||||
{Domain: "domain2.com", MatchOnly: true},
|
||||
{Domain: "domain3.com", MatchOnly: true},
|
||||
{Domain: "domain4.com", MatchOnly: true},
|
||||
{Domain: "domain5.com", MatchOnly: true},
|
||||
},
|
||||
}
|
||||
|
||||
err = cfg.applyDNSConfig(config125, nil)
|
||||
err = cfg.applyDNSConfig(config5, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify 3 NRPT rules exist
|
||||
assert.Equal(t, 3, cfg.nrptEntryCount, "Should create 3 NRPT rules for 125 domains")
|
||||
for i := 0; i < 3; i++ {
|
||||
// Verify all 5 entries exist
|
||||
for i := 0; i < 5; i++ {
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, exists, "NRPT rule %d should exist after first config", i)
|
||||
assert.True(t, exists, "Entry %d should exist after first config", i)
|
||||
}
|
||||
|
||||
// Reduce to 75 domains which will result in 2 NRPT rules (50+25)
|
||||
domains75 := make([]DomainConfig, 75)
|
||||
for i := 0; i < 75; i++ {
|
||||
domains75[i] = DomainConfig{
|
||||
Domain: fmt.Sprintf("domain%d.com", i+1),
|
||||
MatchOnly: true,
|
||||
}
|
||||
}
|
||||
|
||||
config75 := HostDNSConfig{
|
||||
config2 := HostDNSConfig{
|
||||
ServerIP: testIP,
|
||||
Domains: domains75,
|
||||
Domains: []DomainConfig{
|
||||
{Domain: "domain1.com", MatchOnly: true},
|
||||
{Domain: "domain2.com", MatchOnly: true},
|
||||
},
|
||||
}
|
||||
|
||||
err = cfg.applyDNSConfig(config75, nil)
|
||||
err = cfg.applyDNSConfig(config2, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify first 2 NRPT rules exist
|
||||
assert.Equal(t, 2, cfg.nrptEntryCount, "Should create 2 NRPT rules for 75 domains")
|
||||
// Verify first 2 entries exist
|
||||
for i := 0; i < 2; i++ {
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, exists, "NRPT rule %d should exist after second config", i)
|
||||
assert.True(t, exists, "Entry %d should exist after second config", i)
|
||||
}
|
||||
|
||||
// Verify rule 2 is cleaned up
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, 2))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "NRPT rule 2 should NOT exist after reducing to 75 domains")
|
||||
// Verify entries 2-4 are cleaned up
|
||||
for i := 2; i < 5; i++ {
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "Entry %d should NOT exist after reducing to 2 domains", i)
|
||||
}
|
||||
}
|
||||
|
||||
func registryKeyExists(path string) (bool, error) {
|
||||
@@ -107,106 +97,6 @@ func registryKeyExists(path string) (bool, error) {
|
||||
}
|
||||
|
||||
func cleanupRegistryKeys(*testing.T) {
|
||||
// Clean up more entries to account for batching tests with many domains
|
||||
cfg := ®istryConfigurator{nrptEntryCount: 20}
|
||||
cfg := ®istryConfigurator{nrptEntryCount: 10}
|
||||
_ = cfg.removeDNSMatchPolicies()
|
||||
}
|
||||
|
||||
// TestNRPTDomainBatching verifies that domains are correctly batched into NRPT rules.
|
||||
func TestNRPTDomainBatching(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping registry integration test in short mode")
|
||||
}
|
||||
|
||||
defer cleanupRegistryKeys(t)
|
||||
cleanupRegistryKeys(t)
|
||||
|
||||
testIP := netip.MustParseAddr("100.64.0.1")
|
||||
|
||||
// Create a test interface registry key so updateSearchDomains doesn't fail
|
||||
testGUID := "{12345678-1234-1234-1234-123456789ABC}"
|
||||
interfacePath := `SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\` + testGUID
|
||||
testKey, _, err := registry.CreateKey(registry.LOCAL_MACHINE, interfacePath, registry.SET_VALUE)
|
||||
require.NoError(t, err, "Should create test interface registry key")
|
||||
testKey.Close()
|
||||
defer func() {
|
||||
_ = registry.DeleteKey(registry.LOCAL_MACHINE, interfacePath)
|
||||
}()
|
||||
|
||||
cfg := ®istryConfigurator{
|
||||
guid: testGUID,
|
||||
gpo: false,
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
domainCount int
|
||||
expectedRuleCount int
|
||||
}{
|
||||
{
|
||||
name: "Less than 50 domains (single rule)",
|
||||
domainCount: 30,
|
||||
expectedRuleCount: 1,
|
||||
},
|
||||
{
|
||||
name: "Exactly 50 domains (single rule)",
|
||||
domainCount: 50,
|
||||
expectedRuleCount: 1,
|
||||
},
|
||||
{
|
||||
name: "51 domains (two rules)",
|
||||
domainCount: 51,
|
||||
expectedRuleCount: 2,
|
||||
},
|
||||
{
|
||||
name: "100 domains (two rules)",
|
||||
domainCount: 100,
|
||||
expectedRuleCount: 2,
|
||||
},
|
||||
{
|
||||
name: "125 domains (three rules: 50+50+25)",
|
||||
domainCount: 125,
|
||||
expectedRuleCount: 3,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Clean up before each subtest
|
||||
cleanupRegistryKeys(t)
|
||||
|
||||
// Generate domains
|
||||
domains := make([]DomainConfig, tc.domainCount)
|
||||
for i := 0; i < tc.domainCount; i++ {
|
||||
domains[i] = DomainConfig{
|
||||
Domain: fmt.Sprintf("domain%d.com", i+1),
|
||||
MatchOnly: true,
|
||||
}
|
||||
}
|
||||
|
||||
config := HostDNSConfig{
|
||||
ServerIP: testIP,
|
||||
Domains: domains,
|
||||
}
|
||||
|
||||
err := cfg.applyDNSConfig(config, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify that exactly expectedRuleCount rules were created
|
||||
assert.Equal(t, tc.expectedRuleCount, cfg.nrptEntryCount,
|
||||
"Should create %d NRPT rules for %d domains", tc.expectedRuleCount, tc.domainCount)
|
||||
|
||||
// Verify all expected rules exist
|
||||
for i := 0; i < tc.expectedRuleCount; i++ {
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, i))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, exists, "NRPT rule %d should exist", i)
|
||||
}
|
||||
|
||||
// Verify no extra rules were created
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-%d", dnsPolicyConfigMatchPath, tc.expectedRuleCount))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "No NRPT rule should exist at index %d", tc.expectedRuleCount)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -84,18 +84,3 @@ func (m *MockServer) UpdateServerConfig(domains dnsconfig.ServerDomains) error {
|
||||
func (m *MockServer) PopulateManagementDomain(mgmtURL *url.URL) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeginBatch mock implementation of BeginBatch from Server interface
|
||||
func (m *MockServer) BeginBatch() {
|
||||
// Mock implementation - no-op
|
||||
}
|
||||
|
||||
// EndBatch mock implementation of EndBatch from Server interface
|
||||
func (m *MockServer) EndBatch() {
|
||||
// Mock implementation - no-op
|
||||
}
|
||||
|
||||
// CancelBatch mock implementation of CancelBatch from Server interface
|
||||
func (m *MockServer) CancelBatch() {
|
||||
// Mock implementation - no-op
|
||||
}
|
||||
@@ -45,9 +45,6 @@ type IosDnsManager interface {
|
||||
type Server interface {
|
||||
RegisterHandler(domains domain.List, handler dns.Handler, priority int)
|
||||
DeregisterHandler(domains domain.List, priority int)
|
||||
BeginBatch()
|
||||
EndBatch()
|
||||
CancelBatch()
|
||||
Initialize() error
|
||||
Stop()
|
||||
DnsIP() netip.Addr
|
||||
@@ -90,7 +87,6 @@ type DefaultServer struct {
|
||||
currentConfigHash uint64
|
||||
handlerChain *HandlerChain
|
||||
extraDomains map[domain.Domain]int
|
||||
batchMode bool
|
||||
|
||||
mgmtCacheResolver *mgmt.Resolver
|
||||
|
||||
@@ -238,9 +234,7 @@ func (s *DefaultServer) RegisterHandler(domains domain.List, handler dns.Handler
|
||||
// convert to zone with simple ref counter
|
||||
s.extraDomains[toZone(domain)]++
|
||||
}
|
||||
if !s.batchMode {
|
||||
s.applyHostConfig()
|
||||
}
|
||||
s.applyHostConfig()
|
||||
}
|
||||
|
||||
func (s *DefaultServer) registerHandler(domains []string, handler dns.Handler, priority int) {
|
||||
@@ -269,41 +263,9 @@ func (s *DefaultServer) DeregisterHandler(domains domain.List, priority int) {
|
||||
delete(s.extraDomains, zone)
|
||||
}
|
||||
}
|
||||
if !s.batchMode {
|
||||
s.applyHostConfig()
|
||||
}
|
||||
}
|
||||
|
||||
// BeginBatch starts batch mode for DNS handler registration/deregistration.
|
||||
// In batch mode, applyHostConfig() is not called after each handler operation,
|
||||
// allowing multiple handlers to be registered/deregistered efficiently.
|
||||
// Must be followed by EndBatch() to apply the accumulated changes.
|
||||
func (s *DefaultServer) BeginBatch() {
|
||||
s.mux.Lock()
|
||||
defer s.mux.Unlock()
|
||||
log.Debugf("DNS batch mode enabled")
|
||||
s.batchMode = true
|
||||
}
|
||||
|
||||
// EndBatch ends batch mode and applies all accumulated DNS configuration changes.
|
||||
func (s *DefaultServer) EndBatch() {
|
||||
s.mux.Lock()
|
||||
defer s.mux.Unlock()
|
||||
log.Debugf("DNS batch mode disabled, applying accumulated changes")
|
||||
s.batchMode = false
|
||||
s.applyHostConfig()
|
||||
}
|
||||
|
||||
// CancelBatch cancels batch mode without applying accumulated changes.
|
||||
// This is useful when operations fail partway through and you want to
|
||||
// discard partial state rather than applying it.
|
||||
func (s *DefaultServer) CancelBatch() {
|
||||
s.mux.Lock()
|
||||
defer s.mux.Unlock()
|
||||
log.Debugf("DNS batch mode cancelled, discarding accumulated changes")
|
||||
s.batchMode = false
|
||||
}
|
||||
|
||||
func (s *DefaultServer) deregisterHandler(domains []string, priority int) {
|
||||
log.Debugf("deregistering handler with priority %d for %v", priority, domains)
|
||||
|
||||
@@ -561,7 +523,6 @@ func (s *DefaultServer) applyConfiguration(update nbdns.Config) error {
|
||||
s.currentConfig.RouteAll = false
|
||||
}
|
||||
|
||||
// Always apply host config for management updates, regardless of batch mode
|
||||
s.applyHostConfig()
|
||||
|
||||
s.shutdownWg.Add(1)
|
||||
@@ -926,7 +887,6 @@ func (s *DefaultServer) upstreamCallbacks(
|
||||
}
|
||||
}
|
||||
|
||||
// Always apply host config when nameserver goes down, regardless of batch mode
|
||||
s.applyHostConfig()
|
||||
|
||||
go func() {
|
||||
@@ -962,7 +922,6 @@ func (s *DefaultServer) upstreamCallbacks(
|
||||
s.registerHandler([]string{nbdns.RootZone}, handler, priority)
|
||||
}
|
||||
|
||||
// Always apply host config when nameserver reactivates, regardless of batch mode
|
||||
s.applyHostConfig()
|
||||
|
||||
s.updateNSState(nsGroup, nil, true)
|
||||
|
||||
@@ -18,12 +18,7 @@ func TestGetServerDns(t *testing.T) {
|
||||
t.Errorf("invalid dns server instance: %s", err)
|
||||
}
|
||||
|
||||
mockSrvB, ok := srvB.(*MockServer)
|
||||
if !ok {
|
||||
t.Errorf("returned server is not a MockServer")
|
||||
}
|
||||
|
||||
if mockSrvB != srv {
|
||||
if srvB != srv {
|
||||
t.Errorf("mismatch dns instances")
|
||||
}
|
||||
}
|
||||
@@ -410,7 +410,7 @@ func (conn *Conn) onICEConnectionIsReady(priority conntype.ConnPriority, iceConn
|
||||
conn.doOnConnected(iceConnInfo.RosenpassPubKey, iceConnInfo.RosenpassAddr)
|
||||
}
|
||||
|
||||
func (conn *Conn) onICEStateDisconnected(sessionChanged bool) {
|
||||
func (conn *Conn) onICEStateDisconnected() {
|
||||
conn.mu.Lock()
|
||||
defer conn.mu.Unlock()
|
||||
|
||||
@@ -430,10 +430,6 @@ func (conn *Conn) onICEStateDisconnected(sessionChanged bool) {
|
||||
if conn.isReadyToUpgrade() {
|
||||
conn.Log.Infof("ICE disconnected, set Relay to active connection")
|
||||
conn.dumpState.SwitchToRelay()
|
||||
if sessionChanged {
|
||||
conn.resetEndpoint()
|
||||
}
|
||||
|
||||
conn.wgProxyRelay.Work()
|
||||
|
||||
presharedKey := conn.presharedKey(conn.rosenpassRemoteKey)
|
||||
@@ -761,17 +757,6 @@ func (conn *Conn) newProxy(remoteConn net.Conn) (wgproxy.Proxy, error) {
|
||||
return wgProxy, nil
|
||||
}
|
||||
|
||||
func (conn *Conn) resetEndpoint() {
|
||||
if !isController(conn.config) {
|
||||
return
|
||||
}
|
||||
conn.Log.Infof("reset wg endpoint")
|
||||
conn.wgWatcher.Reset()
|
||||
if err := conn.endpointUpdater.RemoveEndpointAddress(); err != nil {
|
||||
conn.Log.Warnf("failed to remove endpoint address before update: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (conn *Conn) isReadyToUpgrade() bool {
|
||||
return conn.wgProxyRelay != nil && conn.currentConnPriority != conntype.Relay
|
||||
}
|
||||
|
||||
@@ -66,10 +66,6 @@ func (e *EndpointUpdater) RemoveWgPeer() error {
|
||||
return e.wgConfig.WgInterface.RemovePeer(e.wgConfig.RemoteKey)
|
||||
}
|
||||
|
||||
func (e *EndpointUpdater) RemoveEndpointAddress() error {
|
||||
return e.wgConfig.WgInterface.RemoveEndpointAddress(e.wgConfig.RemoteKey)
|
||||
}
|
||||
|
||||
func (e *EndpointUpdater) waitForCloseTheDelayedUpdate() {
|
||||
if e.cancelFunc == nil {
|
||||
return
|
||||
|
||||
@@ -32,8 +32,6 @@ type WGWatcher struct {
|
||||
|
||||
enabled bool
|
||||
muEnabled sync.RWMutex
|
||||
|
||||
resetCh chan struct{}
|
||||
}
|
||||
|
||||
func NewWGWatcher(log *log.Entry, wgIfaceStater WGInterfaceStater, peerKey string, stateDump *stateDump) *WGWatcher {
|
||||
@@ -42,7 +40,6 @@ func NewWGWatcher(log *log.Entry, wgIfaceStater WGInterfaceStater, peerKey strin
|
||||
wgIfaceStater: wgIfaceStater,
|
||||
peerKey: peerKey,
|
||||
stateDump: stateDump,
|
||||
resetCh: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,15 +76,6 @@ func (w *WGWatcher) IsEnabled() bool {
|
||||
return w.enabled
|
||||
}
|
||||
|
||||
// Reset signals the watcher that the WireGuard peer has been reset and a new
|
||||
// handshake is expected. This restarts the handshake timeout from scratch.
|
||||
func (w *WGWatcher) Reset() {
|
||||
select {
|
||||
case w.resetCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// wgStateCheck help to check the state of the WireGuard handshake and relay connection
|
||||
func (w *WGWatcher) periodicHandshakeCheck(ctx context.Context, onDisconnectedFn func(), enabledTime time.Time, initialHandshake time.Time) {
|
||||
w.log.Infof("WireGuard watcher started")
|
||||
@@ -117,12 +105,6 @@ func (w *WGWatcher) periodicHandshakeCheck(ctx context.Context, onDisconnectedFn
|
||||
w.stateDump.WGcheckSuccess()
|
||||
|
||||
w.log.Debugf("WireGuard watcher reset timer: %v", resetTime)
|
||||
case <-w.resetCh:
|
||||
w.log.Infof("WireGuard watcher received peer reset, restarting handshake timeout")
|
||||
lastHandshake = time.Time{}
|
||||
enabledTime = time.Now()
|
||||
timer.Stop()
|
||||
timer.Reset(wgHandshakeOvertime)
|
||||
case <-ctx.Done():
|
||||
w.log.Infof("WireGuard watcher stopped")
|
||||
return
|
||||
|
||||
@@ -52,9 +52,8 @@ type WorkerICE struct {
|
||||
// increase by one when disconnecting the agent
|
||||
// with it the remote peer can discard the already deprecated offer/answer
|
||||
// Without it the remote peer may recreate a workable ICE connection
|
||||
sessionID ICESessionID
|
||||
remoteSessionChanged bool
|
||||
muxAgent sync.Mutex
|
||||
sessionID ICESessionID
|
||||
muxAgent sync.Mutex
|
||||
|
||||
localUfrag string
|
||||
localPwd string
|
||||
@@ -107,7 +106,6 @@ func (w *WorkerICE) OnNewOffer(remoteOfferAnswer *OfferAnswer) {
|
||||
return
|
||||
}
|
||||
w.log.Debugf("agent already exists, recreate the connection")
|
||||
w.remoteSessionChanged = true
|
||||
w.agentDialerCancel()
|
||||
if w.agent != nil {
|
||||
if err := w.agent.Close(); err != nil {
|
||||
@@ -308,17 +306,13 @@ func (w *WorkerICE) connect(ctx context.Context, agent *icemaker.ThreadSafeAgent
|
||||
w.conn.onICEConnectionIsReady(selectedPriority(pair), ci)
|
||||
}
|
||||
|
||||
func (w *WorkerICE) closeAgent(agent *icemaker.ThreadSafeAgent, cancel context.CancelFunc) bool {
|
||||
func (w *WorkerICE) closeAgent(agent *icemaker.ThreadSafeAgent, cancel context.CancelFunc) {
|
||||
cancel()
|
||||
if err := agent.Close(); err != nil {
|
||||
w.log.Warnf("failed to close ICE agent: %s", err)
|
||||
}
|
||||
|
||||
w.muxAgent.Lock()
|
||||
defer w.muxAgent.Unlock()
|
||||
|
||||
sessionChanged := w.remoteSessionChanged
|
||||
w.remoteSessionChanged = false
|
||||
|
||||
if w.agent == agent {
|
||||
// consider to remove from here and move to the OnNewOffer
|
||||
@@ -331,7 +325,7 @@ func (w *WorkerICE) closeAgent(agent *icemaker.ThreadSafeAgent, cancel context.C
|
||||
w.agentConnecting = false
|
||||
w.remoteSessionID = ""
|
||||
}
|
||||
return sessionChanged
|
||||
w.muxAgent.Unlock()
|
||||
}
|
||||
|
||||
func (w *WorkerICE) punchRemoteWGPort(pair *ice.CandidatePair, remoteWgPort int) {
|
||||
@@ -432,11 +426,11 @@ func (w *WorkerICE) onConnectionStateChange(agent *icemaker.ThreadSafeAgent, dia
|
||||
// ice.ConnectionStateClosed happens when we recreate the agent. For the P2P to TURN switch important to
|
||||
// notify the conn.onICEStateDisconnected changes to update the current used priority
|
||||
|
||||
sessionChanged := w.closeAgent(agent, dialerCancel)
|
||||
w.closeAgent(agent, dialerCancel)
|
||||
|
||||
if w.lastKnownState == ice.ConnectionStateConnected {
|
||||
w.lastKnownState = ice.ConnectionStateDisconnected
|
||||
w.conn.onICEStateDisconnected(sessionChanged)
|
||||
w.conn.onICEStateDisconnected()
|
||||
}
|
||||
default:
|
||||
return
|
||||
|
||||
@@ -346,23 +346,6 @@ func (m *DefaultManager) updateSystemRoutes(newRoutes route.HAMap) error {
|
||||
}
|
||||
|
||||
var merr *multierror.Error
|
||||
|
||||
// Begin batch mode to avoid calling applyHostConfig() after each DNS handler operation
|
||||
batchStarted := false
|
||||
if m.dnsServer != nil {
|
||||
m.dnsServer.BeginBatch()
|
||||
batchStarted = true
|
||||
defer func() {
|
||||
if merr != nil {
|
||||
// On error, cancel batch to discard partial DNS state
|
||||
m.dnsServer.CancelBatch()
|
||||
} else {
|
||||
// On success, apply accumulated DNS changes
|
||||
m.dnsServer.EndBatch()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
for id, handler := range toRemove {
|
||||
if err := handler.RemoveRoute(); err != nil {
|
||||
merr = multierror.Append(merr, fmt.Errorf("remove route %s: %w", handler.String(), err))
|
||||
@@ -393,7 +376,6 @@ func (m *DefaultManager) updateSystemRoutes(newRoutes route.HAMap) error {
|
||||
m.activeRoutes[id] = handler
|
||||
}
|
||||
|
||||
_ = batchStarted // Mark as used
|
||||
return nberrors.FormatErrorOrNil(merr)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,7 @@
|
||||
|
||||
package NetBirdSDK
|
||||
|
||||
import (
|
||||
"github.com/netbirdio/netbird/client/internal/lazyconn"
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
)
|
||||
import "github.com/netbirdio/netbird/client/internal/peer"
|
||||
|
||||
// EnvList is an exported struct to be bound by gomobile
|
||||
type EnvList struct {
|
||||
@@ -35,13 +32,3 @@ func (el *EnvList) AllItems() map[string]string {
|
||||
func GetEnvKeyNBForceRelay() string {
|
||||
return peer.EnvKeyNBForceRelay
|
||||
}
|
||||
|
||||
// GetEnvKeyNBLazyConn Exports the environment variable for the iOS client
|
||||
func GetEnvKeyNBLazyConn() string {
|
||||
return lazyconn.EnvEnableLazyConn
|
||||
}
|
||||
|
||||
// GetEnvKeyNBInactivityThreshold Exports the environment variable for the iOS client
|
||||
func GetEnvKeyNBInactivityThreshold() string {
|
||||
return lazyconn.EnvInactivityThreshold
|
||||
}
|
||||
@@ -627,15 +627,7 @@ func (c *CombinedConfig) ToManagementConfig() (*nbconfig.Config, error) {
|
||||
|
||||
// Set HTTP config fields for embedded IDP
|
||||
httpConfig.AuthIssuer = mgmt.Auth.Issuer
|
||||
httpConfig.AuthAudience = "netbird-dashboard"
|
||||
httpConfig.AuthClientID = httpConfig.AuthAudience
|
||||
httpConfig.CLIAuthAudience = "netbird-cli"
|
||||
httpConfig.AuthUserIDClaim = "sub"
|
||||
httpConfig.AuthKeysLocation = mgmt.Auth.Issuer + "/keys"
|
||||
httpConfig.OIDCConfigEndpoint = mgmt.Auth.Issuer + "/.well-known/openid-configuration"
|
||||
httpConfig.IdpSignKeyRefreshEnabled = mgmt.Auth.SignKeyRefreshEnabled
|
||||
callbackURL := strings.TrimSuffix(httpConfig.AuthIssuer, "/oauth2")
|
||||
httpConfig.AuthCallbackURL = callbackURL + types.ProxyCallbackEndpointFull
|
||||
|
||||
return &nbconfig.Config{
|
||||
Stuns: stuns,
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/netbirdio/netbird/client/embed"
|
||||
)
|
||||
|
||||
const (
|
||||
echoPort = 9000
|
||||
connectTimeout = 120 * time.Second
|
||||
startTimeout = 60 * time.Second
|
||||
stopTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
type peerInfo struct {
|
||||
client *embed.Client
|
||||
tunnelIP string
|
||||
name string
|
||||
}
|
||||
|
||||
type pairStats struct {
|
||||
from string
|
||||
to string
|
||||
sent int64
|
||||
received int64
|
||||
lost int64
|
||||
rtts []time.Duration
|
||||
}
|
||||
|
||||
func (s *pairStats) summary() (avgRTT, minRTT, maxRTT time.Duration, lossPercent float64) {
|
||||
if len(s.rtts) == 0 {
|
||||
return 0, 0, 0, 100
|
||||
}
|
||||
minRTT = s.rtts[0]
|
||||
maxRTT = s.rtts[0]
|
||||
var total time.Duration
|
||||
for _, rtt := range s.rtts {
|
||||
total += rtt
|
||||
if rtt < minRTT {
|
||||
minRTT = rtt
|
||||
}
|
||||
if rtt > maxRTT {
|
||||
maxRTT = rtt
|
||||
}
|
||||
}
|
||||
avgRTT = total / time.Duration(len(s.rtts))
|
||||
if s.sent > 0 {
|
||||
lossPercent = float64(s.lost) / float64(s.sent) * 100
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
managementURL := flag.String("management-url", "", "Management server URL (required)")
|
||||
setupKey := flag.String("setup-key", "", "Reusable setup key (required)")
|
||||
numPeers := flag.Int("peers", 5, "Number of peers to spawn")
|
||||
forceRelay := flag.Bool("force-relay", false, "Force relay connections (NB_FORCE_RELAY=true)")
|
||||
duration := flag.Duration("duration", 30*time.Second, "Traffic test duration")
|
||||
packetSize := flag.Int("packet-size", 512, "UDP packet size in bytes")
|
||||
logLevel := flag.String("log-level", "panic", "Client log level (trace, debug, info, warn, error, panic)")
|
||||
flag.Parse()
|
||||
|
||||
if *managementURL == "" || *setupKey == "" {
|
||||
fmt.Fprintln(os.Stderr, "Error: --management-url and --setup-key are required")
|
||||
flag.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if *numPeers < 2 {
|
||||
fmt.Fprintln(os.Stderr, "Error: --peers must be at least 2")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Minimum packet size: 8 bytes for timestamp + 8 bytes for sequence number
|
||||
if *packetSize < 16 {
|
||||
fmt.Fprintln(os.Stderr, "Error: --packet-size must be at least 16")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if *forceRelay {
|
||||
os.Setenv("NB_FORCE_RELAY", "true")
|
||||
}
|
||||
os.Setenv("NB_USE_NETSTACK_MODE", "true")
|
||||
|
||||
fmt.Println("=== NetBird Performance Test ===")
|
||||
fmt.Printf("Management URL: %s\n", *managementURL)
|
||||
fmt.Printf("Peers: %d\n", *numPeers)
|
||||
fmt.Printf("Force relay: %v\n", *forceRelay)
|
||||
fmt.Printf("Duration: %s\n", *duration)
|
||||
fmt.Printf("Packet size: %d bytes\n", *packetSize)
|
||||
fmt.Println()
|
||||
|
||||
// Phase 1: Create peers
|
||||
fmt.Println("--- Phase 1: Creating peers ---")
|
||||
peers := make([]peerInfo, *numPeers)
|
||||
for i := 0; i < *numPeers; i++ {
|
||||
name := fmt.Sprintf("perf-peer-%d", i)
|
||||
port := 0
|
||||
c, err := embed.New(embed.Options{
|
||||
DeviceName: name,
|
||||
SetupKey: *setupKey,
|
||||
ManagementURL: *managementURL,
|
||||
WireguardPort: &port,
|
||||
LogLevel: *logLevel,
|
||||
LogOutput: io.Discard,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error creating peer %s: %v\n", name, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
peers[i] = peerInfo{client: c, name: name}
|
||||
fmt.Printf(" Created %s\n", name)
|
||||
}
|
||||
|
||||
// Phase 2: Start peers in parallel
|
||||
fmt.Println("\n--- Phase 2: Starting peers ---")
|
||||
startTime := time.Now()
|
||||
var wg sync.WaitGroup
|
||||
startErrors := make([]error, *numPeers)
|
||||
|
||||
for i := range peers {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), startTimeout)
|
||||
defer cancel()
|
||||
t := time.Now()
|
||||
if err := peers[idx].client.Start(ctx); err != nil {
|
||||
startErrors[idx] = err
|
||||
return
|
||||
}
|
||||
fmt.Printf(" %s started in %s\n", peers[idx].name, time.Since(t).Round(time.Millisecond))
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Check for start errors
|
||||
var failed bool
|
||||
for i, err := range startErrors {
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, " Error starting %s: %v\n", peers[i].name, err)
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
cleanup(peers)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf(" All peers started in %s\n", time.Since(startTime).Round(time.Millisecond))
|
||||
|
||||
// Get tunnel IPs
|
||||
for i := range peers {
|
||||
status, err := peers[i].client.Status()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, " Error getting status for %s: %v\n", peers[i].name, err)
|
||||
cleanup(peers)
|
||||
os.Exit(1)
|
||||
}
|
||||
ip := status.LocalPeerState.IP
|
||||
// Strip CIDR suffix if present (e.g. "100.64.0.1/16" -> "100.64.0.1")
|
||||
if idx := strings.Index(ip, "/"); idx != -1 {
|
||||
ip = ip[:idx]
|
||||
}
|
||||
peers[i].tunnelIP = ip
|
||||
fmt.Printf(" %s -> %s\n", peers[i].name, peers[i].tunnelIP)
|
||||
}
|
||||
|
||||
// Phase 3: Wait for connections
|
||||
fmt.Println("\n--- Phase 3: Waiting for peer connections ---")
|
||||
connStart := time.Now()
|
||||
expectedPeers := *numPeers - 1
|
||||
deadline := time.After(connectTimeout)
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
allConnected := false
|
||||
waitLoop:
|
||||
for {
|
||||
select {
|
||||
case <-deadline:
|
||||
fmt.Fprintf(os.Stderr, " Timeout waiting for connections after %s\n", connectTimeout)
|
||||
printConnectionStatus(peers)
|
||||
cleanup(peers)
|
||||
os.Exit(1)
|
||||
case <-ticker.C:
|
||||
allConnected = true
|
||||
for i := range peers {
|
||||
connected := countConnectedPeers(peers[i].client)
|
||||
if connected < expectedPeers {
|
||||
allConnected = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allConnected {
|
||||
break waitLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf(" All peers connected in %s\n", time.Since(connStart).Round(time.Millisecond))
|
||||
printConnectionStatus(peers)
|
||||
|
||||
// Phase 4: Traffic test
|
||||
fmt.Printf("\n--- Phase 4: Traffic test (%s) ---\n", *duration)
|
||||
|
||||
// Start echo listeners on all peers
|
||||
listeners := make([]net.PacketConn, *numPeers)
|
||||
for i := range peers {
|
||||
conn, err := peers[i].client.ListenUDP(fmt.Sprintf(":%d", echoPort))
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, " Error creating listener on %s: %v\n", peers[i].name, err)
|
||||
cleanup(peers)
|
||||
os.Exit(1)
|
||||
}
|
||||
listeners[i] = conn
|
||||
go echoServer(conn, *packetSize)
|
||||
fmt.Printf(" Echo listener started on %s:%d\n", peers[i].tunnelIP, echoPort)
|
||||
}
|
||||
|
||||
// Run traffic between all pairs (i < j)
|
||||
var statsMu sync.Mutex
|
||||
var allStats []pairStats
|
||||
|
||||
var trafficWg sync.WaitGroup
|
||||
for i := 0; i < *numPeers; i++ {
|
||||
for j := i + 1; j < *numPeers; j++ {
|
||||
trafficWg.Add(1)
|
||||
go func(from, to int) {
|
||||
defer trafficWg.Done()
|
||||
stats := runTraffic(peers[from].client, peers[from].name, peers[to].tunnelIP, peers[to].name, *duration, *packetSize)
|
||||
statsMu.Lock()
|
||||
allStats = append(allStats, stats)
|
||||
statsMu.Unlock()
|
||||
}(i, j)
|
||||
}
|
||||
}
|
||||
trafficWg.Wait()
|
||||
|
||||
// Close listeners
|
||||
for _, l := range listeners {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 5: Report
|
||||
fmt.Println("\n--- Phase 5: Results ---")
|
||||
printReport(allStats)
|
||||
|
||||
// Cleanup
|
||||
fmt.Println("\n--- Cleanup ---")
|
||||
cleanup(peers)
|
||||
fmt.Println("Done.")
|
||||
}
|
||||
|
||||
func countConnectedPeers(c *embed.Client) int {
|
||||
status, err := c.Status()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
count := 0
|
||||
for _, p := range status.Peers {
|
||||
if p.ConnStatus == embed.PeerStatusConnected {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func printConnectionStatus(peers []peerInfo) {
|
||||
for i := range peers {
|
||||
status, err := peers[i].client.Status()
|
||||
if err != nil {
|
||||
fmt.Printf(" %s: error getting status: %v\n", peers[i].name, err)
|
||||
continue
|
||||
}
|
||||
connected := 0
|
||||
relayed := 0
|
||||
for _, p := range status.Peers {
|
||||
if p.ConnStatus == embed.PeerStatusConnected {
|
||||
connected++
|
||||
if p.Relayed {
|
||||
relayed++
|
||||
}
|
||||
}
|
||||
}
|
||||
connType := "direct"
|
||||
if relayed > 0 {
|
||||
connType = fmt.Sprintf("%d direct, %d relayed", connected-relayed, relayed)
|
||||
}
|
||||
fmt.Printf(" %s: %d/%d connected (%s)\n", peers[i].name, connected, len(status.Peers), connType)
|
||||
}
|
||||
}
|
||||
|
||||
func echoServer(conn net.PacketConn, maxSize int) {
|
||||
buf := make([]byte, maxSize+100)
|
||||
for {
|
||||
n, addr, err := conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = conn.WriteTo(buf[:n], addr)
|
||||
}
|
||||
}
|
||||
|
||||
func runTraffic(client *embed.Client, fromName, toIP, toName string, duration time.Duration, packetSize int) pairStats {
|
||||
stats := pairStats{
|
||||
from: fromName,
|
||||
to: toName,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), duration+10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
conn, err := client.Dial(ctx, "udp", fmt.Sprintf("%s:%d", toIP, echoPort))
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, " Error dialing %s -> %s: %v\n", fromName, toName, err)
|
||||
return stats
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
deadline := time.Now().Add(duration)
|
||||
buf := make([]byte, packetSize)
|
||||
recvBuf := make([]byte, packetSize+100)
|
||||
var seq uint64
|
||||
|
||||
for time.Now().Before(deadline) {
|
||||
seq++
|
||||
// Encode timestamp and sequence number
|
||||
binary.BigEndian.PutUint64(buf[0:8], uint64(time.Now().UnixNano()))
|
||||
binary.BigEndian.PutUint64(buf[8:16], seq)
|
||||
|
||||
stats.sent++
|
||||
conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
_, err := conn.Write(buf)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, " Error sending packet to %s: %v\n", toName, err)
|
||||
stats.lost++
|
||||
continue
|
||||
}
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
n, err := conn.Read(recvBuf)
|
||||
if err != nil {
|
||||
stats.lost++
|
||||
continue
|
||||
}
|
||||
|
||||
if n >= 8 {
|
||||
sentNano := binary.BigEndian.Uint64(recvBuf[0:8])
|
||||
rtt := time.Since(time.Unix(0, int64(sentNano)))
|
||||
stats.received++
|
||||
stats.rtts = append(stats.rtts, rtt)
|
||||
} else {
|
||||
stats.received++
|
||||
}
|
||||
|
||||
// Small sleep to avoid flooding
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
func printReport(allStats []pairStats) {
|
||||
if len(allStats) == 0 {
|
||||
fmt.Println(" No traffic data collected.")
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf(" %-30s %8s %8s %8s %8s %10s %10s %10s\n",
|
||||
"Pair", "Sent", "Recv", "Lost", "Loss%", "Avg RTT", "Min RTT", "Max RTT")
|
||||
fmt.Println(" " + strings.Repeat("-", 108))
|
||||
|
||||
var totalSent, totalRecv, totalLost int64
|
||||
var totalRTTs []time.Duration
|
||||
|
||||
for _, s := range allStats {
|
||||
avg, min, max, loss := s.summary()
|
||||
pair := fmt.Sprintf("%s -> %s", s.from, s.to)
|
||||
fmt.Printf(" %-30s %8d %8d %8d %7.1f%% %10s %10s %10s\n",
|
||||
pair, s.sent, s.received, s.lost, loss,
|
||||
avg.Round(time.Microsecond), min.Round(time.Microsecond), max.Round(time.Microsecond))
|
||||
totalSent += s.sent
|
||||
totalRecv += s.received
|
||||
totalLost += s.lost
|
||||
totalRTTs = append(totalRTTs, s.rtts...)
|
||||
}
|
||||
|
||||
fmt.Println(" " + strings.Repeat("-", 108))
|
||||
|
||||
// Overall summary
|
||||
var overallLoss float64
|
||||
if totalSent > 0 {
|
||||
overallLoss = float64(totalLost) / float64(totalSent) * 100
|
||||
}
|
||||
|
||||
var avgRTT, minRTT, maxRTT time.Duration
|
||||
if len(totalRTTs) > 0 {
|
||||
minRTT = totalRTTs[0]
|
||||
maxRTT = totalRTTs[0]
|
||||
var total time.Duration
|
||||
for _, rtt := range totalRTTs {
|
||||
total += rtt
|
||||
if rtt < minRTT {
|
||||
minRTT = rtt
|
||||
}
|
||||
if rtt > maxRTT {
|
||||
maxRTT = rtt
|
||||
}
|
||||
}
|
||||
avgRTT = total / time.Duration(len(totalRTTs))
|
||||
}
|
||||
|
||||
fmt.Printf(" %-30s %8d %8d %8d %7.1f%% %10s %10s %10s\n",
|
||||
"TOTAL", totalSent, totalRecv, totalLost, overallLoss,
|
||||
avgRTT.Round(time.Microsecond), minRTT.Round(time.Microsecond), maxRTT.Round(time.Microsecond))
|
||||
|
||||
// Extra stats
|
||||
if len(totalRTTs) > 0 {
|
||||
fmt.Println()
|
||||
var sumSq float64
|
||||
avgNs := float64(avgRTT.Nanoseconds())
|
||||
for _, rtt := range totalRTTs {
|
||||
diff := float64(rtt.Nanoseconds()) - avgNs
|
||||
sumSq += diff * diff
|
||||
}
|
||||
stddev := time.Duration(math.Sqrt(sumSq / float64(len(totalRTTs))))
|
||||
|
||||
fmt.Printf(" RTT stddev: %s\n", stddev.Round(time.Microsecond))
|
||||
fmt.Printf(" Pairs tested: %d\n", len(allStats))
|
||||
}
|
||||
}
|
||||
|
||||
func cleanup(peers []peerInfo) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), stopTimeout)
|
||||
defer cancel()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := range peers {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
if err := peers[idx].client.Stop(ctx); err != nil {
|
||||
fmt.Fprintf(os.Stderr, " Error stopping %s: %v\n", peers[idx].name, err)
|
||||
} else {
|
||||
fmt.Printf(" Stopped %s\n", peers[idx].name)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
BINARY="$SCRIPT_DIR/perftest"
|
||||
|
||||
# Defaults
|
||||
MANAGEMENT_URL="${MANAGEMENT_URL:-}"
|
||||
SETUP_KEY="${SETUP_KEY:-}"
|
||||
PEERS="${PEERS:-5}"
|
||||
DURATION="${DURATION:-30s}"
|
||||
PACKET_SIZE="${PACKET_SIZE:-512}"
|
||||
FORCE_RELAY="${FORCE_RELAY:-false}"
|
||||
LOG_LEVEL="${LOG_LEVEL:-panic}"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: MANAGEMENT_URL=... SETUP_KEY=... $0 [options]
|
||||
|
||||
Environment variables (or flags):
|
||||
MANAGEMENT_URL Management server URL (required)
|
||||
SETUP_KEY Reusable setup key (required). Use ephemeral.
|
||||
PEERS Number of peers (default: 5)
|
||||
DURATION Traffic test duration (default: 30s)
|
||||
PACKET_SIZE UDP packet size in bytes (default: 512)
|
||||
FORCE_RELAY Force relay mode (default: false)
|
||||
LOG_LEVEL Client log level (default: panic)
|
||||
|
||||
All extra arguments are passed directly to the binary.
|
||||
EOF
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [[ -z "$MANAGEMENT_URL" || -z "$SETUP_KEY" ]]; then
|
||||
echo "Error: MANAGEMENT_URL and SETUP_KEY must be set"
|
||||
echo
|
||||
usage
|
||||
fi
|
||||
|
||||
# Build
|
||||
echo "Building perftest..."
|
||||
cd "$SCRIPT_DIR"
|
||||
go build -o "$BINARY" .
|
||||
echo "Build OK: $BINARY"
|
||||
echo
|
||||
|
||||
# Run
|
||||
ARGS=(
|
||||
--management-url "$MANAGEMENT_URL"
|
||||
--setup-key "$SETUP_KEY"
|
||||
--peers "$PEERS"
|
||||
--duration "$DURATION"
|
||||
--packet-size "$PACKET_SIZE"
|
||||
--log-level "$LOG_LEVEL"
|
||||
)
|
||||
|
||||
if [[ "$FORCE_RELAY" == "true" ]]; then
|
||||
ARGS+=(--force-relay)
|
||||
fi
|
||||
|
||||
exec "$BINARY" "${ARGS[@]}" "$@"
|
||||
@@ -83,7 +83,6 @@ require (
|
||||
github.com/pion/stun/v3 v3.1.0
|
||||
github.com/pion/transport/v3 v3.1.1
|
||||
github.com/pion/turn/v3 v3.0.1
|
||||
github.com/pires/go-proxyproto v0.11.0
|
||||
github.com/pkg/sftp v1.13.9
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/quic-go/quic-go v0.55.0
|
||||
|
||||
@@ -474,8 +474,6 @@ github.com/pion/turn/v3 v3.0.1 h1:wLi7BTQr6/Q20R0vt/lHbjv6y4GChFtC33nkYbasoT8=
|
||||
github.com/pion/turn/v3 v3.0.1/go.mod h1:MrJDKgqryDyWy1/4NT9TWfXWGMC7UHT6pJIv1+gMeNE=
|
||||
github.com/pion/turn/v4 v4.1.1 h1:9UnY2HB99tpDyz3cVVZguSxcqkJ1DsTSZ+8TGruh4fc=
|
||||
github.com/pion/turn/v4 v4.1.1/go.mod h1:2123tHk1O++vmjI5VSD0awT50NywDAq5A2NNNU4Jjs8=
|
||||
github.com/pires/go-proxyproto v0.11.0 h1:gUQpS85X/VJMdUsYyEgyn59uLJvGqPhJV5YvG68wXH4=
|
||||
github.com/pires/go-proxyproto v0.11.0/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
|
||||
@@ -169,8 +169,7 @@ read_proxy_docker_network() {
|
||||
read_enable_proxy() {
|
||||
echo "" > /dev/stderr
|
||||
echo "Do you want to enable the NetBird Proxy service?" > /dev/stderr
|
||||
echo "The proxy allows you to selectively expose internal NetBird network resources" > /dev/stderr
|
||||
echo "to the internet. You control which resources are exposed through the dashboard." > /dev/stderr
|
||||
echo "The proxy exposes internal NetBird network resources to the internet." > /dev/stderr
|
||||
echo -n "Enable proxy? [y/N]: " > /dev/stderr
|
||||
read -r CHOICE < /dev/tty
|
||||
|
||||
@@ -182,44 +181,6 @@ read_enable_proxy() {
|
||||
return 0
|
||||
}
|
||||
|
||||
read_proxy_domain() {
|
||||
local suggested_proxy="proxy.${BASE_DOMAIN}"
|
||||
|
||||
echo "" > /dev/stderr
|
||||
echo "NOTE: The proxy domain must be different from the management domain ($NETBIRD_DOMAIN)" > /dev/stderr
|
||||
echo "to avoid TLS certificate conflicts." > /dev/stderr
|
||||
echo "" > /dev/stderr
|
||||
echo "You also need to add a wildcard DNS record for the proxy domain," > /dev/stderr
|
||||
echo "e.g. *.${suggested_proxy} pointing to the same server domain as $NETBIRD_DOMAIN with a CNAME record." > /dev/stderr
|
||||
echo "" > /dev/stderr
|
||||
echo -n "Enter the domain for the NetBird Proxy (e.g. ${suggested_proxy}): " > /dev/stderr
|
||||
read -r READ_PROXY_DOMAIN < /dev/tty
|
||||
|
||||
if [[ -z "$READ_PROXY_DOMAIN" ]]; then
|
||||
echo "The proxy domain cannot be empty." > /dev/stderr
|
||||
read_proxy_domain
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$READ_PROXY_DOMAIN" == "$NETBIRD_DOMAIN" ]]; then
|
||||
echo "" > /dev/stderr
|
||||
echo "WARNING: The proxy domain cannot be the same as the management domain ($NETBIRD_DOMAIN)." > /dev/stderr
|
||||
read_proxy_domain
|
||||
return
|
||||
fi
|
||||
|
||||
echo ${READ_PROXY_DOMAIN} | grep ${NETBIRD_DOMAIN} > /dev/null
|
||||
if [[ $? -eq 0 ]]; then
|
||||
echo "" > /dev/stderr
|
||||
echo "WARNING: The proxy domain cannot be a subdomain of the management domain ($NETBIRD_DOMAIN)." > /dev/stderr
|
||||
read_proxy_domain
|
||||
return
|
||||
fi
|
||||
|
||||
echo "$READ_PROXY_DOMAIN"
|
||||
return 0
|
||||
}
|
||||
|
||||
read_traefik_acme_email() {
|
||||
echo "" > /dev/stderr
|
||||
echo "Enter your email for Let's Encrypt certificate notifications." > /dev/stderr
|
||||
@@ -313,10 +274,9 @@ initialize_default_values() {
|
||||
NETBIRD_STUN_PORT=3478
|
||||
|
||||
# Docker images
|
||||
DASHBOARD_IMAGE="netbirdio/dashboard:latest"
|
||||
DASHBOARD_IMAGE="netbirdio/dashboard:pr-552"
|
||||
# Combined server replaces separate signal, relay, and management containers
|
||||
NETBIRD_SERVER_IMAGE="netbirdio/netbird-server:latest"
|
||||
NETBIRD_PROXY_IMAGE="netbirdio/reverse-proxy:latest"
|
||||
|
||||
# Reverse proxy configuration
|
||||
REVERSE_PROXY_TYPE="0"
|
||||
@@ -329,12 +289,8 @@ initialize_default_values() {
|
||||
BIND_LOCALHOST_ONLY="true"
|
||||
EXTERNAL_PROXY_NETWORK=""
|
||||
|
||||
# Traefik static IP within the internal bridge network
|
||||
TRAEFIK_IP="172.30.0.10"
|
||||
|
||||
# NetBird Proxy configuration
|
||||
ENABLE_PROXY="false"
|
||||
PROXY_DOMAIN=""
|
||||
PROXY_TOKEN=""
|
||||
return 0
|
||||
}
|
||||
@@ -346,12 +302,10 @@ configure_domain() {
|
||||
|
||||
if [[ "$NETBIRD_DOMAIN" == "use-ip" ]]; then
|
||||
NETBIRD_DOMAIN=$(get_main_ip_address)
|
||||
BASE_DOMAIN=$NETBIRD_DOMAIN
|
||||
else
|
||||
NETBIRD_PORT=443
|
||||
NETBIRD_HTTP_PROTOCOL="https"
|
||||
NETBIRD_RELAY_PROTO="rels"
|
||||
BASE_DOMAIN=$(echo $NETBIRD_DOMAIN | sed -E 's/^[^.]+\.//')
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
@@ -364,9 +318,6 @@ configure_reverse_proxy() {
|
||||
if [[ "$REVERSE_PROXY_TYPE" == "0" ]]; then
|
||||
TRAEFIK_ACME_EMAIL=$(read_traefik_acme_email)
|
||||
ENABLE_PROXY=$(read_enable_proxy)
|
||||
if [[ "$ENABLE_PROXY" == "true" ]]; then
|
||||
PROXY_DOMAIN=$(read_proxy_domain)
|
||||
fi
|
||||
fi
|
||||
|
||||
# Handle external Traefik-specific prompts (option 1)
|
||||
@@ -396,7 +347,7 @@ check_existing_installation() {
|
||||
echo "Generated files already exist, if you want to reinitialize the environment, please remove them first."
|
||||
echo "You can use the following commands:"
|
||||
echo " $DOCKER_COMPOSE_COMMAND down --volumes # to remove all containers and volumes"
|
||||
echo " rm -f docker-compose.yml dashboard.env config.yaml proxy.env traefik-dynamic.yaml nginx-netbird.conf caddyfile-netbird.txt npm-advanced-config.txt"
|
||||
echo " rm -f docker-compose.yml dashboard.env config.yaml proxy.env nginx-netbird.conf caddyfile-netbird.txt npm-advanced-config.txt"
|
||||
echo "Be aware that this will remove all data from the database, and you will have to reconfigure the dashboard."
|
||||
exit 1
|
||||
fi
|
||||
@@ -415,8 +366,6 @@ generate_configuration_files() {
|
||||
# This will be overwritten with the actual token after netbird-server starts
|
||||
echo "# Placeholder - will be updated with token after netbird-server starts" > proxy.env
|
||||
echo "NB_PROXY_TOKEN=placeholder" >> proxy.env
|
||||
# TCP ServersTransport for PROXY protocol v2 to the proxy backend
|
||||
render_traefik_dynamic > traefik-dynamic.yaml
|
||||
fi
|
||||
;;
|
||||
1)
|
||||
@@ -564,24 +513,21 @@ init_environment() {
|
||||
############################################
|
||||
|
||||
render_docker_compose_traefik_builtin() {
|
||||
# Generate proxy service section and Traefik dynamic config if enabled
|
||||
# Generate proxy service section if enabled
|
||||
local proxy_service=""
|
||||
local proxy_volumes=""
|
||||
local traefik_file_provider=""
|
||||
local traefik_dynamic_volume=""
|
||||
if [[ "$ENABLE_PROXY" == "true" ]]; then
|
||||
traefik_file_provider=' - "--providers.file.filename=/etc/traefik/dynamic.yaml"'
|
||||
traefik_dynamic_volume=" - ./traefik-dynamic.yaml:/etc/traefik/dynamic.yaml:ro"
|
||||
proxy_service="
|
||||
# NetBird Proxy - exposes internal resources to the internet
|
||||
proxy:
|
||||
image: $NETBIRD_PROXY_IMAGE
|
||||
build:
|
||||
context: ../
|
||||
dockerfile: proxy/Dockerfile
|
||||
pull_policy: build
|
||||
container_name: netbird-proxy
|
||||
# Hairpin NAT fix: route domain back to traefik's static IP within Docker
|
||||
extra_hosts:
|
||||
- \"$NETBIRD_DOMAIN:$TRAEFIK_IP\"
|
||||
ports:
|
||||
- 51820:51820/udp
|
||||
- \"$NETBIRD_DOMAIN:172.30.0.10\"
|
||||
restart: unless-stopped
|
||||
networks: [netbird]
|
||||
depends_on:
|
||||
@@ -599,7 +545,6 @@ render_docker_compose_traefik_builtin() {
|
||||
- traefik.tcp.routers.proxy-passthrough.service=proxy-tls
|
||||
- traefik.tcp.routers.proxy-passthrough.priority=1
|
||||
- traefik.tcp.services.proxy-tls.loadbalancer.server.port=8443
|
||||
- traefik.tcp.services.proxy-tls.loadbalancer.serverstransport=pp-v2@file
|
||||
logging:
|
||||
driver: \"json-file\"
|
||||
options:
|
||||
@@ -619,7 +564,7 @@ services:
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
netbird:
|
||||
ipv4_address: $TRAEFIK_IP
|
||||
ipv4_address: 172.30.0.10
|
||||
command:
|
||||
# Logging
|
||||
- "--log.level=INFO"
|
||||
@@ -646,14 +591,12 @@ services:
|
||||
# gRPC transport settings
|
||||
- "--serverstransport.forwardingtimeouts.responseheadertimeout=0s"
|
||||
- "--serverstransport.forwardingtimeouts.idleconntimeout=0s"
|
||||
$traefik_file_provider
|
||||
ports:
|
||||
- '443:443'
|
||||
- '80:80'
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- netbird_traefik_letsencrypt:/letsencrypt
|
||||
$traefik_dynamic_volume
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
@@ -685,7 +628,11 @@ $traefik_dynamic_volume
|
||||
|
||||
# Combined server (Management + Signal + Relay + STUN)
|
||||
netbird-server:
|
||||
image: $NETBIRD_SERVER_IMAGE
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: combined/Dockerfile.multistage
|
||||
pull_policy: build
|
||||
#image: $NETBIRD_SERVER_IMAGE
|
||||
container_name: netbird-server
|
||||
restart: unless-stopped
|
||||
networks: [netbird]
|
||||
@@ -763,10 +710,6 @@ server:
|
||||
cliRedirectURIs:
|
||||
- "http://localhost:53000/"
|
||||
|
||||
reverseProxy:
|
||||
trustedHTTPProxies:
|
||||
- "$TRAEFIK_IP/32"
|
||||
|
||||
store:
|
||||
engine: "sqlite"
|
||||
encryptionKey: "$DATASTORE_ENCRYPTION_KEY"
|
||||
@@ -796,17 +739,6 @@ EOF
|
||||
return 0
|
||||
}
|
||||
|
||||
render_traefik_dynamic() {
|
||||
cat <<'EOF'
|
||||
tcp:
|
||||
serversTransports:
|
||||
pp-v2:
|
||||
proxyProtocol:
|
||||
version: 2
|
||||
EOF
|
||||
return 0
|
||||
}
|
||||
|
||||
render_proxy_env() {
|
||||
cat <<EOF
|
||||
# NetBird Proxy Configuration
|
||||
@@ -816,7 +748,7 @@ NB_PROXY_MANAGEMENT_ADDRESS=http://netbird-server:80
|
||||
# Allow insecure gRPC connection to management (required for internal Docker network)
|
||||
NB_PROXY_ALLOW_INSECURE=true
|
||||
# Public URL where this proxy is reachable (used for cluster registration)
|
||||
NB_PROXY_DOMAIN=$PROXY_DOMAIN
|
||||
NB_PROXY_DOMAIN=$NETBIRD_DOMAIN
|
||||
NB_PROXY_ADDRESS=:8443
|
||||
NB_PROXY_TOKEN=$PROXY_TOKEN
|
||||
NB_PROXY_CERTIFICATE_DIRECTORY=/certs
|
||||
@@ -826,10 +758,6 @@ NB_PROXY_OIDC_CLIENT_ID=netbird-proxy
|
||||
NB_PROXY_OIDC_ENDPOINT=$NETBIRD_HTTP_PROTOCOL://$NETBIRD_DOMAIN/oauth2
|
||||
NB_PROXY_OIDC_SCOPES=openid,profile,email
|
||||
NB_PROXY_FORWARDED_PROTO=https
|
||||
# Enable PROXY protocol to preserve client IPs through L4 proxies (Traefik TCP passthrough)
|
||||
NB_PROXY_PROXY_PROTOCOL=true
|
||||
# Trust Traefik's IP for PROXY protocol headers
|
||||
NB_PROXY_TRUSTED_PROXIES=$TRAEFIK_IP
|
||||
EOF
|
||||
return 0
|
||||
}
|
||||
@@ -1188,30 +1116,23 @@ print_builtin_traefik_instructions() {
|
||||
echo " NETBIRD SETUP COMPLETE"
|
||||
echo "$MSG_SEPARATOR"
|
||||
echo ""
|
||||
echo "You can access the NetBird dashboard at:"
|
||||
echo " $NETBIRD_HTTP_PROTOCOL://$NETBIRD_DOMAIN"
|
||||
echo ""
|
||||
echo "You can access the NetBird dashboard at $NETBIRD_HTTP_PROTOCOL://$NETBIRD_DOMAIN"
|
||||
echo "Follow the onboarding steps to set up your NetBird instance."
|
||||
echo ""
|
||||
echo "Traefik is handling TLS certificates automatically via Let's Encrypt."
|
||||
echo "If you see certificate warnings, wait a moment for certificate issuance to complete."
|
||||
echo ""
|
||||
echo "Open ports:"
|
||||
echo " - 443/tcp (HTTPS - all NetBird services)"
|
||||
echo " - 80/tcp (HTTP - redirects to HTTPS)"
|
||||
echo " - $NETBIRD_STUN_PORT/udp (STUN - required for NAT traversal)"
|
||||
echo " - 443/tcp (HTTPS - all NetBird services)"
|
||||
echo " - 80/tcp (HTTP - redirects to HTTPS)"
|
||||
echo " - $NETBIRD_STUN_PORT/udp (STUN - required for NAT traversal)"
|
||||
if [[ "$ENABLE_PROXY" == "true" ]]; then
|
||||
echo " - 51820/udp (WIREGUARD - (optional) for P2P proxy connections)"
|
||||
echo ""
|
||||
echo "NetBird Proxy:"
|
||||
echo " The proxy service is enabled and running."
|
||||
echo " Any domain NOT matching $NETBIRD_DOMAIN will be passed through to the proxy."
|
||||
echo " The proxy handles its own TLS certificates via ACME TLS-ALPN-01 challenge."
|
||||
echo " Point your proxy domain to this server's domain address like in the examples below:"
|
||||
echo ""
|
||||
echo " $PROXY_DOMAIN CNAME $NETBIRD_DOMAIN"
|
||||
echo " *.$PROXY_DOMAIN CNAME $NETBIRD_DOMAIN"
|
||||
echo ""
|
||||
echo " Point your proxy domains (CNAMEs) to this server's IP address."
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -473,6 +473,8 @@ func (m *managerImpl) ReloadAllServicesForAccount(ctx context.Context, accountID
|
||||
m.proxyGRPCServer.SendServiceUpdateToCluster(service.ToProtoMapping(reverseproxy.Update, "", m.proxyGRPCServer.GetOIDCValidationConfig()), service.ProxyCluster)
|
||||
}
|
||||
|
||||
m.accountManager.UpdateAccountPeers(ctx, accountID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -15,14 +15,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/netbirdio/netbird/shared/management/domain"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/oauth2"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/domain"
|
||||
|
||||
"github.com/netbirdio/netbird/management/internals/modules/peers"
|
||||
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy"
|
||||
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy/accesslogs"
|
||||
@@ -520,11 +519,61 @@ func (s *ProxyServiceServer) Authenticate(ctx context.Context, req *proto.Authen
|
||||
return nil, status.Errorf(codes.FailedPrecondition, "get service from store: %v", err)
|
||||
}
|
||||
|
||||
authenticated, userId, method := s.authenticateRequest(ctx, req, service)
|
||||
var authenticated bool
|
||||
var userId string
|
||||
var method proxyauth.Method
|
||||
switch v := req.GetRequest().(type) {
|
||||
case *proto.AuthenticateRequest_Pin:
|
||||
auth := service.Auth.PinAuth
|
||||
if auth == nil || !auth.Enabled {
|
||||
log.WithContext(ctx).Debugf("PIN authentication attempted but not enabled for service %s", req.GetId())
|
||||
break
|
||||
}
|
||||
err = argon2id.Verify(v.Pin.GetPin(), auth.Pin)
|
||||
if err != nil {
|
||||
if errors.Is(err, argon2id.ErrMismatchedHashAndPassword) {
|
||||
log.WithContext(ctx).Tracef("PIN authentication failed: invalid PIN")
|
||||
} else {
|
||||
log.WithContext(ctx).Errorf("PIN authentication error: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
authenticated = true
|
||||
userId = "pin-user"
|
||||
method = proxyauth.MethodPIN
|
||||
case *proto.AuthenticateRequest_Password:
|
||||
auth := service.Auth.PasswordAuth
|
||||
if auth == nil || !auth.Enabled {
|
||||
log.WithContext(ctx).Debugf("password authentication attempted but not enabled for service %s", req.GetId())
|
||||
break
|
||||
}
|
||||
err = argon2id.Verify(v.Password.GetPassword(), auth.Password)
|
||||
if err != nil {
|
||||
if errors.Is(err, argon2id.ErrMismatchedHashAndPassword) {
|
||||
log.WithContext(ctx).Tracef("Password authentication failed: invalid password")
|
||||
} else {
|
||||
log.WithContext(ctx).Errorf("Password authentication error: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
authenticated = true
|
||||
userId = "password-user"
|
||||
method = proxyauth.MethodPassword
|
||||
}
|
||||
|
||||
token, err := s.generateSessionToken(ctx, authenticated, service, userId, method)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
var token string
|
||||
if authenticated && service.SessionPrivateKey != "" {
|
||||
token, err = sessionkey.SignToken(
|
||||
service.SessionPrivateKey,
|
||||
userId,
|
||||
service.Domain,
|
||||
method,
|
||||
proxyauth.DefaultSessionExpiry,
|
||||
)
|
||||
if err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("failed to sign session token")
|
||||
return nil, status.Errorf(codes.Internal, "sign session token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &proto.AuthenticateResponse{
|
||||
@@ -533,73 +582,6 @@ func (s *ProxyServiceServer) Authenticate(ctx context.Context, req *proto.Authen
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ProxyServiceServer) authenticateRequest(ctx context.Context, req *proto.AuthenticateRequest, service *reverseproxy.Service) (bool, string, proxyauth.Method) {
|
||||
switch v := req.GetRequest().(type) {
|
||||
case *proto.AuthenticateRequest_Pin:
|
||||
return s.authenticatePIN(ctx, req.GetId(), v, service.Auth.PinAuth)
|
||||
case *proto.AuthenticateRequest_Password:
|
||||
return s.authenticatePassword(ctx, req.GetId(), v, service.Auth.PasswordAuth)
|
||||
default:
|
||||
return false, "", ""
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProxyServiceServer) authenticatePIN(ctx context.Context, serviceID string, req *proto.AuthenticateRequest_Pin, auth *reverseproxy.PINAuthConfig) (bool, string, proxyauth.Method) {
|
||||
if auth == nil || !auth.Enabled {
|
||||
log.WithContext(ctx).Debugf("PIN authentication attempted but not enabled for service %s", serviceID)
|
||||
return false, "", ""
|
||||
}
|
||||
|
||||
if err := argon2id.Verify(req.Pin.GetPin(), auth.Pin); err != nil {
|
||||
s.logAuthenticationError(ctx, err, "PIN")
|
||||
return false, "", ""
|
||||
}
|
||||
|
||||
return true, "pin-user", proxyauth.MethodPIN
|
||||
}
|
||||
|
||||
func (s *ProxyServiceServer) authenticatePassword(ctx context.Context, serviceID string, req *proto.AuthenticateRequest_Password, auth *reverseproxy.PasswordAuthConfig) (bool, string, proxyauth.Method) {
|
||||
if auth == nil || !auth.Enabled {
|
||||
log.WithContext(ctx).Debugf("password authentication attempted but not enabled for service %s", serviceID)
|
||||
return false, "", ""
|
||||
}
|
||||
|
||||
if err := argon2id.Verify(req.Password.GetPassword(), auth.Password); err != nil {
|
||||
s.logAuthenticationError(ctx, err, "Password")
|
||||
return false, "", ""
|
||||
}
|
||||
|
||||
return true, "password-user", proxyauth.MethodPassword
|
||||
}
|
||||
|
||||
func (s *ProxyServiceServer) logAuthenticationError(ctx context.Context, err error, authType string) {
|
||||
if errors.Is(err, argon2id.ErrMismatchedHashAndPassword) {
|
||||
log.WithContext(ctx).Tracef("%s authentication failed: invalid credentials", authType)
|
||||
} else {
|
||||
log.WithContext(ctx).Errorf("%s authentication error: %v", authType, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProxyServiceServer) generateSessionToken(ctx context.Context, authenticated bool, service *reverseproxy.Service, userId string, method proxyauth.Method) (string, error) {
|
||||
if !authenticated || service.SessionPrivateKey == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
token, err := sessionkey.SignToken(
|
||||
service.SessionPrivateKey,
|
||||
userId,
|
||||
service.Domain,
|
||||
method,
|
||||
proxyauth.DefaultSessionExpiry,
|
||||
)
|
||||
if err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("failed to sign session token")
|
||||
return "", status.Errorf(codes.Internal, "sign session token: %v", err)
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// SendStatusUpdate handles status updates from proxy clients
|
||||
func (s *ProxyServiceServer) SendStatusUpdate(ctx context.Context, req *proto.SendStatusUpdateRequest) (*proto.SendStatusUpdateResponse, error) {
|
||||
accountID := req.GetAccountId()
|
||||
|
||||
@@ -297,7 +297,6 @@ func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, acco
|
||||
var oldSettings *types.Settings
|
||||
var updateAccountPeers bool
|
||||
var groupChangesAffectPeers bool
|
||||
var reloadReverseProxy bool
|
||||
|
||||
err = am.Store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
|
||||
var groupsUpdated bool
|
||||
@@ -328,7 +327,9 @@ func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, acco
|
||||
if err = am.reallocateAccountPeerIPs(ctx, transaction, accountID, newSettings.NetworkRange); err != nil {
|
||||
return err
|
||||
}
|
||||
reloadReverseProxy = true
|
||||
if err = am.reverseProxyManager.ReloadAllServicesForAccount(ctx, accountID); err != nil {
|
||||
log.WithContext(ctx).Warnf("failed to reload all services for account %s: %v", accountID, err)
|
||||
}
|
||||
updateAccountPeers = true
|
||||
}
|
||||
|
||||
@@ -393,11 +394,6 @@ func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, acco
|
||||
}
|
||||
am.StoreEvent(ctx, userID, accountID, accountID, activity.AccountNetworkRangeUpdated, eventMeta)
|
||||
}
|
||||
if reloadReverseProxy {
|
||||
if err = am.reverseProxyManager.ReloadAllServicesForAccount(ctx, accountID); err != nil {
|
||||
log.WithContext(ctx).Warnf("failed to reload all services for account %s: %v", accountID, err)
|
||||
}
|
||||
}
|
||||
|
||||
if updateAccountPeers || extraSettingsChanged || groupChangesAffectPeers {
|
||||
go am.UpdateAccountPeers(ctx, accountID)
|
||||
|
||||
@@ -3918,36 +3918,3 @@ func TestAddNewUserToDomainAccountWithoutApproval(t *testing.T) {
|
||||
assert.False(t, user.PendingApproval, "User should not be pending approval")
|
||||
assert.Equal(t, existingAccountID, user.AccountID)
|
||||
}
|
||||
|
||||
// TestDefaultAccountManager_UpdateAccountSettings_NetworkRangeChange verifies that
|
||||
// changing NetworkRange via UpdateAccountSettings does not deadlock.
|
||||
// The deadlock occurs because ReloadAllServicesForAccount is called inside a DB
|
||||
// transaction but uses the main store connection, which blocks on the transaction lock.
|
||||
func TestDefaultAccountManager_UpdateAccountSettings_NetworkRangeChange(t *testing.T) {
|
||||
manager, _, err := createManager(t)
|
||||
require.NoError(t, err)
|
||||
|
||||
accountID, err := manager.GetAccountIDByUserID(context.Background(), auth.UserAuth{UserId: userID})
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Use a channel to detect if the call completes or hangs
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := manager.UpdateAccountSettings(ctx, accountID, userID, &types.Settings{
|
||||
PeerLoginExpiration: time.Hour,
|
||||
PeerLoginExpirationEnabled: true,
|
||||
NetworkRange: netip.MustParsePrefix("10.100.0.0/16"),
|
||||
Extra: &types.ExtraSettings{},
|
||||
})
|
||||
done <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
require.NoError(t, err, "UpdateAccountSettings should complete without error")
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("UpdateAccountSettings deadlocked when changing NetworkRange")
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -1,19 +1,25 @@
|
||||
FROM golang:1.25-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o netbird-proxy ./proxy/cmd/proxy
|
||||
|
||||
RUN echo "netbird:x:1000:1000:netbird:/var/lib/netbird:/sbin/nologin" > /tmp/passwd && \
|
||||
echo "netbird:x:1000:netbird" > /tmp/group && \
|
||||
mkdir -p /tmp/var/lib/netbird && \
|
||||
mkdir -p /tmp/certs
|
||||
|
||||
FROM gcr.io/distroless/base:debug
|
||||
COPY netbird-proxy /go/bin/netbird-proxy
|
||||
COPY --from=builder /app/netbird-proxy /usr/bin/netbird-proxy
|
||||
COPY --from=builder /tmp/passwd /etc/passwd
|
||||
COPY --from=builder /tmp/group /etc/group
|
||||
COPY --from=builder /tmp/var/lib/netbird /var/lib/netbird
|
||||
COPY --from=builder --chown=1000:1000 --chmod=755 /tmp/certs /certs
|
||||
COPY --from=builder --chown=1000:1000 /tmp/certs /certs
|
||||
USER netbird:netbird
|
||||
ENV HOME=/var/lib/netbird
|
||||
ENV NB_PROXY_ADDRESS=":8443"
|
||||
EXPOSE 8443
|
||||
ENTRYPOINT ["/go/bin/netbird-proxy"]
|
||||
ENTRYPOINT ["/usr/bin/netbird-proxy"]
|
||||
@@ -1,37 +0,0 @@
|
||||
FROM golang:1.25-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY client ./client
|
||||
COPY dns ./dns
|
||||
COPY encryption ./encryption
|
||||
COPY flow ./flow
|
||||
COPY formatter ./formatter
|
||||
COPY monotime ./monotime
|
||||
COPY proxy ./proxy
|
||||
COPY route ./route
|
||||
COPY shared ./shared
|
||||
COPY sharedsock ./sharedsock
|
||||
COPY upload-server ./upload-server
|
||||
COPY util ./util
|
||||
COPY version ./version
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o netbird-proxy ./proxy/cmd/proxy
|
||||
|
||||
RUN echo "netbird:x:1000:1000:netbird:/var/lib/netbird:/sbin/nologin" > /tmp/passwd && \
|
||||
echo "netbird:x:1000:netbird" > /tmp/group && \
|
||||
mkdir -p /tmp/var/lib/netbird && \
|
||||
mkdir -p /tmp/certs
|
||||
|
||||
FROM gcr.io/distroless/base:debug
|
||||
COPY --from=builder /app/netbird-proxy /usr/bin/netbird-proxy
|
||||
COPY --from=builder /tmp/passwd /etc/passwd
|
||||
COPY --from=builder /tmp/group /etc/group
|
||||
COPY --from=builder /tmp/var/lib/netbird /var/lib/netbird
|
||||
COPY --from=builder --chown=1000:1000 --chmod=755 /tmp/certs /certs
|
||||
USER netbird:netbird
|
||||
ENV HOME=/var/lib/netbird
|
||||
ENV NB_PROXY_ADDRESS=":8443"
|
||||
EXPOSE 8443
|
||||
ENTRYPOINT ["/usr/bin/netbird-proxy"]
|
||||
@@ -56,7 +56,6 @@ var (
|
||||
certKeyFile string
|
||||
certLockMethod string
|
||||
wgPort int
|
||||
proxyProtocol bool
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
@@ -91,7 +90,6 @@ func init() {
|
||||
rootCmd.Flags().StringVar(&certKeyFile, "cert-key-file", envStringOrDefault("NB_PROXY_CERTIFICATE_KEY_FILE", "tls.key"), "TLS certificate key filename within the certificate directory")
|
||||
rootCmd.Flags().StringVar(&certLockMethod, "cert-lock-method", envStringOrDefault("NB_PROXY_CERT_LOCK_METHOD", "auto"), "Certificate lock method for cross-replica coordination: auto, flock, or k8s-lease")
|
||||
rootCmd.Flags().IntVar(&wgPort, "wg-port", envIntOrDefault("NB_PROXY_WG_PORT", 0), "WireGuard listen port (0 = random). Fixed port only works with single-account deployments")
|
||||
rootCmd.Flags().BoolVar(&proxyProtocol, "proxy-protocol", envBoolOrDefault("NB_PROXY_PROXY_PROTOCOL", false), "Enable PROXY protocol on TCP listeners to preserve client IPs behind L4 proxies")
|
||||
}
|
||||
|
||||
// Execute runs the root command.
|
||||
@@ -167,7 +165,6 @@ func runServer(cmd *cobra.Command, args []string) error {
|
||||
TrustedProxies: parsedTrustedProxies,
|
||||
CertLockMethod: nbacme.CertLockMethod(certLockMethod),
|
||||
WireguardPort: wgPort,
|
||||
ProxyProtocol: proxyProtocol,
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// httpRedirectListener wraps a net.Listener and sniffs the first bytes of each connection
|
||||
// to determine if it's TLS or plain HTTP. Plain HTTP connections are redirected to HTTPS.
|
||||
type httpRedirectListener struct {
|
||||
net.Listener
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
func (l *httpRedirectListener) Accept() (net.Conn, error) {
|
||||
conn, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &httpRedirectConn{Conn: conn, logger: l.logger}, nil
|
||||
}
|
||||
|
||||
// httpRedirectConn wraps a connection and peeks at the first byte to detect TLS vs HTTP.
|
||||
// If HTTP is detected, it sends a redirect to HTTPS and closes the connection.
|
||||
type httpRedirectConn struct {
|
||||
net.Conn
|
||||
logger *log.Logger
|
||||
peeked bool
|
||||
isTLS bool
|
||||
}
|
||||
|
||||
func (c *httpRedirectConn) Read(b []byte) (int, error) {
|
||||
if c.peeked {
|
||||
return c.Conn.Read(b)
|
||||
}
|
||||
|
||||
c.peeked = true
|
||||
|
||||
// Peek at first byte
|
||||
firstByte := make([]byte, 1)
|
||||
n, err := c.Conn.Read(firstByte)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
|
||||
// TLS handshake starts with 0x16 (ContentType: handshake)
|
||||
if firstByte[0] == 0x16 {
|
||||
c.isTLS = true
|
||||
// Copy first byte to output buffer
|
||||
copy(b, firstByte)
|
||||
// Read remaining bytes
|
||||
if len(b) > 1 {
|
||||
n2, err := c.Conn.Read(b[1:])
|
||||
return n + n2, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Plain HTTP - handle redirect and close
|
||||
c.handleHTTPRedirect(firstByte)
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
func (c *httpRedirectConn) handleHTTPRedirect(firstByte []byte) {
|
||||
defer func(Conn net.Conn) {
|
||||
_ = Conn.Close()
|
||||
}(c.Conn)
|
||||
|
||||
// Create a reader that includes the first byte
|
||||
reader := io.MultiReader(bytes.NewReader(firstByte), c.Conn)
|
||||
bufReader := bufio.NewReader(reader)
|
||||
|
||||
// Parse the HTTP request
|
||||
req, err := http.ReadRequest(bufReader)
|
||||
if err != nil {
|
||||
c.logger.WithError(err).Debug("failed to parse HTTP request for redirect")
|
||||
return
|
||||
}
|
||||
|
||||
// Create a simple HTTP redirect response
|
||||
redirectURL := "https://" + req.Host + req.URL.String()
|
||||
response := &http.Response{
|
||||
StatusCode: http.StatusMovedPermanently,
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: make(http.Header),
|
||||
}
|
||||
response.Header.Set("Location", redirectURL)
|
||||
response.Header.Set("Content-Length", "0")
|
||||
if err := response.Write(c.Conn); err != nil {
|
||||
c.logger.WithError(err).Warn("failed to write HTTP redirect response")
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,11 @@
|
||||
<h2>Client Control</h2>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<span> </span>
|
||||
<label> </label>
|
||||
<button onclick="startClient()">Start</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<span> </span>
|
||||
<label> </label>
|
||||
<button onclick="stopClient()">Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -30,7 +30,7 @@
|
||||
<h2>Log Level</h2>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="log-level">Level</label>
|
||||
<label>Level</label>
|
||||
<select id="log-level" style="width: 120px;">
|
||||
<option value="trace">trace</option>
|
||||
<option value="debug">debug</option>
|
||||
@@ -40,7 +40,7 @@
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<span> </span>
|
||||
<label> </label>
|
||||
<button onclick="setLogLevel()">Set Level</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -49,15 +49,15 @@
|
||||
<h2>TCP Ping</h2>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="tcp-host">Host</label>
|
||||
<label>Host</label>
|
||||
<input type="text" id="tcp-host" placeholder="100.0.0.1 or hostname.netbird.cloud" style="width: 300px;">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="tcp-port">Port</label>
|
||||
<label>Port</label>
|
||||
<input type="number" id="tcp-port" placeholder="80" style="width: 80px;">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<span> </span>
|
||||
<label> </label>
|
||||
<button onclick="doTcpPing()">Connect</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -346,12 +346,6 @@ func classifyProxyError(err error) (title, message string, code int, status web.
|
||||
http.StatusBadGateway,
|
||||
web.ErrorStatus{Proxy: false, Destination: false}
|
||||
|
||||
case errors.Is(err, roundtrip.ErrTooManyInflight):
|
||||
return "Service Overloaded",
|
||||
"The service is currently handling too many requests. Please try again shortly.",
|
||||
http.StatusServiceUnavailable,
|
||||
web.ErrorStatus{Proxy: true, Destination: false}
|
||||
|
||||
case isConnectionRefused(err):
|
||||
return "Service Unavailable",
|
||||
"The connection to the service was refused. Please verify that the service is running and try again.",
|
||||
|
||||
@@ -24,9 +24,6 @@ import (
|
||||
|
||||
const deviceNamePrefix = "ingress-proxy-"
|
||||
|
||||
// backendKey identifies a backend by its host:port from the target URL.
|
||||
type backendKey = string
|
||||
|
||||
var (
|
||||
// ErrNoAccountID is returned when a request context is missing the account ID.
|
||||
ErrNoAccountID = errors.New("no account ID in request context")
|
||||
@@ -34,8 +31,6 @@ var (
|
||||
ErrNoPeerConnection = errors.New("no peer connection found")
|
||||
// ErrClientStartFailed is returned when the embedded client fails to start.
|
||||
ErrClientStartFailed = errors.New("client start failed")
|
||||
// ErrTooManyInflight is returned when the per-backend in-flight limit is reached.
|
||||
ErrTooManyInflight = errors.New("too many in-flight requests")
|
||||
)
|
||||
|
||||
// domainInfo holds metadata about a registered domain.
|
||||
@@ -55,35 +50,6 @@ type clientEntry struct {
|
||||
domains map[domain.Domain]domainInfo
|
||||
createdAt time.Time
|
||||
started bool
|
||||
// Per-backend in-flight limiting keyed by target host:port.
|
||||
// TODO: clean up stale entries when backend targets change.
|
||||
inflightMu sync.Mutex
|
||||
inflightMap map[backendKey]chan struct{}
|
||||
maxInflight int
|
||||
}
|
||||
|
||||
// acquireInflight attempts to acquire an in-flight slot for the given backend.
|
||||
// It returns a release function that must always be called, and true on success.
|
||||
func (e *clientEntry) acquireInflight(backend backendKey) (release func(), ok bool) {
|
||||
noop := func() {}
|
||||
if e.maxInflight <= 0 {
|
||||
return noop, true
|
||||
}
|
||||
|
||||
e.inflightMu.Lock()
|
||||
sem, exists := e.inflightMap[backend]
|
||||
if !exists {
|
||||
sem = make(chan struct{}, e.maxInflight)
|
||||
e.inflightMap[backend] = sem
|
||||
}
|
||||
e.inflightMu.Unlock()
|
||||
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
return func() { <-sem }, true
|
||||
default:
|
||||
return noop, false
|
||||
}
|
||||
}
|
||||
|
||||
type statusNotifier interface {
|
||||
@@ -98,13 +64,12 @@ type managementClient interface {
|
||||
// backed by underlying NetBird connections.
|
||||
// Clients are keyed by AccountID, allowing multiple domains to share the same connection.
|
||||
type NetBird struct {
|
||||
mgmtAddr string
|
||||
proxyID string
|
||||
proxyAddr string
|
||||
wgPort int
|
||||
logger *log.Logger
|
||||
mgmtClient managementClient
|
||||
transportCfg transportConfig
|
||||
mgmtAddr string
|
||||
proxyID string
|
||||
proxyAddr string
|
||||
wgPort int
|
||||
logger *log.Logger
|
||||
mgmtClient managementClient
|
||||
|
||||
clientsMux sync.RWMutex
|
||||
clients map[types.AccountID]*clientEntry
|
||||
@@ -248,21 +213,13 @@ func (n *NetBird) createClientEntry(ctx context.Context, accountID types.Account
|
||||
transport: &http.Transport{
|
||||
DialContext: client.DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: n.transportCfg.maxIdleConns,
|
||||
MaxIdleConnsPerHost: n.transportCfg.maxIdleConnsPerHost,
|
||||
MaxConnsPerHost: n.transportCfg.maxConnsPerHost,
|
||||
IdleConnTimeout: n.transportCfg.idleConnTimeout,
|
||||
TLSHandshakeTimeout: n.transportCfg.tlsHandshakeTimeout,
|
||||
ExpectContinueTimeout: n.transportCfg.expectContinueTimeout,
|
||||
ResponseHeaderTimeout: n.transportCfg.responseHeaderTimeout,
|
||||
WriteBufferSize: n.transportCfg.writeBufferSize,
|
||||
ReadBufferSize: n.transportCfg.readBufferSize,
|
||||
DisableCompression: n.transportCfg.disableCompression,
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
},
|
||||
createdAt: time.Now(),
|
||||
started: false,
|
||||
inflightMap: make(map[backendKey]chan struct{}),
|
||||
maxInflight: n.transportCfg.maxInflight,
|
||||
createdAt: time.Now(),
|
||||
started: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -410,12 +367,6 @@ func (n *NetBird) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
transport := entry.transport
|
||||
n.clientsMux.RUnlock()
|
||||
|
||||
release, ok := entry.acquireInflight(req.URL.Host)
|
||||
defer release()
|
||||
if !ok {
|
||||
return nil, ErrTooManyInflight
|
||||
}
|
||||
|
||||
// Attempt to start the client, if the client is already running then
|
||||
// it will return an error that we ignore, if this hits a timeout then
|
||||
// this request is unprocessable.
|
||||
@@ -552,7 +503,6 @@ func NewNetBird(mgmtAddr, proxyID, proxyAddr string, wgPort int, logger *log.Log
|
||||
clients: make(map[types.AccountID]*clientEntry),
|
||||
statusNotifier: notifier,
|
||||
mgmtClient: mgmtClient,
|
||||
transportCfg: loadTransportConfig(logger),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
package roundtrip
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Environment variable names for tuning the backend HTTP transport.
|
||||
const (
|
||||
EnvMaxIdleConns = "NB_PROXY_MAX_IDLE_CONNS"
|
||||
EnvMaxIdleConnsPerHost = "NB_PROXY_MAX_IDLE_CONNS_PER_HOST"
|
||||
EnvMaxConnsPerHost = "NB_PROXY_MAX_CONNS_PER_HOST"
|
||||
EnvIdleConnTimeout = "NB_PROXY_IDLE_CONN_TIMEOUT"
|
||||
EnvTLSHandshakeTimeout = "NB_PROXY_TLS_HANDSHAKE_TIMEOUT"
|
||||
EnvExpectContinueTimeout = "NB_PROXY_EXPECT_CONTINUE_TIMEOUT"
|
||||
EnvResponseHeaderTimeout = "NB_PROXY_RESPONSE_HEADER_TIMEOUT"
|
||||
EnvWriteBufferSize = "NB_PROXY_WRITE_BUFFER_SIZE"
|
||||
EnvReadBufferSize = "NB_PROXY_READ_BUFFER_SIZE"
|
||||
EnvDisableCompression = "NB_PROXY_DISABLE_COMPRESSION"
|
||||
EnvMaxInflight = "NB_PROXY_MAX_INFLIGHT"
|
||||
)
|
||||
|
||||
// transportConfig holds tunable parameters for the per-account HTTP transport.
|
||||
type transportConfig struct {
|
||||
maxIdleConns int
|
||||
maxIdleConnsPerHost int
|
||||
maxConnsPerHost int
|
||||
idleConnTimeout time.Duration
|
||||
tlsHandshakeTimeout time.Duration
|
||||
expectContinueTimeout time.Duration
|
||||
responseHeaderTimeout time.Duration
|
||||
writeBufferSize int
|
||||
readBufferSize int
|
||||
disableCompression bool
|
||||
// maxInflight limits per-backend concurrent requests. 0 means unlimited.
|
||||
maxInflight int
|
||||
}
|
||||
|
||||
func defaultTransportConfig() transportConfig {
|
||||
return transportConfig{
|
||||
maxIdleConns: 100,
|
||||
maxIdleConnsPerHost: 100,
|
||||
maxConnsPerHost: 0, // unlimited
|
||||
idleConnTimeout: 90 * time.Second,
|
||||
tlsHandshakeTimeout: 10 * time.Second,
|
||||
expectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func loadTransportConfig(logger *log.Logger) transportConfig {
|
||||
cfg := defaultTransportConfig()
|
||||
|
||||
if v, ok := envInt(EnvMaxIdleConns, logger); ok {
|
||||
cfg.maxIdleConns = v
|
||||
}
|
||||
if v, ok := envInt(EnvMaxIdleConnsPerHost, logger); ok {
|
||||
cfg.maxIdleConnsPerHost = v
|
||||
}
|
||||
if v, ok := envInt(EnvMaxConnsPerHost, logger); ok {
|
||||
cfg.maxConnsPerHost = v
|
||||
}
|
||||
if v, ok := envDuration(EnvIdleConnTimeout, logger); ok {
|
||||
cfg.idleConnTimeout = v
|
||||
}
|
||||
if v, ok := envDuration(EnvTLSHandshakeTimeout, logger); ok {
|
||||
cfg.tlsHandshakeTimeout = v
|
||||
}
|
||||
if v, ok := envDuration(EnvExpectContinueTimeout, logger); ok {
|
||||
cfg.expectContinueTimeout = v
|
||||
}
|
||||
if v, ok := envDuration(EnvResponseHeaderTimeout, logger); ok {
|
||||
cfg.responseHeaderTimeout = v
|
||||
}
|
||||
if v, ok := envInt(EnvWriteBufferSize, logger); ok {
|
||||
cfg.writeBufferSize = v
|
||||
}
|
||||
if v, ok := envInt(EnvReadBufferSize, logger); ok {
|
||||
cfg.readBufferSize = v
|
||||
}
|
||||
if v, ok := envBool(EnvDisableCompression, logger); ok {
|
||||
cfg.disableCompression = v
|
||||
}
|
||||
if v, ok := envInt(EnvMaxInflight, logger); ok {
|
||||
cfg.maxInflight = v
|
||||
}
|
||||
|
||||
logger.WithFields(log.Fields{
|
||||
"max_idle_conns": cfg.maxIdleConns,
|
||||
"max_idle_conns_per_host": cfg.maxIdleConnsPerHost,
|
||||
"max_conns_per_host": cfg.maxConnsPerHost,
|
||||
"idle_conn_timeout": cfg.idleConnTimeout,
|
||||
"tls_handshake_timeout": cfg.tlsHandshakeTimeout,
|
||||
"expect_continue_timeout": cfg.expectContinueTimeout,
|
||||
"response_header_timeout": cfg.responseHeaderTimeout,
|
||||
"write_buffer_size": cfg.writeBufferSize,
|
||||
"read_buffer_size": cfg.readBufferSize,
|
||||
"disable_compression": cfg.disableCompression,
|
||||
"max_inflight": cfg.maxInflight,
|
||||
}).Debug("backend transport configuration")
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func envInt(key string, logger *log.Logger) (int, bool) {
|
||||
s := os.Getenv(key)
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
v, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
logger.Warnf("failed to parse %s=%q as int: %v", key, s, err)
|
||||
return 0, false
|
||||
}
|
||||
if v < 0 {
|
||||
logger.Warnf("ignoring negative value for %s=%d", key, v)
|
||||
return 0, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
func envDuration(key string, logger *log.Logger) (time.Duration, bool) {
|
||||
s := os.Getenv(key)
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
v, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
logger.Warnf("failed to parse %s=%q as duration: %v", key, s, err)
|
||||
return 0, false
|
||||
}
|
||||
if v < 0 {
|
||||
logger.Warnf("ignoring negative value for %s=%s", key, v)
|
||||
return 0, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
func envBool(key string, logger *log.Logger) (bool, bool) {
|
||||
s := os.Getenv(key)
|
||||
if s == "" {
|
||||
return false, false
|
||||
}
|
||||
v, err := strconv.ParseBool(s)
|
||||
if err != nil {
|
||||
logger.Warnf("failed to parse %s=%q as bool: %v", key, s, err)
|
||||
return false, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
proxyproto "github.com/pires/go-proxyproto"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWrapProxyProtocol_OverridesRemoteAddr(t *testing.T) {
|
||||
srv := &Server{
|
||||
Logger: log.StandardLogger(),
|
||||
TrustedProxies: []netip.Prefix{netip.MustParsePrefix("127.0.0.1/32")},
|
||||
ProxyProtocol: true,
|
||||
}
|
||||
|
||||
raw, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
defer raw.Close()
|
||||
|
||||
ln := srv.wrapProxyProtocol(raw)
|
||||
|
||||
realClientIP := "203.0.113.50"
|
||||
realClientPort := uint16(54321)
|
||||
|
||||
accepted := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
accepted <- conn
|
||||
}()
|
||||
|
||||
// Connect and send a PROXY v2 header.
|
||||
conn, err := net.Dial("tcp", ln.Addr().String())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
header := &proxyproto.Header{
|
||||
Version: 2,
|
||||
Command: proxyproto.PROXY,
|
||||
TransportProtocol: proxyproto.TCPv4,
|
||||
SourceAddr: &net.TCPAddr{IP: net.ParseIP(realClientIP), Port: int(realClientPort)},
|
||||
DestinationAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 443},
|
||||
}
|
||||
_, err = header.WriteTo(conn)
|
||||
require.NoError(t, err)
|
||||
|
||||
select {
|
||||
case accepted := <-accepted:
|
||||
defer accepted.Close()
|
||||
host, _, err := net.SplitHostPort(accepted.RemoteAddr().String())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, realClientIP, host, "RemoteAddr should reflect the PROXY header source IP")
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyProtocolPolicy_TrustedRequires(t *testing.T) {
|
||||
srv := &Server{
|
||||
Logger: log.StandardLogger(),
|
||||
TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")},
|
||||
}
|
||||
|
||||
opts := proxyproto.ConnPolicyOptions{
|
||||
Upstream: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 1234},
|
||||
}
|
||||
policy, err := srv.proxyProtocolPolicy(opts)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, proxyproto.REQUIRE, policy, "trusted source should require PROXY header")
|
||||
}
|
||||
|
||||
func TestProxyProtocolPolicy_UntrustedIgnores(t *testing.T) {
|
||||
srv := &Server{
|
||||
Logger: log.StandardLogger(),
|
||||
TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")},
|
||||
}
|
||||
|
||||
opts := proxyproto.ConnPolicyOptions{
|
||||
Upstream: &net.TCPAddr{IP: net.ParseIP("203.0.113.50"), Port: 1234},
|
||||
}
|
||||
policy, err := srv.proxyProtocolPolicy(opts)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, proxyproto.IGNORE, policy, "untrusted source should have PROXY header ignored")
|
||||
}
|
||||
|
||||
func TestProxyProtocolPolicy_InvalidIPRejects(t *testing.T) {
|
||||
srv := &Server{
|
||||
Logger: log.StandardLogger(),
|
||||
TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")},
|
||||
}
|
||||
|
||||
opts := proxyproto.ConnPolicyOptions{
|
||||
Upstream: &net.UnixAddr{Name: "/tmp/test.sock", Net: "unix"},
|
||||
}
|
||||
policy, err := srv.proxyProtocolPolicy(opts)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, proxyproto.REJECT, policy, "unparsable address should be rejected")
|
||||
}
|
||||
+75
-108
@@ -23,7 +23,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/cenkalti/backoff/v4"
|
||||
proxyproto "github.com/pires/go-proxyproto"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -93,7 +92,7 @@ type Server struct {
|
||||
DebugEndpointEnabled bool
|
||||
// DebugEndpointAddress is the address for the debug HTTP endpoint (default: ":8444").
|
||||
DebugEndpointAddress string
|
||||
// HealthAddress is the address for the health probe endpoint.
|
||||
// HealthAddress is the address for the health probe endpoint (default: "localhost:8080").
|
||||
HealthAddress string
|
||||
// ProxyToken is the access token for authenticating with the management server.
|
||||
ProxyToken string
|
||||
@@ -108,10 +107,6 @@ type Server struct {
|
||||
// random OS-assigned port. A fixed port only works with single-account
|
||||
// deployments; multiple accounts will fail to bind the same port.
|
||||
WireguardPort int
|
||||
// ProxyProtocol enables PROXY protocol (v1/v2) on TCP listeners.
|
||||
// When enabled, the real client IP is extracted from the PROXY header
|
||||
// sent by upstream L4 proxies that support PROXY protocol.
|
||||
ProxyProtocol bool
|
||||
}
|
||||
|
||||
// NotifyStatus sends a status update to management about tunnel connectivity
|
||||
@@ -142,12 +137,12 @@ func (s *Server) NotifyCertificateIssued(ctx context.Context, accountID, service
|
||||
}
|
||||
|
||||
func (s *Server) ListenAndServe(ctx context.Context, addr string) (err error) {
|
||||
s.initDefaults()
|
||||
s.initializeDefaults()
|
||||
|
||||
reg := prometheus.NewRegistry()
|
||||
s.meter = metrics.New(reg)
|
||||
|
||||
mgmtConn, err := s.dialManagement()
|
||||
mgmtConn, err := s.setupManagementConnection(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -156,95 +151,73 @@ func (s *Server) ListenAndServe(ctx context.Context, addr string) (err error) {
|
||||
s.Logger.Debugf("management connection close: %v", err)
|
||||
}
|
||||
}()
|
||||
s.mgmtClient = proto.NewProxyServiceClient(mgmtConn)
|
||||
go s.newManagementMappingWorker(ctx, s.mgmtClient)
|
||||
|
||||
// Initialize the netbird client, this is required to build peer connections
|
||||
// to proxy over.
|
||||
s.netbird = roundtrip.NewNetBird(s.ManagementAddress, s.ID, s.ProxyURL, s.WireguardPort, s.Logger, s, s.mgmtClient)
|
||||
|
||||
tlsConfig, err := s.configureTLS(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Configure the reverse proxy using NetBird's HTTP Client Transport for proxying.
|
||||
s.proxy = proxy.NewReverseProxy(s.meter.RoundTripper(s.netbird), s.ForwardedProto, s.TrustedProxies, s.Logger)
|
||||
accessLog := s.initializeComponents()
|
||||
|
||||
// Configure the authentication middleware with session validator for OIDC group checks.
|
||||
s.auth = auth.NewMiddleware(s.Logger, s.mgmtClient)
|
||||
|
||||
// Configure Access logs to management server.
|
||||
accessLog := accesslog.NewLogger(s.mgmtClient, s.Logger, s.TrustedProxies)
|
||||
|
||||
s.healthChecker = health.NewChecker(s.Logger, s.netbird)
|
||||
|
||||
s.startDebugEndpoint()
|
||||
|
||||
if err := s.startHealthServer(reg); err != nil {
|
||||
if err := s.startDebugEndpoint(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Start the reverse proxy HTTPS server.
|
||||
s.https = &http.Server{
|
||||
Addr: addr,
|
||||
Handler: s.meter.Middleware(accessLog.Middleware(web.AssetHandler(s.auth.Protect(s.proxy)))),
|
||||
TLSConfig: tlsConfig,
|
||||
ErrorLog: newHTTPServerLogger(s.Logger, logtagValueHTTPS),
|
||||
if err := s.startHealthProbe(reg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lc := net.ListenConfig{}
|
||||
ln, err := lc.Listen(ctx, "tcp", addr)
|
||||
listener, err := s.createHTTPSListener(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen on %s: %w", addr, err)
|
||||
}
|
||||
if s.ProxyProtocol {
|
||||
ln = s.wrapProxyProtocol(ln)
|
||||
return err
|
||||
}
|
||||
|
||||
httpsErr := make(chan error, 1)
|
||||
go func() {
|
||||
s.Logger.Debugf("starting reverse proxy server on %s", addr)
|
||||
httpsErr <- s.https.ServeTLS(ln, "", "")
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-httpsErr:
|
||||
s.shutdownServices()
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
return fmt.Errorf("https server: %w", err)
|
||||
}
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
s.gracefulShutdown()
|
||||
return nil
|
||||
}
|
||||
return s.serveHTTPS(ctx, listener, addr, tlsConfig, accessLog)
|
||||
}
|
||||
|
||||
// initDefaults sets fallback values for optional Server fields.
|
||||
func (s *Server) initDefaults() {
|
||||
// initializeDefaults sets default values for server configuration fields.
|
||||
func (s *Server) initializeDefaults() {
|
||||
s.startTime = time.Now()
|
||||
|
||||
// If no ID is set then one can be generated.
|
||||
if s.ID == "" {
|
||||
s.ID = "netbird-proxy-" + s.startTime.Format("20060102150405")
|
||||
}
|
||||
// Fallback version option in case it is not set.
|
||||
if s.Version == "" {
|
||||
s.Version = "dev"
|
||||
}
|
||||
|
||||
// If no logger is specified fallback to the standard logger.
|
||||
if s.Logger == nil {
|
||||
s.Logger = log.StandardLogger()
|
||||
}
|
||||
}
|
||||
|
||||
// startDebugEndpoint launches the debug HTTP server if enabled.
|
||||
func (s *Server) startDebugEndpoint() {
|
||||
if !s.DebugEndpointEnabled {
|
||||
return
|
||||
// setupManagementConnection establishes the gRPC connection to the management server
|
||||
// and starts the mapping worker.
|
||||
func (s *Server) setupManagementConnection(ctx context.Context) (*grpc.ClientConn, error) {
|
||||
mgmtConn, err := s.dialManagement()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.mgmtClient = proto.NewProxyServiceClient(mgmtConn)
|
||||
go s.newManagementMappingWorker(ctx, s.mgmtClient)
|
||||
return mgmtConn, nil
|
||||
}
|
||||
|
||||
// initializeComponents sets up the core proxy components and returns the access logger.
|
||||
func (s *Server) initializeComponents() *accesslog.Logger {
|
||||
s.netbird = roundtrip.NewNetBird(s.ManagementAddress, s.ID, s.ProxyURL, s.WireguardPort, s.Logger, s, s.mgmtClient)
|
||||
s.proxy = proxy.NewReverseProxy(s.meter.RoundTripper(s.netbird), s.ForwardedProto, s.TrustedProxies, s.Logger)
|
||||
s.auth = auth.NewMiddleware(s.Logger, s.mgmtClient)
|
||||
accessLog := accesslog.NewLogger(s.mgmtClient, s.Logger, s.TrustedProxies)
|
||||
s.healthChecker = health.NewChecker(s.Logger, s.netbird)
|
||||
return accessLog
|
||||
}
|
||||
|
||||
// startDebugEndpoint starts the debug HTTP server if enabled.
|
||||
func (s *Server) startDebugEndpoint() error {
|
||||
if !s.DebugEndpointEnabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
debugAddr := debugEndpointAddr(s.DebugEndpointAddress)
|
||||
debugHandler := debug.NewHandler(s.netbird, s.healthChecker, s.Logger)
|
||||
if s.acme != nil {
|
||||
@@ -261,13 +234,14 @@ func (s *Server) startDebugEndpoint() {
|
||||
s.Logger.Errorf("debug endpoint error: %v", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// startHealthServer launches the health probe and metrics server.
|
||||
func (s *Server) startHealthServer(reg *prometheus.Registry) error {
|
||||
// startHealthProbe starts the health probe HTTP server.
|
||||
func (s *Server) startHealthProbe(reg *prometheus.Registry) error {
|
||||
healthAddr := s.HealthAddress
|
||||
if healthAddr == "" {
|
||||
healthAddr = defaultHealthAddr
|
||||
healthAddr = "localhost:8080"
|
||||
}
|
||||
s.healthServer = health.NewServer(healthAddr, s.healthChecker, s.Logger, promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
|
||||
healthListener, err := net.Listen("tcp", healthAddr)
|
||||
@@ -282,54 +256,47 @@ func (s *Server) startHealthServer(reg *prometheus.Registry) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// wrapProxyProtocol wraps a listener with PROXY protocol support.
|
||||
// When TrustedProxies is configured, only those sources may send PROXY headers;
|
||||
// connections from untrusted sources have any PROXY header ignored.
|
||||
func (s *Server) wrapProxyProtocol(ln net.Listener) net.Listener {
|
||||
ppListener := &proxyproto.Listener{
|
||||
Listener: ln,
|
||||
ReadHeaderTimeout: proxyProtoHeaderTimeout,
|
||||
// createHTTPSListener creates and wraps a TCP listener for HTTPS with HTTP redirect support.
|
||||
func (s *Server) createHTTPSListener(addr string) (net.Listener, error) {
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
|
||||
}
|
||||
if len(s.TrustedProxies) > 0 {
|
||||
ppListener.ConnPolicy = s.proxyProtocolPolicy
|
||||
} else {
|
||||
s.Logger.Warn("PROXY protocol enabled without trusted proxies; any source may send PROXY headers")
|
||||
}
|
||||
s.Logger.Info("PROXY protocol enabled on listener")
|
||||
return ppListener
|
||||
return &httpRedirectListener{
|
||||
Listener: listener,
|
||||
logger: s.Logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// proxyProtocolPolicy returns whether to require, skip, or reject the PROXY
|
||||
// header based on whether the connection source is in TrustedProxies.
|
||||
func (s *Server) proxyProtocolPolicy(opts proxyproto.ConnPolicyOptions) (proxyproto.Policy, error) {
|
||||
// No logging on reject to prevent abuse
|
||||
tcpAddr, ok := opts.Upstream.(*net.TCPAddr)
|
||||
if !ok {
|
||||
return proxyproto.REJECT, nil
|
||||
// serveHTTPS starts the HTTPS server and waits for it to complete or context cancellation.
|
||||
func (s *Server) serveHTTPS(ctx context.Context, listener net.Listener, addr string, tlsConfig *tls.Config, accessLog *accesslog.Logger) error {
|
||||
s.https = &http.Server{
|
||||
Addr: addr,
|
||||
Handler: s.meter.Middleware(accessLog.Middleware(web.AssetHandler(s.auth.Protect(s.proxy)))),
|
||||
TLSConfig: tlsConfig,
|
||||
ErrorLog: newHTTPServerLogger(s.Logger, logtagValueHTTPS),
|
||||
}
|
||||
addr, ok := netip.AddrFromSlice(tcpAddr.IP)
|
||||
if !ok {
|
||||
return proxyproto.REJECT, nil
|
||||
}
|
||||
addr = addr.Unmap()
|
||||
|
||||
// called per accept
|
||||
for _, prefix := range s.TrustedProxies {
|
||||
if prefix.Contains(addr) {
|
||||
return proxyproto.REQUIRE, nil
|
||||
httpsErr := make(chan error, 1)
|
||||
go func() {
|
||||
s.Logger.Debugf("starting reverse proxy server on %s", addr)
|
||||
httpsErr <- s.https.ServeTLS(listener, "", "")
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-httpsErr:
|
||||
s.shutdownServices()
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
return fmt.Errorf("https server: %w", err)
|
||||
}
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
s.gracefulShutdown()
|
||||
return nil
|
||||
}
|
||||
return proxyproto.IGNORE, nil
|
||||
}
|
||||
|
||||
const (
|
||||
defaultHealthAddr = "localhost:8080"
|
||||
defaultDebugAddr = "localhost:8444"
|
||||
|
||||
// proxyProtoHeaderTimeout is the deadline for reading the PROXY protocol
|
||||
// header after accepting a connection.
|
||||
proxyProtoHeaderTimeout = 5 * time.Second
|
||||
|
||||
// shutdownPreStopDelay is the time to wait after receiving a shutdown signal
|
||||
// before draining connections. This allows the load balancer to propagate
|
||||
// the endpoint removal.
|
||||
@@ -725,7 +692,7 @@ func (s *Server) protoToMapping(mapping *proto.ProxyMapping) proxy.Mapping {
|
||||
// If addr is empty, it defaults to localhost:8444 for security.
|
||||
func debugEndpointAddr(addr string) string {
|
||||
if addr == "" {
|
||||
return defaultDebugAddr
|
||||
return "localhost:8444"
|
||||
}
|
||||
return addr
|
||||
}
|
||||
Vendored
+3
-3
@@ -1,9 +1,9 @@
|
||||
(function(){const v=document.createElement("link").relList;if(v&&v.supports&&v.supports("modulepreload"))return;for(const _ of document.querySelectorAll('link[rel="modulepreload"]'))f(_);new MutationObserver(_=>{for(const O of _)if(O.type==="childList")for(const D of O.addedNodes)D.tagName==="LINK"&&D.rel==="modulepreload"&&f(D)}).observe(document,{childList:!0,subtree:!0});function S(_){const O={};return _.integrity&&(O.integrity=_.integrity),_.referrerPolicy&&(O.referrerPolicy=_.referrerPolicy),_.crossOrigin==="use-credentials"?O.credentials="include":_.crossOrigin==="anonymous"?O.credentials="omit":O.credentials="same-origin",O}function f(_){if(_.ep)return;_.ep=!0;const O=S(_);fetch(_.href,O)}})();var Sf={exports:{}},Du={};var Yd;function jm(){if(Yd)return Du;Yd=1;var r=Symbol.for("react.transitional.element"),v=Symbol.for("react.fragment");function S(f,_,O){var D=null;if(O!==void 0&&(D=""+O),_.key!==void 0&&(D=""+_.key),"key"in _){O={};for(var U in _)U!=="key"&&(O[U]=_[U])}else O=_;return _=O.ref,{$$typeof:r,type:f,key:D,ref:_!==void 0?_:null,props:O}}return Du.Fragment=v,Du.jsx=S,Du.jsxs=S,Du}var Gd;function Rm(){return Gd||(Gd=1,Sf.exports=jm()),Sf.exports}var A=Rm(),xf={exports:{}},K={};var Xd;function Hm(){if(Xd)return K;Xd=1;var r=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),_=Symbol.for("react.profiler"),O=Symbol.for("react.consumer"),D=Symbol.for("react.context"),U=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),R=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),V=Symbol.iterator;function st(s){return s===null||typeof s!="object"?null:(s=V&&s[V]||s["@@iterator"],typeof s=="function"?s:null)}var ct={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},G=Object.assign,Q={};function L(s,M,j){this.props=s,this.context=M,this.refs=Q,this.updater=j||ct}L.prototype.isReactComponent={},L.prototype.setState=function(s,M){if(typeof s!="object"&&typeof s!="function"&&s!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,s,M,"setState")},L.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function gt(){}gt.prototype=L.prototype;function zt(s,M,j){this.props=s,this.context=M,this.refs=Q,this.updater=j||ct}var _t=zt.prototype=new gt;_t.constructor=zt,G(_t,L.prototype),_t.isPureReactComponent=!0;var it=Array.isArray;function Ot(){}var J={H:null,A:null,T:null,S:null},Rt=Object.prototype.hasOwnProperty;function It(s,M,j){var q=j.ref;return{$$typeof:r,type:s,key:M,ref:q!==void 0?q:null,props:j}}function jl(s,M){return It(s.type,M,s.props)}function Pt(s){return typeof s=="object"&&s!==null&&s.$$typeof===r}function I(s){var M={"=":"=0",":":"=2"};return"$"+s.replace(/[=:]/g,function(j){return M[j]})}var Rl=/\/+/g;function tl(s,M){return typeof s=="object"&&s!==null&&s.key!=null?I(""+s.key):M.toString(36)}function ll(s){switch(s.status){case"fulfilled":return s.value;case"rejected":throw s.reason;default:switch(typeof s.status=="string"?s.then(Ot,Ot):(s.status="pending",s.then(function(M){s.status==="pending"&&(s.status="fulfilled",s.value=M)},function(M){s.status==="pending"&&(s.status="rejected",s.reason=M)})),s.status){case"fulfilled":return s.value;case"rejected":throw s.reason}}throw s}function x(s,M,j,q,k){var P=typeof s;(P==="undefined"||P==="boolean")&&(s=null);var yt=!1;if(s===null)yt=!0;else switch(P){case"bigint":case"string":case"number":yt=!0;break;case"object":switch(s.$$typeof){case r:case v:yt=!0;break;case R:return yt=s._init,x(yt(s._payload),M,j,q,k)}}if(yt)return k=k(s),yt=q===""?"."+tl(s,0):q,it(k)?(j="",yt!=null&&(j=yt.replace(Rl,"$&/")+"/"),x(k,M,j,"",function(qa){return qa})):k!=null&&(Pt(k)&&(k=jl(k,j+(k.key==null||s&&s.key===k.key?"":(""+k.key).replace(Rl,"$&/")+"/")+yt)),M.push(k)),1;yt=0;var Wt=q===""?".":q+":";if(it(s))for(var Ut=0;Ut<s.length;Ut++)q=s[Ut],P=Wt+tl(q,Ut),yt+=x(q,M,j,P,k);else if(Ut=st(s),typeof Ut=="function")for(s=Ut.call(s),Ut=0;!(q=s.next()).done;)q=q.value,P=Wt+tl(q,Ut++),yt+=x(q,M,j,P,k);else if(P==="object"){if(typeof s.then=="function")return x(ll(s),M,j,q,k);throw M=String(s),Error("Objects are not valid as a React child (found: "+(M==="[object Object]"?"object with keys {"+Object.keys(s).join(", ")+"}":M)+"). If you meant to render a collection of children, use an array instead.")}return yt}function C(s,M,j){if(s==null)return s;var q=[],k=0;return x(s,q,"","",function(P){return M.call(j,P,k++)}),q}function Z(s){if(s._status===-1){var M=s._result;M=M(),M.then(function(j){(s._status===0||s._status===-1)&&(s._status=1,s._result=j)},function(j){(s._status===0||s._status===-1)&&(s._status=2,s._result=j)}),s._status===-1&&(s._status=0,s._result=M)}if(s._status===1)return s._result.default;throw s._result}var nt=typeof reLine truncated
|
||||
(function(){const v=document.createElement("link").relList;if(v&&v.supports&&v.supports("modulepreload"))return;for(const _ of document.querySelectorAll('link[rel="modulepreload"]'))f(_);new MutationObserver(_=>{for(const O of _)if(O.type==="childList")for(const D of O.addedNodes)D.tagName==="LINK"&&D.rel==="modulepreload"&&f(D)}).observe(document,{childList:!0,subtree:!0});function p(_){const O={};return _.integrity&&(O.integrity=_.integrity),_.referrerPolicy&&(O.referrerPolicy=_.referrerPolicy),_.crossOrigin==="use-credentials"?O.credentials="include":_.crossOrigin==="anonymous"?O.credentials="omit":O.credentials="same-origin",O}function f(_){if(_.ep)return;_.ep=!0;const O=p(_);fetch(_.href,O)}})();var Sf={exports:{}},Du={};var Yd;function jm(){if(Yd)return Du;Yd=1;var r=Symbol.for("react.transitional.element"),v=Symbol.for("react.fragment");function p(f,_,O){var D=null;if(O!==void 0&&(D=""+O),_.key!==void 0&&(D=""+_.key),"key"in _){O={};for(var U in _)U!=="key"&&(O[U]=_[U])}else O=_;return _=O.ref,{$$typeof:r,type:f,key:D,ref:_!==void 0?_:null,props:O}}return Du.Fragment=v,Du.jsx=p,Du.jsxs=p,Du}var Gd;function Rm(){return Gd||(Gd=1,Sf.exports=jm()),Sf.exports}var A=Rm(),xf={exports:{}},K={};var Xd;function Hm(){if(Xd)return K;Xd=1;var r=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),_=Symbol.for("react.profiler"),O=Symbol.for("react.consumer"),D=Symbol.for("react.context"),U=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),S=Symbol.for("react.memo"),R=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),L=Symbol.iterator;function st(s){return s===null||typeof s!="object"?null:(s=L&&s[L]||s["@@iterator"],typeof s=="function"?s:null)}var Z={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},X=Object.assign,V={};function tt(s,M,j){this.props=s,this.context=M,this.refs=V,this.updater=j||Z}tt.prototype.isReactComponent={},tt.prototype.setState=function(s,M){if(typeof s!="object"&&typeof s!="function"&&s!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,s,M,"setState")},tt.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function St(){}St.prototype=tt.prototype;function xt(s,M,j){this.props=s,this.context=M,this.refs=V,this.updater=j||Z}var P=xt.prototype=new St;P.constructor=xt,X(P,tt.prototype),P.isPureReactComponent=!0;var jt=Array.isArray;function Nt(){}var W={H:null,A:null,T:null,S:null},wt=Object.prototype.hasOwnProperty;function It(s,M,j){var q=j.ref;return{$$typeof:r,type:s,key:M,ref:q!==void 0?q:null,props:j}}function jl(s,M){return It(s.type,M,s.props)}function Pt(s){return typeof s=="object"&&s!==null&&s.$$typeof===r}function I(s){var M={"=":"=0",":":"=2"};return"$"+s.replace(/[=:]/g,function(j){return M[j]})}var Rl=/\/+/g;function tl(s,M){return typeof s=="object"&&s!==null&&s.key!=null?I(""+s.key):M.toString(36)}function ll(s){switch(s.status){case"fulfilled":return s.value;case"rejected":throw s.reason;default:switch(typeof s.status=="string"?s.then(Nt,Nt):(s.status="pending",s.then(function(M){s.status==="pending"&&(s.status="fulfilled",s.value=M)},function(M){s.status==="pending"&&(s.status="rejected",s.reason=M)})),s.status){case"fulfilled":return s.value;case"rejected":throw s.reason}}throw s}function x(s,M,j,q,J){var lt=typeof s;(lt==="undefined"||lt==="boolean")&&(s=null);var yt=!1;if(s===null)yt=!0;else switch(lt){case"bigint":case"string":case"number":yt=!0;break;case"object":switch(s.$$typeof){case r:case v:yt=!0;break;case R:return yt=s._init,x(yt(s._payload),M,j,q,J)}}if(yt)return J=J(s),yt=q===""?"."+tl(s,0):q,jt(J)?(j="",yt!=null&&(j=yt.replace(Rl,"$&/")+"/"),x(J,M,j,"",function(qa){return qa})):J!=null&&(Pt(J)&&(J=jl(J,j+(J.key==null||s&&s.key===J.key?"":(""+J.key).replace(Rl,"$&/")+"/")+yt)),M.push(J)),1;yt=0;var Wt=q===""?".":q+":";if(jt(s))for(var Dt=0;Dt<s.length;Dt++)q=s[Dt],lt=Wt+tl(q,Dt),yt+=x(q,M,j,lt,J);else if(Dt=st(s),typeof Dt=="function")for(s=Dt.call(s),Dt=0;!(q=s.next()).done;)q=q.value,lt=Wt+tl(q,Dt++),yt+=x(q,M,j,lt,J);else if(lt==="object"){if(typeof s.then=="function")return x(ll(s),M,j,q,J);throw M=String(s),Error("Objects are not valid as a React child (found: "+(M==="[object Object]"?"object with keys {"+Object.keys(s).join(", ")+"}":M)+"). If you meant to render a collection of children, use an array instead.")}return yt}function C(s,M,j){if(s==null)return s;var q=[],J=0;return x(s,q,"","",function(lt){return M.call(j,lt,J++)}),q}function Q(s){if(s._status===-1){var M=s._result;M=M(),M.then(function(j){(s._status===0||s._status===-1)&&(s._status=1,s._result=j)},function(j){(s._status===0||s._status===-1)&&(s._status=2,s._result=j)}),s._status===-1&&(s._status=0,s._result=M)}if(s._status===1)return s._result.default;throw s._result}var ctLine truncated
|
||||
at`)?" (<anonymous>)":-1<e.stack.indexOf("@")?"@unknown:0:0":""}return`
|
||||
`+li+t+Bf}var ei=!1;function ai(t,l){if(!t||ei)return"";ei=!0;var e=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(l){var E=function(){throw Error()};if(Object.defineProperty(E.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(E,[])}catch(b){var g=b}Reflect.construct(t,[],E)}else{try{E.call()}catch(b){g=b}t.call(E.prototype)}}else{try{throw Error()}catch(b){g=b}(E=t())&&typeof E.catch=="function"&&E.catch(function(){})}}catch(b){if(b&&g&&typeof b.stack=="string")return[b.stack,g.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var u=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");u&&u.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var n=a.DetermineComponentFrameRoot(),i=n[0],c=n[1];if(i&&c){var o=i.split(`
|
||||
`),h=c.split(`
|
||||
`);for(u=a=0;a<o.length&&!o[a].includes("DetermineComponentFrameRoot");)a++;for(;u<h.length&&!h[u].includes("DetermineComponentFrameRoot");)u++;if(a===o.length||u===h.length)for(a=o.length-1,u=h.length-1;1<=a&&0<=u&&o[a]!==h[u];)u--;for(;1<=a&&0<=u;a--,u--)if(o[a]!==h[u]){if(a!==1||u!==1)do if(a--,u--,0>u||o[a]!==h[u]){var z=`
|
||||
`+o[a].replace(" at new "," at ");return t.displayName&&z.includes("<anonymous>")&&(z=z.replace("<anonymous>",t.displayName)),z}while(1<=a&&0<=u);break}}}finally{ei=!1,Error.prepareStackTrace=e}return(e=t?t.displayName||t.name:"")?Ue(e):""}function o0(t,l){switch(t.tag){case 26:case 27:case 5:return Ue(t.type);case 16:return Ue("Lazy");case 13:return t.child!==l&&l!==null?Ue("Suspense Fallback"):Ue("Suspense");case 19:return Ue("SuspenseList");case 0:case 15:return ai(t.type,!1);case 11:return ai(t.type.render,!1);case 1:return ai(t.type,!0);case 31:return Ue("Activity");default:return""}}function qf(t){try{var l="",e=null;do l+=o0(t,e),e=t,t=t.return;while(t);return l}catch(a){return`
|
||||
Error generating stack: `+a.message+`
|
||||
`+a.stack}}var ui=Object.prototype.hasOwnProperty,ni=r.unstable_scheduleCallback,ii=r.unstable_cancelCallback,s0=r.unstable_shouldYield,d0=r.unstable_requestPaint,rl=r.unstable_now,y0=r.unstable_getCurrentPriorityLevel,Yf=r.unstable_ImmediatePriority,Gf=r.unstable_UserBlockingPriority,Bu=r.unstable_NormalPriority,m0=r.unstable_LowPriority,Xf=r.unstable_IdlePriority,h0=r.log,g0=r.unstable_setDisableYieldValue,Ya=null,ol=null;function ue(t){if(typeof h0=="function"&&g0(t),ol&&typeof ol.setStrictMode=="function")try{ol.setStrictMode(Ya,t)}catch{}}var sl=Math.clz32?Math.clz32:p0,v0=Math.log,b0=Math.LN2;function p0(t){return t>>>=0,t===0?32:31-(v0(t)/b0|0)|0}var qu=256,Yu=262144,Gu=4194304;function Ce(t){var l=t&42;if(l!==0)return l;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Xu(t,l,e){var a=t.pendingLanes;if(a===0)return 0;var u=0,n=t.suspendedLanes,i=t.pingedLanes;t=t.warmLanes;var c=a&134217727;return c!==0?(a=c&~n,a!==0?u=Ce(a):(i&=c,i!==0?u=Ce(i):e||(e=c&~t,e!==0&&(u=Ce(e))))):(c=a&~n,c!==0?u=Ce(c):i!==0?u=Ce(i):e||(e=a&~t,e!==0&&(u=Ce(e)))),u===0?0:l!==0&&l!==u&&(l&n)===0&&(n=u&-u,e=l&-l,n>=e||n===32&&(e&4194048)!==0)?l:u}function Ga(t,l){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&l)===0}function S0(t,l){switch(t){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Qf(){var t=Gu;return Gu<<=1,(Gu&62914560)===0&&(Gu=4194304),t}function ci(t){for(var l=[],e=0;31>e;e++)l.push(t);return l}function Xa(t,l){t.pendingLanes|=l,l!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function x0(t,l,e,a,u,n){var i=t.pendingLanes;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=e,t.entangledLanes&=e,t.errorRecoveryDisabledLanes&=e,t.shellSuspendCounter=0;var c=t.entanglements,o=t.expirationTimes,h=t.hiddenUpdates;for(e=i&~e;0<e;){var z=31-sl(e),E=1<<z;c[z]=0,o[z]=-1;var g=h[z];if(g!==null)for(h[z]=null,z=0;z<g.length;z++){var b=g[z];b!==null&&(b.lane&=-536870913)}e&=~E}a!==0&&Zf(t,a,0),n!==0&&u===0&&t.tag!==0&&(t.suspendedLanes|=n&~(i&~l))}function Zf(t,l,e){t.pendingLanes|=l,t.suspendedLanes&=~l;var a=31-sl(l);t.entangledLanes|=l,t.entanglements[a]=t.entanglements[a]|1073741824|e&261930}function wf(t,l){var e=t.entangledLanes|=l;for(t=t.entanglements;e;){var a=31-sl(e),u=1<<a;u&l|t[a]&l&&(t[a]|=l),e&=~u}}function Lf(t,l){var e=l&-l;return e=(e&42)!==0?1:fi(e),(e&(t.suspendedLanes|l))!==0?0:e}function fi(t){switch(t){case 2:t=1;break;case 8:t=4;break;case 32:t=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:t=128;break;case 268435456:t=134217728;break;default:t=0}return t}function ri(t){return t&=-t,2<t?8<t?(t&134217727)!==0?32:268435456:8:2}function Vf(){var t=C.p;return t!==0?t:(t=window.event,t===void 0?32:Ud(t.type))}function Kf(t,l){var e=C.p;try{return C.p=t,l()}finally{C.p=e}}var ne=Math.random().toString(36).slice(2),wt="__reactFiber$"+ne,el="__reactProps$"+ne,Fe="__reactContainer$"+ne,oi="__reactEvents$"+ne,z0="__reactListeners$"+ne,T0="__reactHandles$"+ne,Jf="__reactResources$"+ne,Qa="__reactMarker$"+ne;function si(t){delete t[wt],delete t[el],delete t[oi],delete t[z0],delete t[T0]}function Ie(t){var l=t[wt];if(l)return l;for(var e=t.parentNode;e;){if(l=e[Fe]||e[wt]){if(e=l.alternate,l.child!==null||e!==null&&e.child!==null)for(t=hd(t);t!==null;){if(e=t[wt])return e;t=hd(t)}return l}t=e,e=t.parentNode}return null}function Pe(t){if(t=t[wt]||t[Fe]){var l=t.tag;if(l===5||l===6||l===13||l===31||l===26||l===27||l===3)return t}return null}function Za(t){var l=t.tag;if(l===5||l===26||l===27||l===6)return t.stateNode;throw Error(f(33))}function ta(t){var l=t[Jf];return l||(l=t[Jf]={hoistableStyles:new Map,hoistableScripts:new Map}),l}function Xt(t){t[Qa]=!0}var kf=new Set,Wf={};function je(t,l){la(t,l),la(t+"Capture",l)}function la(t,l){for(Wf[t]=l,t=0;t<l.length;t++)kf.add(l[t])}var E0=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u21
Line truncated
|
||||
`).replace(lm,"")}function nd(t,l){return l=ud(l),ud(t)===l}function bt(t,l,e,a,u,n){switch(e){case"children":typeof a=="string"?l==="body"||l==="textarea"&&a===""||aa(t,a):(typeof a=="number"||typeof a=="bigint")&&l!=="body"&&aa(t,""+a);break;case"className":Zu(t,"class",a);break;case"tabIndex":Zu(t,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":Zu(t,e,a);break;case"style":ur(t,a,n);break;case"data":if(l!=="object"){Zu(t,"data",a);break}case"src":case"href":if(a===""&&(l!=="a"||e!=="href")){t.removeAttribute(e);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(e);break}a=Lu(""+a),t.setAttribute(e,a);break;case"action":case"formAction":if(typeof a=="function"){t.setAttribute(e,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof n=="function"&&(e==="formAction"?(l!=="input"&&bt(t,l,"name",u.name,u,null),bt(t,l,"formEncType",u.formEncType,u,null),bt(t,l,"formMethod",u.formMethod,u,null),bt(t,l,"formTarget",u.formTarget,u,null)):(bt(t,l,"encType",u.encType,u,null),bt(t,l,"method",u.method,u,null),bt(t,l,"target",u.target,u,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(e);break}a=Lu(""+a),t.setAttribute(e,a);break;case"onClick":a!=null&&(t.onclick=Xl);break;case"onScroll":a!=null&<("scroll",t);break;case"onScrollEnd":a!=null&<("scrollend",t);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(f(61));if(e=a.__html,e!=null){if(u.children!=null)throw Error(f(60));t.innerHTML=e}}break;case"multiple":t.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":t.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){t.removeAttribute("xlink:href");break}e=Lu(""+a),t.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",e);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(e,""+a):t.removeAttribute(e);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(e,""):t.removeAttribute(e);break;case"capture":case"download":a===!0?t.setAttribute(e,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(e,a):t.removeAttribute(e);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?t.setAttribute(e,a):t.removeAttribute(e);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?t.removeAttribute(e):t.setAttribute(e,a);break;case"popover":lt("beforetoggle",t),lt("toggle",t),Qu(t,"popover",a);break;case"xlinkActuate":Gl(t,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Gl(t,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Gl(t,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Gl(t,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Gl(t,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Gl(t,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Gl(t,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Gl(t,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Gl(t,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Qu(t,"is",a);break;case"innerText":case"textContent":break;default:(!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(e=N0.get(e)||e,Qu(t,e,a))}}function lf(t,l,e,a,u,n){switch(e){case"style":ur(t,a,n);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(f(61));if(e=a.__html,e!=null){if(u.children!=null)throw Error(f(60));t.innerHTML=e}}break;case"children":typeof a=="string"?aa(t,a):(typeof a=="number"||typeof a=="bigint")&&aa(t,""+a);break;case"onScroll":a!=null&<("scroll",t);break;case"onScrollEnd":a!=null&<("scrollend",t);break;case"onClick":a!=null&&(t.onclick=Xl);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne
Line truncated
|
||||
`+a.stack}}var ui=Object.prototype.hasOwnProperty,ni=r.unstable_scheduleCallback,ii=r.unstable_cancelCallback,s0=r.unstable_shouldYield,d0=r.unstable_requestPaint,rl=r.unstable_now,y0=r.unstable_getCurrentPriorityLevel,Yf=r.unstable_ImmediatePriority,Gf=r.unstable_UserBlockingPriority,Bu=r.unstable_NormalPriority,m0=r.unstable_LowPriority,Xf=r.unstable_IdlePriority,h0=r.log,g0=r.unstable_setDisableYieldValue,Ya=null,ol=null;function ue(t){if(typeof h0=="function"&&g0(t),ol&&typeof ol.setStrictMode=="function")try{ol.setStrictMode(Ya,t)}catch{}}var sl=Math.clz32?Math.clz32:p0,v0=Math.log,b0=Math.LN2;function p0(t){return t>>>=0,t===0?32:31-(v0(t)/b0|0)|0}var qu=256,Yu=262144,Gu=4194304;function Ce(t){var l=t&42;if(l!==0)return l;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Xu(t,l,e){var a=t.pendingLanes;if(a===0)return 0;var u=0,n=t.suspendedLanes,i=t.pingedLanes;t=t.warmLanes;var c=a&134217727;return c!==0?(a=c&~n,a!==0?u=Ce(a):(i&=c,i!==0?u=Ce(i):e||(e=c&~t,e!==0&&(u=Ce(e))))):(c=a&~n,c!==0?u=Ce(c):i!==0?u=Ce(i):e||(e=a&~t,e!==0&&(u=Ce(e)))),u===0?0:l!==0&&l!==u&&(l&n)===0&&(n=u&-u,e=l&-l,n>=e||n===32&&(e&4194048)!==0)?l:u}function Ga(t,l){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&l)===0}function S0(t,l){switch(t){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Qf(){var t=Gu;return Gu<<=1,(Gu&62914560)===0&&(Gu=4194304),t}function ci(t){for(var l=[],e=0;31>e;e++)l.push(t);return l}function Xa(t,l){t.pendingLanes|=l,l!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function x0(t,l,e,a,u,n){var i=t.pendingLanes;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=e,t.entangledLanes&=e,t.errorRecoveryDisabledLanes&=e,t.shellSuspendCounter=0;var c=t.entanglements,o=t.expirationTimes,h=t.hiddenUpdates;for(e=i&~e;0<e;){var z=31-sl(e),E=1<<z;c[z]=0,o[z]=-1;var g=h[z];if(g!==null)for(h[z]=null,z=0;z<g.length;z++){var b=g[z];b!==null&&(b.lane&=-536870913)}e&=~E}a!==0&&wf(t,a,0),n!==0&&u===0&&t.tag!==0&&(t.suspendedLanes|=n&~(i&~l))}function wf(t,l,e){t.pendingLanes|=l,t.suspendedLanes&=~l;var a=31-sl(l);t.entangledLanes|=l,t.entanglements[a]=t.entanglements[a]|1073741824|e&261930}function Zf(t,l){var e=t.entangledLanes|=l;for(t=t.entanglements;e;){var a=31-sl(e),u=1<<a;u&l|t[a]&l&&(t[a]|=l),e&=~u}}function Lf(t,l){var e=l&-l;return e=(e&42)!==0?1:fi(e),(e&(t.suspendedLanes|l))!==0?0:e}function fi(t){switch(t){case 2:t=1;break;case 8:t=4;break;case 32:t=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:t=128;break;case 268435456:t=134217728;break;default:t=0}return t}function ri(t){return t&=-t,2<t?8<t?(t&134217727)!==0?32:268435456:8:2}function Vf(){var t=C.p;return t!==0?t:(t=window.event,t===void 0?32:Ud(t.type))}function Kf(t,l){var e=C.p;try{return C.p=t,l()}finally{C.p=e}}var ne=Math.random().toString(36).slice(2),Zt="__reactFiber$"+ne,el="__reactProps$"+ne,Fe="__reactContainer$"+ne,oi="__reactEvents$"+ne,z0="__reactListeners$"+ne,T0="__reactHandles$"+ne,Jf="__reactResources$"+ne,Qa="__reactMarker$"+ne;function si(t){delete t[Zt],delete t[el],delete t[oi],delete t[z0],delete t[T0]}function Ie(t){var l=t[Zt];if(l)return l;for(var e=t.parentNode;e;){if(l=e[Fe]||e[Zt]){if(e=l.alternate,l.child!==null||e!==null&&e.child!==null)for(t=hd(t);t!==null;){if(e=t[Zt])return e;t=hd(t)}return l}t=e,e=t.parentNode}return null}function Pe(t){if(t=t[Zt]||t[Fe]){var l=t.tag;if(l===5||l===6||l===13||l===31||l===26||l===27||l===3)return t}return null}function wa(t){var l=t.tag;if(l===5||l===26||l===27||l===6)return t.stateNode;throw Error(f(33))}function ta(t){var l=t[Jf];return l||(l=t[Jf]={hoistableStyles:new Map,hoistableScripts:new Map}),l}function Gt(t){t[Qa]=!0}var kf=new Set,Wf={};function je(t,l){la(t,l),la(t+"Capture",l)}function la(t,l){for(Wf[t]=l,t=0;t<l.length;t++)kf.add(l[t])}var E0=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u21
Line truncated
|
||||
`).replace(lm,"")}function nd(t,l){return l=ud(l),ud(t)===l}function vt(t,l,e,a,u,n){switch(e){case"children":typeof a=="string"?l==="body"||l==="textarea"&&a===""||aa(t,a):(typeof a=="number"||typeof a=="bigint")&&l!=="body"&&aa(t,""+a);break;case"className":wu(t,"class",a);break;case"tabIndex":wu(t,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":wu(t,e,a);break;case"style":ur(t,a,n);break;case"data":if(l!=="object"){wu(t,"data",a);break}case"src":case"href":if(a===""&&(l!=="a"||e!=="href")){t.removeAttribute(e);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(e);break}a=Lu(""+a),t.setAttribute(e,a);break;case"action":case"formAction":if(typeof a=="function"){t.setAttribute(e,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof n=="function"&&(e==="formAction"?(l!=="input"&&vt(t,l,"name",u.name,u,null),vt(t,l,"formEncType",u.formEncType,u,null),vt(t,l,"formMethod",u.formMethod,u,null),vt(t,l,"formTarget",u.formTarget,u,null)):(vt(t,l,"encType",u.encType,u,null),vt(t,l,"method",u.method,u,null),vt(t,l,"target",u.target,u,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(e);break}a=Lu(""+a),t.setAttribute(e,a);break;case"onClick":a!=null&&(t.onclick=Xl);break;case"onScroll":a!=null&&at("scroll",t);break;case"onScrollEnd":a!=null&&at("scrollend",t);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(f(61));if(e=a.__html,e!=null){if(u.children!=null)throw Error(f(60));t.innerHTML=e}}break;case"multiple":t.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":t.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){t.removeAttribute("xlink:href");break}e=Lu(""+a),t.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",e);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(e,""+a):t.removeAttribute(e);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(e,""):t.removeAttribute(e);break;case"capture":case"download":a===!0?t.setAttribute(e,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(e,a):t.removeAttribute(e);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?t.setAttribute(e,a):t.removeAttribute(e);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?t.removeAttribute(e):t.setAttribute(e,a);break;case"popover":at("beforetoggle",t),at("toggle",t),Qu(t,"popover",a);break;case"xlinkActuate":Gl(t,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Gl(t,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Gl(t,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Gl(t,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Gl(t,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Gl(t,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Gl(t,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Gl(t,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Gl(t,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Qu(t,"is",a);break;case"innerText":case"textContent":break;default:(!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(e=N0.get(e)||e,Qu(t,e,a))}}function lf(t,l,e,a,u,n){switch(e){case"style":ur(t,a,n);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(f(61));if(e=a.__html,e!=null){if(u.children!=null)throw Error(f(60));t.innerHTML=e}}break;case"children":typeof a=="string"?aa(t,a):(typeof a=="number"||typeof a=="bigint")&&aa(t,""+a);break;case"onScroll":a!=null&&at("scroll",t);break;case"onScrollEnd":a!=null&&at("scrollend",t);break;case"onClick":a!=null&&(t.onclick=Xl);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne
Line truncated
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-100:#fde8e8;--color-red-400:#f98080;--color-red-500:#f05252;--color-red-600:#e02424;--color-red-700:#c81e1e;--color-red-800:#9b1c1c;--color-red-950:oklch(25.8% .092 26.042);--color-green-500:#0e9f6e;--color-gray-100:#f3f4f6;--color-gray-200:#e5e7eb;--color-gray-400:#9ca3af;--color-gray-500:#6b7280;--color-gray-700:#374151;--color-gray-800:#1f2937;--color-gray-900:#111827;--color-zinc-50:oklch(98.5% 0 0);--color-zinc-200:oklch(92% .004 286.32);--color-zinc-800:oklch(27.4% .006 286.033);--color-neutral-200:oklch(92.2% 0 0);--color-neutral-400:oklch(70.8% 0 0);--color-neutral-500:oklch(55.6% 0 0);--color-neutral-950:oklch(14.5% 0 0);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--font-weight-light:300;--font-weight-normal:400;--font-weight-medium:500;--tracking-wide:.025em;--tracking-wider:.05em;--radius-md:.375rem;--radius-lg:.5rem;--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-nb-gray:#181a1d;--color-nb-gray-100:#e4e7e9;--color-nb-gray-200:#cbd2d6;--color-nb-gray-300:#aab4bd;--color-nb-gray-400:#7c8994;--color-nb-gray-500:#616e79;--color-nb-gray-700:#474e57;--color-nb-gray-800:#3f444b;--color-nb-gray-900:#32363d;--color-nb-gray-910:#2b2f33;--color-nb-gray-920:#25282d;--color-nb-gray-930:#25282c;--color-nb-gray-940:#1c1e21;--color-nb-gray-950:#181a1d;--color-netbird:#f68330;--color-netbird-400:#f68330;--color-netbird-500:#f46d1b;--color-netbird-600:#e55311}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-familyLine truncated
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-100:#fde8e8;--color-red-400:#f98080;--color-red-500:#f05252;--color-red-600:#e02424;--color-red-700:#c81e1e;--color-red-800:#9b1c1c;--color-red-950:oklch(25.8% .092 26.042);--color-green-500:#0e9f6e;--color-gray-100:#f3f4f6;--color-gray-200:#e5e7eb;--color-gray-400:#9ca3af;--color-gray-500:#6b7280;--color-gray-700:#374151;--color-gray-800:#1f2937;--color-gray-900:#111827;--color-zinc-50:oklch(98.5% 0 0);--color-zinc-200:oklch(92% .004 286.32);--color-zinc-800:oklch(27.4% .006 286.033);--color-neutral-200:oklch(92.2% 0 0);--color-neutral-400:oklch(70.8% 0 0);--color-neutral-500:oklch(55.6% 0 0);--color-neutral-950:oklch(14.5% 0 0);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--font-weight-light:300;--font-weight-normal:400;--font-weight-medium:500;--tracking-wide:.025em;--tracking-wider:.05em;--radius-md:.375rem;--radius-lg:.5rem;--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-nb-gray:#181a1d;--color-nb-gray-100:#e4e7e9;--color-nb-gray-200:#cbd2d6;--color-nb-gray-300:#aab4bd;--color-nb-gray-400:#7c8994;--color-nb-gray-500:#616e79;--color-nb-gray-700:#474e57;--color-nb-gray-800:#3f444b;--color-nb-gray-900:#32363d;--color-nb-gray-910:#2b2f33;--color-nb-gray-920:#25282d;--color-nb-gray-930:#25282c;--color-nb-gray-940:#1c1e21;--color-nb-gray-950:#181a1d;--color-netbird:#f68330;--color-netbird-400:#f68330;--color-netbird-500:#f46d1b;--color-netbird-600:#e55311}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-familyLine truncated
|
||||
@@ -59,7 +59,7 @@ function App() {
|
||||
formData.append(methods.pin!, value);
|
||||
}
|
||||
|
||||
fetch(globalThis.location.href, {
|
||||
fetch(window.location.href, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
redirect: "manual",
|
||||
@@ -67,7 +67,7 @@ function App() {
|
||||
.then((res) => {
|
||||
if (res.type === "opaqueredirect" || res.status === 0) {
|
||||
setSubmitting("redirect");
|
||||
globalThis.location.reload();
|
||||
window.location.reload();
|
||||
} else {
|
||||
handleAuthError(method, "Authentication failed. Please try again.");
|
||||
}
|
||||
@@ -92,7 +92,6 @@ function App() {
|
||||
|
||||
const hasCredentialAuth = methods.password || methods.pin;
|
||||
const hasBothCredentials = methods.password && methods.pin;
|
||||
const buttonLabel = activeTab === "password" ? "Sign in" : "Submit";
|
||||
|
||||
if (submitting === "redirect") {
|
||||
return (
|
||||
@@ -125,7 +124,7 @@ function App() {
|
||||
<Button
|
||||
variant="primary"
|
||||
className="w-full"
|
||||
onClick={() => { globalThis.location.href = methods.oidc!; }}
|
||||
onClick={() => (window.location.href = methods.oidc!)}
|
||||
>
|
||||
<LogIn size={16} />
|
||||
Sign in with SSO
|
||||
@@ -171,7 +170,7 @@ function App() {
|
||||
<div className="mb-4">
|
||||
{methods.password && (activeTab === "password" || !methods.pin) && (
|
||||
<>
|
||||
{!hasBothCredentials && <Label htmlFor="password">Password</Label>}
|
||||
{!hasBothCredentials && <Label>Password</Label>}
|
||||
<Input
|
||||
ref={passwordRef}
|
||||
type="password"
|
||||
@@ -187,7 +186,7 @@ function App() {
|
||||
)}
|
||||
{methods.pin && (activeTab === "pin" || !methods.password) && (
|
||||
<>
|
||||
{!hasBothCredentials && <Label htmlFor="pin-0">Enter PIN Code</Label>}
|
||||
{!hasBothCredentials && <Label>Enter PIN Code</Label>}
|
||||
<PinCodeInput
|
||||
ref={pinRef}
|
||||
value={pin}
|
||||
@@ -205,13 +204,13 @@ function App() {
|
||||
variant="secondary"
|
||||
className="w-full"
|
||||
>
|
||||
{submitting === null ? (
|
||||
buttonLabel
|
||||
) : (
|
||||
{submitting !== null ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" size={16} />
|
||||
Verifying...
|
||||
</>
|
||||
) : (
|
||||
activeTab === "password" ? "Sign in" : "Submit"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PoweredByNetBird } from "@/components/PoweredByNetBird";
|
||||
import { StatusCard } from "@/components/StatusCard";
|
||||
import type { ErrorData } from "@/data";
|
||||
|
||||
export function ErrorPage({ code, title, message, proxy = true, destination = true, requestId, simple = false, retryUrl }: Readonly<ErrorData>) {
|
||||
export function ErrorPage({ code, title, message, proxy = true, destination = true, requestId, simple = false, retryUrl }: ErrorData) {
|
||||
useEffect(() => {
|
||||
document.title = `${title} - NetBird Service`;
|
||||
}, [title]);
|
||||
@@ -38,19 +38,13 @@ export function ErrorPage({ code, title, message, proxy = true, destination = tr
|
||||
|
||||
{/* Buttons */}
|
||||
<div className="flex gap-3 justify-center items-center mb-6 z-10 relative">
|
||||
<Button variant="primary" onClick={() => {
|
||||
if (retryUrl) {
|
||||
globalThis.location.href = retryUrl;
|
||||
} else {
|
||||
globalThis.location.reload();
|
||||
}
|
||||
}}>
|
||||
<Button variant="primary" onClick={() => retryUrl ? window.location.href = retryUrl : window.location.reload()}>
|
||||
<RotateCw size={16} />
|
||||
Refresh Page
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => globalThis.open("https://docs.netbird.io", "_blank", "noopener,noreferrer")}
|
||||
onClick={() => window.open("https://docs.netbird.io", "_blank", "noopener,noreferrer")}
|
||||
>
|
||||
<BookText size={16} />
|
||||
Documentation
|
||||
|
||||
@@ -4,7 +4,7 @@ interface ConnectionLineProps {
|
||||
success?: boolean;
|
||||
}
|
||||
|
||||
export function ConnectionLine({ success = true }: Readonly<ConnectionLineProps>) {
|
||||
export function ConnectionLine({ success = true }: ConnectionLineProps) {
|
||||
if (success) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center h-12 w-full px-5">
|
||||
|
||||
@@ -5,7 +5,7 @@ type Props = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export function Description({ children, className }: Readonly<Props>) {
|
||||
export function Description({ children, className }: Props) {
|
||||
return (
|
||||
<div className={cn("text-sm text-nb-gray-300 font-light mt-2 block text-center z-10 relative", className)}>
|
||||
{children}
|
||||
|
||||
@@ -5,7 +5,7 @@ interface HelpTextProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function HelpText({ children, className }: Readonly<HelpTextProps>) {
|
||||
export default function HelpText({ children, className }: HelpTextProps) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
|
||||
@@ -2,10 +2,9 @@ import { cn } from "@/utils/helpers";
|
||||
|
||||
type LabelProps = React.LabelHTMLAttributes<HTMLLabelElement>;
|
||||
|
||||
export function Label({ className, htmlFor, ...props }: Readonly<LabelProps>) {
|
||||
export function Label({ className, ...props }: LabelProps) {
|
||||
return (
|
||||
<label
|
||||
htmlFor={htmlFor}
|
||||
className={cn(
|
||||
"text-sm font-medium tracking-wider leading-none",
|
||||
"peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
|
||||
|
||||
@@ -20,7 +20,7 @@ interface Props {
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
const PinCodeInput = forwardRef<PinCodeInputRef, Readonly<Props>>(function PinCodeInput(
|
||||
const PinCodeInput = forwardRef<PinCodeInputRef, Props>(function PinCodeInput(
|
||||
{ value, onChange, length = 6, disabled = false, className, autoFocus = false },
|
||||
ref,
|
||||
) {
|
||||
@@ -32,15 +32,14 @@ const PinCodeInput = forwardRef<PinCodeInputRef, Readonly<Props>>(function PinCo
|
||||
},
|
||||
}));
|
||||
|
||||
const digits = value.split("").concat(new Array(length).fill("")).slice(0, length);
|
||||
const slotIds = Array.from({ length }, (_, i) => `pin-${i}`);
|
||||
const digits = value.split("").concat(Array(length).fill("")).slice(0, length);
|
||||
|
||||
const handleChange = (index: number, digit: string) => {
|
||||
if (!/^\d*$/.test(digit)) return;
|
||||
|
||||
const newDigits = [...digits];
|
||||
newDigits[index] = digit.slice(-1);
|
||||
const newValue = newDigits.join("").replaceAll(/\s/g, "");
|
||||
const newValue = newDigits.join("").replace(/\s/g, "");
|
||||
onChange(newValue);
|
||||
|
||||
if (digit && index < length - 1) {
|
||||
@@ -62,7 +61,7 @@ const PinCodeInput = forwardRef<PinCodeInputRef, Readonly<Props>>(function PinCo
|
||||
|
||||
const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedData = e.clipboardData.getData("text").replaceAll(/\D/g, "").slice(0, length);
|
||||
const pastedData = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, length);
|
||||
onChange(pastedData);
|
||||
|
||||
const nextIndex = Math.min(pastedData.length, length - 1);
|
||||
@@ -77,8 +76,7 @@ const PinCodeInput = forwardRef<PinCodeInputRef, Readonly<Props>>(function PinCo
|
||||
<div className={cn("flex gap-2 w-full min-w-0", className)}>
|
||||
{digits.map((digit, index) => (
|
||||
<input
|
||||
key={slotIds[index]}
|
||||
id={slotIds[index]}
|
||||
key={index}
|
||||
ref={(el) => {
|
||||
inputRefs.current[index] = el;
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { cn } from "@/utils/helpers";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useState } from "react";
|
||||
import { TabContext, useTabContext } from "./TabContext";
|
||||
|
||||
type TabsProps = {
|
||||
@@ -11,24 +11,19 @@ type TabsProps = {
|
||||
| ((context: { value: string; onChange: (value: string) => void }) => React.ReactNode);
|
||||
};
|
||||
|
||||
function SegmentedTabs({ value, defaultValue, onChange, children }: Readonly<TabsProps>) {
|
||||
const [internalValue, setInternalValue] = useState(defaultValue ?? "");
|
||||
const currentValue = value ?? internalValue;
|
||||
function SegmentedTabs({ value, defaultValue, onChange, children }: TabsProps) {
|
||||
const [internalValue, setInternalValue] = useState(defaultValue || "");
|
||||
const currentValue = value !== undefined ? value : internalValue;
|
||||
|
||||
const handleChange = useCallback((newValue: string) => {
|
||||
const handleChange = (newValue: string) => {
|
||||
if (value === undefined) {
|
||||
setInternalValue(newValue);
|
||||
}
|
||||
onChange?.(newValue);
|
||||
}, [value, onChange]);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({ value: currentValue, onChange: handleChange }),
|
||||
[currentValue, handleChange],
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<TabContext.Provider value={contextValue}>
|
||||
<TabContext.Provider value={{ value: currentValue, onChange: handleChange }}>
|
||||
<div>
|
||||
{typeof children === "function"
|
||||
? children({ value: currentValue, onChange: handleChange })
|
||||
@@ -41,10 +36,10 @@ function SegmentedTabs({ value, defaultValue, onChange, children }: Readonly<Tab
|
||||
function List({
|
||||
children,
|
||||
className,
|
||||
}: Readonly<{
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}>) {
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
role="tablist"
|
||||
@@ -65,23 +60,16 @@ function Trigger({
|
||||
className,
|
||||
selected,
|
||||
onClick,
|
||||
}: Readonly<{
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
value: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
selected?: boolean;
|
||||
onClick?: () => void;
|
||||
}>) {
|
||||
}) {
|
||||
const context = useTabContext();
|
||||
const isSelected = selected ?? value === context.value;
|
||||
|
||||
let stateClassName = "";
|
||||
if (isSelected) {
|
||||
stateClassName = "bg-nb-gray-900 text-white";
|
||||
} else if (!disabled) {
|
||||
stateClassName = "text-nb-gray-400 hover:bg-nb-gray-900/50";
|
||||
}
|
||||
const isSelected = selected !== undefined ? selected : value === context.value;
|
||||
|
||||
const handleClick = () => {
|
||||
context.onChange(value);
|
||||
@@ -98,7 +86,11 @@ function Trigger({
|
||||
className={cn(
|
||||
"px-4 py-2 text-sm rounded-md w-full transition-all cursor-pointer",
|
||||
disabled && "opacity-30 cursor-not-allowed",
|
||||
stateClassName,
|
||||
isSelected
|
||||
? "bg-nb-gray-900 text-white"
|
||||
: disabled
|
||||
? ""
|
||||
: "text-nb-gray-400 hover:bg-nb-gray-900/50",
|
||||
className
|
||||
)}
|
||||
>
|
||||
@@ -114,14 +106,14 @@ function Content({
|
||||
value,
|
||||
className,
|
||||
visible,
|
||||
}: Readonly<{
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
value: string;
|
||||
className?: string;
|
||||
visible?: boolean;
|
||||
}>) {
|
||||
}) {
|
||||
const context = useTabContext();
|
||||
const isVisible = visible ?? value === context.value;
|
||||
const isVisible = visible !== undefined ? visible : value === context.value;
|
||||
|
||||
if (!isVisible) return null;
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ export function StatusCard({
|
||||
detail,
|
||||
success = true,
|
||||
line = true,
|
||||
}: Readonly<StatusCardProps>) {
|
||||
}: StatusCardProps) {
|
||||
return (
|
||||
<>
|
||||
{line && <ConnectionLine success={success} />}
|
||||
|
||||
@@ -5,7 +5,7 @@ type Props = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export function Title({ children, className }: Readonly<Props>) {
|
||||
export function Title({ children, className }: Props) {
|
||||
return (
|
||||
<h1 className={cn("text-xl! text-center z-10 relative", className)}>
|
||||
{children}
|
||||
|
||||
@@ -24,16 +24,17 @@ export interface Data {
|
||||
}
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var __DATA__: Data | undefined
|
||||
interface Window {
|
||||
__DATA__?: Data
|
||||
}
|
||||
}
|
||||
|
||||
export function getData(): Data {
|
||||
const data = globalThis.__DATA__ ?? {}
|
||||
const data = window.__DATA__ ?? {}
|
||||
|
||||
// Dev mode: allow ?page=error query param to preview error page
|
||||
if (import.meta.env.DEV) {
|
||||
const params = new URLSearchParams(globalThis.location.search)
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const page = params.get('page')
|
||||
if (page === 'error') {
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@font-face {
|
||||
font-family: "Inter";
|
||||
font-style: normal;
|
||||
@@ -186,6 +184,9 @@
|
||||
|
||||
html {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
html{
|
||||
@apply bg-nb-gray;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import path from 'node:path'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// BillingAPI APIs for billing and invoices
|
||||
type BillingAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// GetUsage retrieves current usage statistics for the account
|
||||
// See more: https://docs.netbird.io/api/resources/billing#get-current-usage
|
||||
func (a *BillingAPI) GetUsage(ctx context.Context) (*api.UsageStats, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/billing/usage", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.UsageStats](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// GetSubscription retrieves the current subscription details
|
||||
// See more: https://docs.netbird.io/api/resources/billing#get-current-subscription
|
||||
func (a *BillingAPI) GetSubscription(ctx context.Context) (*api.Subscription, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/billing/subscription", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.Subscription](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// GetInvoices retrieves the account's paid invoices
|
||||
// See more: https://docs.netbird.io/api/resources/billing#list-all-invoices
|
||||
func (a *BillingAPI) GetInvoices(ctx context.Context) ([]api.InvoiceResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/billing/invoices", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.InvoiceResponse](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// GetInvoicePDF retrieves the invoice PDF URL
|
||||
// See more: https://docs.netbird.io/api/resources/billing#get-invoice-pdf
|
||||
func (a *BillingAPI) GetInvoicePDF(ctx context.Context, invoiceID string) (*api.InvoicePDFResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/billing/invoices/"+invoiceID+"/pdf", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.InvoicePDFResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// GetInvoiceCSV retrieves the invoice CSV content
|
||||
// See more: https://docs.netbird.io/api/resources/billing#get-invoice-csv
|
||||
func (a *BillingAPI) GetInvoiceCSV(ctx context.Context, invoiceID string) (string, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/billing/invoices/"+invoiceID+"/csv", nil, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[string](resp)
|
||||
return ret, err
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 (
|
||||
testUsageStats = api.UsageStats{
|
||||
ActiveUsers: 15,
|
||||
TotalUsers: 20,
|
||||
ActivePeers: 10,
|
||||
TotalPeers: 25,
|
||||
}
|
||||
|
||||
testSubscription = api.Subscription{
|
||||
Active: true,
|
||||
PlanTier: "basic",
|
||||
PriceId: "price_1HhxOp",
|
||||
Currency: "USD",
|
||||
Price: 1000,
|
||||
Provider: "stripe",
|
||||
UpdatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
|
||||
testInvoice = api.InvoiceResponse{
|
||||
Id: "inv_123",
|
||||
PeriodStart: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
PeriodEnd: time.Date(2024, 2, 1, 0, 0, 0, 0, time.UTC),
|
||||
Type: "invoice",
|
||||
}
|
||||
|
||||
testInvoicePDF = api.InvoicePDFResponse{
|
||||
Url: "https://example.com/invoice.pdf",
|
||||
}
|
||||
)
|
||||
|
||||
func TestBilling_GetUsage_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/usage", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testUsageStats)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetUsage(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testUsageStats, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetUsage_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/usage", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetUsage(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetSubscription_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/subscription", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testSubscription)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetSubscription(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testSubscription, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetSubscription_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/subscription", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetSubscription(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetInvoices_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/invoices", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal([]api.InvoiceResponse{testInvoice})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetInvoices(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testInvoice, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetInvoices_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/invoices", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetInvoices(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetInvoicePDF_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/invoices/inv_123/pdf", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testInvoicePDF)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetInvoicePDF(context.Background(), "inv_123")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testInvoicePDF, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetInvoicePDF_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/invoices/inv_123/pdf", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetInvoicePDF(context.Background(), "inv_123")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetInvoiceCSV_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/invoices/inv_123/csv", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal("col1,col2\nval1,val2")
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetInvoiceCSV(context.Background(), "inv_123")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "col1,col2\nval1,val2", ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBilling_GetInvoiceCSV_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/billing/invoices/inv_123/csv", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Billing.GetInvoiceCSV(context.Background(), "inv_123")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
@@ -73,38 +73,6 @@ type Client struct {
|
||||
// Events NetBird Events APIs
|
||||
// see more: https://docs.netbird.io/api/resources/events
|
||||
Events *EventsAPI
|
||||
|
||||
// Billing NetBird Billing APIs for subscriptions, plans, and invoices
|
||||
// see more: https://docs.netbird.io/api/resources/billing
|
||||
Billing *BillingAPI
|
||||
|
||||
// MSP NetBird MSP tenant management APIs
|
||||
// see more: https://docs.netbird.io/api/resources/msp
|
||||
MSP *MSPAPI
|
||||
|
||||
// EDR NetBird EDR integration APIs (Intune, SentinelOne, Falcon, Huntress)
|
||||
// see more: https://docs.netbird.io/api/resources/edr
|
||||
EDR *EDRAPI
|
||||
|
||||
// SCIM NetBird SCIM IDP integration APIs
|
||||
// see more: https://docs.netbird.io/api/resources/scim
|
||||
SCIM *SCIMAPI
|
||||
|
||||
// EventStreaming NetBird Event Streaming integration APIs
|
||||
// see more: https://docs.netbird.io/api/resources/event-streaming
|
||||
EventStreaming *EventStreamingAPI
|
||||
|
||||
// IdentityProviders NetBird Identity Providers APIs
|
||||
// see more: https://docs.netbird.io/api/resources/identity-providers
|
||||
IdentityProviders *IdentityProvidersAPI
|
||||
|
||||
// Ingress NetBird Ingress Peers APIs
|
||||
// see more: https://docs.netbird.io/api/resources/ingress-ports
|
||||
Ingress *IngressAPI
|
||||
|
||||
// Instance NetBird Instance API
|
||||
// see more: https://docs.netbird.io/api/resources/instance
|
||||
Instance *InstanceAPI
|
||||
}
|
||||
|
||||
// New initialize new Client instance using PAT token
|
||||
@@ -152,14 +120,6 @@ func (c *Client) initialize() {
|
||||
c.DNSZones = &DNSZonesAPI{c}
|
||||
c.GeoLocation = &GeoLocationAPI{c}
|
||||
c.Events = &EventsAPI{c}
|
||||
c.Billing = &BillingAPI{c}
|
||||
c.MSP = &MSPAPI{c}
|
||||
c.EDR = &EDRAPI{c}
|
||||
c.SCIM = &SCIMAPI{c}
|
||||
c.EventStreaming = &EventStreamingAPI{c}
|
||||
c.IdentityProviders = &IdentityProvidersAPI{c}
|
||||
c.Ingress = &IngressAPI{c}
|
||||
c.Instance = &InstanceAPI{c}
|
||||
}
|
||||
|
||||
// NewRequest creates and executes new management API request
|
||||
|
||||
@@ -1,307 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// EDRAPI APIs for EDR integrations (Intune, SentinelOne, Falcon, Huntress)
|
||||
type EDRAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// GetIntuneIntegration retrieves the EDR Intune integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#get-intune-integration
|
||||
func (a *EDRAPI) GetIntuneIntegration(ctx context.Context) (*api.EDRIntuneResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/edr/intune", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRIntuneResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// CreateIntuneIntegration creates a new EDR Intune integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#create-intune-integration
|
||||
func (a *EDRAPI) CreateIntuneIntegration(ctx context.Context, request api.EDRIntuneRequest) (*api.EDRIntuneResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/edr/intune", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRIntuneResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// UpdateIntuneIntegration updates an existing EDR Intune integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#update-intune-integration
|
||||
func (a *EDRAPI) UpdateIntuneIntegration(ctx context.Context, request api.EDRIntuneRequest) (*api.EDRIntuneResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/integrations/edr/intune", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRIntuneResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// DeleteIntuneIntegration deletes the EDR Intune integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#delete-intune-integration
|
||||
func (a *EDRAPI) DeleteIntuneIntegration(ctx context.Context) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/integrations/edr/intune", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSentinelOneIntegration retrieves the EDR SentinelOne integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#get-sentinelone-integration
|
||||
func (a *EDRAPI) GetSentinelOneIntegration(ctx context.Context) (*api.EDRSentinelOneResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/edr/sentinelone", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRSentinelOneResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// CreateSentinelOneIntegration creates a new EDR SentinelOne integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#create-sentinelone-integration
|
||||
func (a *EDRAPI) CreateSentinelOneIntegration(ctx context.Context, request api.EDRSentinelOneRequest) (*api.EDRSentinelOneResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/edr/sentinelone", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRSentinelOneResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// UpdateSentinelOneIntegration updates an existing EDR SentinelOne integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#update-sentinelone-integration
|
||||
func (a *EDRAPI) UpdateSentinelOneIntegration(ctx context.Context, request api.EDRSentinelOneRequest) (*api.EDRSentinelOneResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/integrations/edr/sentinelone", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRSentinelOneResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// DeleteSentinelOneIntegration deletes the EDR SentinelOne integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#delete-sentinelone-integration
|
||||
func (a *EDRAPI) DeleteSentinelOneIntegration(ctx context.Context) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/integrations/edr/sentinelone", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetFalconIntegration retrieves the EDR Falcon integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#get-falcon-integration
|
||||
func (a *EDRAPI) GetFalconIntegration(ctx context.Context) (*api.EDRFalconResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/edr/falcon", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRFalconResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// CreateFalconIntegration creates a new EDR Falcon integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#create-falcon-integration
|
||||
func (a *EDRAPI) CreateFalconIntegration(ctx context.Context, request api.EDRFalconRequest) (*api.EDRFalconResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/edr/falcon", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRFalconResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// UpdateFalconIntegration updates an existing EDR Falcon integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#update-falcon-integration
|
||||
func (a *EDRAPI) UpdateFalconIntegration(ctx context.Context, request api.EDRFalconRequest) (*api.EDRFalconResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/integrations/edr/falcon", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRFalconResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// DeleteFalconIntegration deletes the EDR Falcon integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#delete-falcon-integration
|
||||
func (a *EDRAPI) DeleteFalconIntegration(ctx context.Context) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/integrations/edr/falcon", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetHuntressIntegration retrieves the EDR Huntress integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#get-huntress-integration
|
||||
func (a *EDRAPI) GetHuntressIntegration(ctx context.Context) (*api.EDRHuntressResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/edr/huntress", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRHuntressResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// CreateHuntressIntegration creates a new EDR Huntress integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#create-huntress-integration
|
||||
func (a *EDRAPI) CreateHuntressIntegration(ctx context.Context, request api.EDRHuntressRequest) (*api.EDRHuntressResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/edr/huntress", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRHuntressResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// UpdateHuntressIntegration updates an existing EDR Huntress integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#update-huntress-integration
|
||||
func (a *EDRAPI) UpdateHuntressIntegration(ctx context.Context, request api.EDRHuntressRequest) (*api.EDRHuntressResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/integrations/edr/huntress", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.EDRHuntressResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// DeleteHuntressIntegration deletes the EDR Huntress integration
|
||||
// See more: https://docs.netbird.io/api/resources/edr#delete-huntress-integration
|
||||
func (a *EDRAPI) DeleteHuntressIntegration(ctx context.Context) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/integrations/edr/huntress", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// BypassPeerCompliance bypasses compliance for a non-compliant peer
|
||||
// See more: https://docs.netbird.io/api/resources/edr#bypass-peer-compliance
|
||||
func (a *EDRAPI) BypassPeerCompliance(ctx context.Context, peerID string) (*api.BypassResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/peers/"+peerID+"/edr/bypass", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.BypassResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// RevokePeerBypass revokes the compliance bypass for a peer
|
||||
// See more: https://docs.netbird.io/api/resources/edr#revoke-peer-bypass
|
||||
func (a *EDRAPI) RevokePeerBypass(ctx context.Context, peerID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/peers/"+peerID+"/edr/bypass", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListBypassedPeers returns all peers that have compliance bypassed
|
||||
// See more: https://docs.netbird.io/api/resources/edr#list-all-bypassed-peers
|
||||
func (a *EDRAPI) ListBypassedPeers(ctx context.Context) ([]api.BypassResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/peers/edr/bypassed", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.BypassResponse](resp)
|
||||
return ret, err
|
||||
}
|
||||
@@ -1,422 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 (
|
||||
testIntuneResponse = api.EDRIntuneResponse{
|
||||
AccountId: "acc-1",
|
||||
ClientId: "client-1",
|
||||
TenantId: "tenant-1",
|
||||
Enabled: true,
|
||||
Id: 1,
|
||||
Groups: []api.Group{},
|
||||
LastSyncedInterval: 24,
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
LastSyncedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
CreatedBy: "user-1",
|
||||
}
|
||||
|
||||
testSentinelOneResponse = api.EDRSentinelOneResponse{
|
||||
AccountId: "acc-1",
|
||||
ApiUrl: "https://sentinelone.example.com",
|
||||
Enabled: true,
|
||||
Id: 2,
|
||||
Groups: []api.Group{},
|
||||
LastSyncedInterval: 24,
|
||||
MatchAttributes: api.SentinelOneMatchAttributes{},
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
LastSyncedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
CreatedBy: "user-1",
|
||||
}
|
||||
|
||||
testFalconResponse = api.EDRFalconResponse{
|
||||
AccountId: "acc-1",
|
||||
CloudId: "us-1",
|
||||
Enabled: true,
|
||||
Id: 3,
|
||||
Groups: []api.Group{},
|
||||
ZtaScoreThreshold: 50,
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
LastSyncedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
CreatedBy: "user-1",
|
||||
}
|
||||
|
||||
testHuntressResponse = api.EDRHuntressResponse{
|
||||
AccountId: "acc-1",
|
||||
Enabled: true,
|
||||
Id: 4,
|
||||
Groups: []api.Group{},
|
||||
LastSyncedInterval: 24,
|
||||
MatchAttributes: api.HuntressMatchAttributes{},
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
LastSyncedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
CreatedBy: "user-1",
|
||||
}
|
||||
|
||||
testBypassResponse = api.BypassResponse{
|
||||
PeerId: "peer-1",
|
||||
}
|
||||
)
|
||||
|
||||
// Intune tests
|
||||
|
||||
func TestEDR_GetIntuneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testIntuneResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.GetIntuneIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIntuneResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_GetIntuneIntegration_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.GetIntuneIntegration(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_CreateIntuneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.EDRIntuneRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "client-1", req.ClientId)
|
||||
retBytes, _ := json.Marshal(testIntuneResponse)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.CreateIntuneIntegration(context.Background(), api.EDRIntuneRequest{
|
||||
ClientId: "client-1",
|
||||
Secret: "secret",
|
||||
TenantId: "tenant-1",
|
||||
Groups: []string{"group-1"},
|
||||
LastSyncedInterval: 24,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIntuneResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_CreateIntuneIntegration_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.CreateIntuneIntegration(context.Background(), api.EDRIntuneRequest{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_UpdateIntuneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
retBytes, _ := json.Marshal(testIntuneResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.UpdateIntuneIntegration(context.Background(), api.EDRIntuneRequest{
|
||||
ClientId: "client-1",
|
||||
Secret: "new-secret",
|
||||
TenantId: "tenant-1",
|
||||
Groups: []string{"group-1"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIntuneResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_DeleteIntuneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.EDR.DeleteIntuneIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_DeleteIntuneIntegration_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/intune", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.EDR.DeleteIntuneIntegration(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
// SentinelOne tests
|
||||
|
||||
func TestEDR_GetSentinelOneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/sentinelone", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testSentinelOneResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.GetSentinelOneIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testSentinelOneResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_CreateSentinelOneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/sentinelone", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testSentinelOneResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.CreateSentinelOneIntegration(context.Background(), api.EDRSentinelOneRequest{
|
||||
ApiToken: "token",
|
||||
ApiUrl: "https://sentinelone.example.com",
|
||||
Groups: []string{"group-1"},
|
||||
LastSyncedInterval: 24,
|
||||
MatchAttributes: api.SentinelOneMatchAttributes{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testSentinelOneResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_DeleteSentinelOneIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/sentinelone", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.EDR.DeleteSentinelOneIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// Falcon tests
|
||||
|
||||
func TestEDR_GetFalconIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/falcon", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testFalconResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.GetFalconIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testFalconResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_CreateFalconIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/falcon", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testFalconResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.CreateFalconIntegration(context.Background(), api.EDRFalconRequest{
|
||||
ClientId: "client-1",
|
||||
Secret: "secret",
|
||||
CloudId: "us-1",
|
||||
Groups: []string{"group-1"},
|
||||
ZtaScoreThreshold: 50,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testFalconResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_DeleteFalconIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/falcon", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.EDR.DeleteFalconIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// Huntress tests
|
||||
|
||||
func TestEDR_GetHuntressIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/huntress", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testHuntressResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.GetHuntressIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testHuntressResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_CreateHuntressIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/huntress", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testHuntressResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.CreateHuntressIntegration(context.Background(), api.EDRHuntressRequest{
|
||||
ApiKey: "key",
|
||||
ApiSecret: "secret",
|
||||
Groups: []string{"group-1"},
|
||||
LastSyncedInterval: 24,
|
||||
MatchAttributes: api.HuntressMatchAttributes{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testHuntressResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_DeleteHuntressIntegration_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/edr/huntress", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.EDR.DeleteHuntressIntegration(context.Background())
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// Peer bypass tests
|
||||
|
||||
func TestEDR_BypassPeerCompliance_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/peer-1/edr/bypass", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testBypassResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.BypassPeerCompliance(context.Background(), "peer-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testBypassResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_BypassPeerCompliance_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/peer-1/edr/bypass", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Bad request", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.BypassPeerCompliance(context.Background(), "peer-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Bad request", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_RevokePeerBypass_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/peer-1/edr/bypass", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.EDR.RevokePeerBypass(context.Background(), "peer-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_RevokePeerBypass_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/peer-1/edr/bypass", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.EDR.RevokePeerBypass(context.Background(), "peer-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_ListBypassedPeers_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/edr/bypassed", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal([]api.BypassResponse{testBypassResponse})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.ListBypassedPeers(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testBypassResponse, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestEDR_ListBypassedPeers_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/edr/bypassed", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EDR.ListBypassedPeers(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// EventStreamingAPI APIs for event streaming integrations
|
||||
type EventStreamingAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// List retrieves all event streaming integrations
|
||||
// See more: https://docs.netbird.io/api/resources/event-streaming#list-all-event-streaming-integrations
|
||||
func (a *EventStreamingAPI) List(ctx context.Context) ([]api.IntegrationResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/event-streaming", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.IntegrationResponse](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// Get retrieves a specific event streaming integration by ID
|
||||
// See more: https://docs.netbird.io/api/resources/event-streaming#retrieve-an-event-streaming-integration
|
||||
func (a *EventStreamingAPI) Get(ctx context.Context, integrationID int) (*api.IntegrationResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/event-streaming/"+strconv.Itoa(integrationID), nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IntegrationResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Create creates a new event streaming integration
|
||||
// See more: https://docs.netbird.io/api/resources/event-streaming#create-an-event-streaming-integration
|
||||
func (a *EventStreamingAPI) Create(ctx context.Context, request api.CreateIntegrationRequest) (*api.IntegrationResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/event-streaming", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IntegrationResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Update updates an existing event streaming integration
|
||||
// See more: https://docs.netbird.io/api/resources/event-streaming#update-an-event-streaming-integration
|
||||
func (a *EventStreamingAPI) Update(ctx context.Context, integrationID int, request api.CreateIntegrationRequest) (*api.IntegrationResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/event-streaming/"+strconv.Itoa(integrationID), bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IntegrationResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Delete deletes an event streaming integration
|
||||
// See more: https://docs.netbird.io/api/resources/event-streaming#delete-an-event-streaming-integration
|
||||
func (a *EventStreamingAPI) Delete(ctx context.Context, integrationID int) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/event-streaming/"+strconv.Itoa(integrationID), nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 (
|
||||
testIntegrationResponse = api.IntegrationResponse{
|
||||
Id: ptr[int64](1),
|
||||
AccountId: ptr("acc-1"),
|
||||
Platform: (*api.IntegrationResponsePlatform)(ptr("datadog")),
|
||||
Enabled: ptr(true),
|
||||
Config: &map[string]string{"api_key": "****"},
|
||||
CreatedAt: ptr(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)),
|
||||
UpdatedAt: ptr(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)),
|
||||
}
|
||||
)
|
||||
|
||||
func TestEventStreaming_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal([]api.IntegrationResponse{testIntegrationResponse})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testIntegrationResponse, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Get_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testIntegrationResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.Get(context.Background(), 1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIntegrationResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Get_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.Get(context.Background(), 1)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Create_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.CreateIntegrationRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.CreateIntegrationRequestPlatformDatadog, req.Platform)
|
||||
assert.Equal(t, true, req.Enabled)
|
||||
retBytes, _ := json.Marshal(testIntegrationResponse)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.Create(context.Background(), api.CreateIntegrationRequest{
|
||||
Platform: api.CreateIntegrationRequestPlatformDatadog,
|
||||
Enabled: true,
|
||||
Config: map[string]string{"api_key": "test-key"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIntegrationResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Create_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.Create(context.Background(), api.CreateIntegrationRequest{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Update_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.CreateIntegrationRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, false, req.Enabled)
|
||||
retBytes, _ := json.Marshal(testIntegrationResponse)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.Update(context.Background(), 1, api.CreateIntegrationRequest{
|
||||
Platform: api.CreateIntegrationRequestPlatformDatadog,
|
||||
Enabled: false,
|
||||
Config: map[string]string{"api_key": "updated-key"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIntegrationResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Update_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.EventStreaming.Update(context.Background(), 1, api.CreateIntegrationRequest{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Delete_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.EventStreaming.Delete(context.Background(), 1)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEventStreaming_Delete_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/event-streaming/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.EventStreaming.Delete(context.Background(), 1)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
@@ -13,79 +11,10 @@ type EventsAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// NetworkTrafficOption options for ListNetworkTrafficEvents API
|
||||
type NetworkTrafficOption func(query map[string]string)
|
||||
|
||||
func NetworkTrafficPage(page int) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["page"] = fmt.Sprintf("%d", page)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficPageSize(pageSize int) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["page_size"] = fmt.Sprintf("%d", pageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficUserID(userID string) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["user_id"] = userID
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficReporterID(reporterID string) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["reporter_id"] = reporterID
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficProtocol(protocol int) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["protocol"] = fmt.Sprintf("%d", protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficType(t api.GetApiEventsNetworkTrafficParamsType) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["type"] = string(t)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficConnectionType(ct api.GetApiEventsNetworkTrafficParamsConnectionType) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["connection_type"] = string(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficDirection(d api.GetApiEventsNetworkTrafficParamsDirection) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["direction"] = string(d)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficSearch(search string) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["search"] = search
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficStartDate(t time.Time) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["start_date"] = t.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
|
||||
func NetworkTrafficEndDate(t time.Time) NetworkTrafficOption {
|
||||
return func(query map[string]string) {
|
||||
query["end_date"] = t.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
|
||||
// ListAuditEvents list all audit events
|
||||
// See more: https://docs.netbird.io/api/resources/events#list-all-audit-events
|
||||
func (a *EventsAPI) ListAuditEvents(ctx context.Context) ([]api.Event, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/events/audit", nil, nil)
|
||||
// List list all events
|
||||
// See more: https://docs.netbird.io/api/resources/events#list-all-events
|
||||
func (a *EventsAPI) List(ctx context.Context) ([]api.Event, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/events", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -95,21 +24,3 @@ func (a *EventsAPI) ListAuditEvents(ctx context.Context) ([]api.Event, error) {
|
||||
ret, err := parseResponse[[]api.Event](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// ListNetworkTrafficEvents list network traffic events
|
||||
// See more: https://docs.netbird.io/api/resources/events#list-network-traffic-events
|
||||
func (a *EventsAPI) ListNetworkTrafficEvents(ctx context.Context, opts ...NetworkTrafficOption) (*api.NetworkTrafficEventsResponse, error) {
|
||||
query := make(map[string]string)
|
||||
for _, o := range opts {
|
||||
o(query)
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/events/network-traffic", nil, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.NetworkTrafficEventsResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
@@ -21,76 +21,37 @@ var (
|
||||
Activity: "AccountCreate",
|
||||
ActivityCode: api.EventActivityCodeAccountCreate,
|
||||
}
|
||||
|
||||
testNetworkTrafficResponse = api.NetworkTrafficEventsResponse{
|
||||
Data: []api.NetworkTrafficEvent{},
|
||||
Page: 1,
|
||||
PageSize: 50,
|
||||
}
|
||||
)
|
||||
|
||||
func TestEvents_ListAuditEvents_200(t *testing.T) {
|
||||
func TestEvents_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/events/audit", func(w http.ResponseWriter, r *http.Request) {
|
||||
mux.HandleFunc("/api/events", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.Event{testEvent})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Events.ListAuditEvents(context.Background())
|
||||
ret, err := c.Events.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testEvent, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvents_ListAuditEvents_Err(t *testing.T) {
|
||||
func TestEvents_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/events/audit", func(w http.ResponseWriter, r *http.Request) {
|
||||
mux.HandleFunc("/api/events", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Events.ListAuditEvents(context.Background())
|
||||
ret, err := c.Events.List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvents_ListNetworkTrafficEvents_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/events/network-traffic", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "1", r.URL.Query().Get("page"))
|
||||
assert.Equal(t, "50", r.URL.Query().Get("page_size"))
|
||||
retBytes, _ := json.Marshal(testNetworkTrafficResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Events.ListNetworkTrafficEvents(context.Background(),
|
||||
rest.NetworkTrafficPage(1),
|
||||
rest.NetworkTrafficPageSize(50),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testNetworkTrafficResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvents_ListNetworkTrafficEvents_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/events/network-traffic", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Events.ListNetworkTrafficEvents(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvents_Integration(t *testing.T) {
|
||||
withBlackBoxServer(t, func(c *rest.Client) {
|
||||
// Do something that would trigger any event
|
||||
@@ -101,7 +62,7 @@ func TestEvents_Integration(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
events, err := c.Events.ListAuditEvents(context.Background())
|
||||
events, err := c.Events.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, events)
|
||||
})
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// IdentityProvidersAPI APIs for Identity Providers, do not use directly
|
||||
type IdentityProvidersAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// List all identity providers
|
||||
// See more: https://docs.netbird.io/api/resources/identity-providers#list-all-identity-providers
|
||||
func (a *IdentityProvidersAPI) List(ctx context.Context) ([]api.IdentityProvider, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/identity-providers", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.IdentityProvider](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// Get identity provider info
|
||||
// See more: https://docs.netbird.io/api/resources/identity-providers#retrieve-an-identity-provider
|
||||
func (a *IdentityProvidersAPI) Get(ctx context.Context, idpID string) (*api.IdentityProvider, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/identity-providers/"+idpID, nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IdentityProvider](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Create new identity provider
|
||||
// See more: https://docs.netbird.io/api/resources/identity-providers#create-an-identity-provider
|
||||
func (a *IdentityProvidersAPI) Create(ctx context.Context, request api.PostApiIdentityProvidersJSONRequestBody) (*api.IdentityProvider, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/identity-providers", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IdentityProvider](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Update update identity provider
|
||||
// See more: https://docs.netbird.io/api/resources/identity-providers#update-an-identity-provider
|
||||
func (a *IdentityProvidersAPI) Update(ctx context.Context, idpID string, request api.PutApiIdentityProvidersIdpIdJSONRequestBody) (*api.IdentityProvider, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/identity-providers/"+idpID, bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IdentityProvider](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Delete delete identity provider
|
||||
// See more: https://docs.netbird.io/api/resources/identity-providers#delete-an-identity-provider
|
||||
func (a *IdentityProvidersAPI) Delete(ctx context.Context, idpID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/identity-providers/"+idpID, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 testIdentityProvider = api.IdentityProvider{
|
||||
ClientId: "test-client-id",
|
||||
Id: ptr("Test"),
|
||||
}
|
||||
|
||||
func TestIdentityProviders_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.IdentityProvider{testIdentityProvider})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testIdentityProvider, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Get_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(testIdentityProvider)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.Get(context.Background(), "Test")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIdentityProvider, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Get_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.Get(context.Background(), "Test")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Create_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PostApiIdentityProvidersJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "new-client-id", req.ClientId)
|
||||
retBytes, _ := json.Marshal(testIdentityProvider)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.Create(context.Background(), api.PostApiIdentityProvidersJSONRequestBody{
|
||||
ClientId: "new-client-id",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIdentityProvider, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Create_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.Create(context.Background(), api.PostApiIdentityProvidersJSONRequestBody{
|
||||
ClientId: "new-client-id",
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Update_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PutApiIdentityProvidersIdpIdJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "updated-client-id", req.ClientId)
|
||||
retBytes, _ := json.Marshal(testIdentityProvider)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.Update(context.Background(), "Test", api.PutApiIdentityProvidersIdpIdJSONRequestBody{
|
||||
ClientId: "updated-client-id",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIdentityProvider, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Update_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.IdentityProviders.Update(context.Background(), "Test", api.PutApiIdentityProvidersIdpIdJSONRequestBody{
|
||||
ClientId: "updated-client-id",
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Delete_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.IdentityProviders.Delete(context.Background(), "Test")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIdentityProviders_Delete_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/identity-providers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.IdentityProviders.Delete(context.Background(), "Test")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// IngressAPI APIs for Ingress Peers, do not use directly
|
||||
type IngressAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// List all ingress peers
|
||||
// See more: https://docs.netbird.io/api/resources/ingress#list-all-ingress-peers
|
||||
func (a *IngressAPI) List(ctx context.Context) ([]api.IngressPeer, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/ingress/peers", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.IngressPeer](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// Get ingress peer info
|
||||
// See more: https://docs.netbird.io/api/resources/ingress#retrieve-an-ingress-peer
|
||||
func (a *IngressAPI) Get(ctx context.Context, ingressPeerID string) (*api.IngressPeer, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/ingress/peers/"+ingressPeerID, nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IngressPeer](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Create new ingress peer
|
||||
// See more: https://docs.netbird.io/api/resources/ingress#create-an-ingress-peer
|
||||
func (a *IngressAPI) Create(ctx context.Context, request api.PostApiIngressPeersJSONRequestBody) (*api.IngressPeer, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/ingress/peers", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IngressPeer](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Update update ingress peer
|
||||
// See more: https://docs.netbird.io/api/resources/ingress#update-an-ingress-peer
|
||||
func (a *IngressAPI) Update(ctx context.Context, ingressPeerID string, request api.PutApiIngressPeersIngressPeerIdJSONRequestBody) (*api.IngressPeer, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/ingress/peers/"+ingressPeerID, bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IngressPeer](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Delete delete ingress peer
|
||||
// See more: https://docs.netbird.io/api/resources/ingress#delete-an-ingress-peer
|
||||
func (a *IngressAPI) Delete(ctx context.Context, ingressPeerID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/ingress/peers/"+ingressPeerID, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 testIngressPeer = api.IngressPeer{
|
||||
Connected: true,
|
||||
Enabled: true,
|
||||
Id: "Test",
|
||||
}
|
||||
|
||||
func TestIngress_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.IngressPeer{testIngressPeer})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testIngressPeer, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Get_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(testIngressPeer)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.Get(context.Background(), "Test")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIngressPeer, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Get_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.Get(context.Background(), "Test")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Create_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PostApiIngressPeersJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "peer-id", req.PeerId)
|
||||
retBytes, _ := json.Marshal(testIngressPeer)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.Create(context.Background(), api.PostApiIngressPeersJSONRequestBody{
|
||||
PeerId: "peer-id",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIngressPeer, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Create_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.Create(context.Background(), api.PostApiIngressPeersJSONRequestBody{
|
||||
PeerId: "peer-id",
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Update_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PutApiIngressPeersIngressPeerIdJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, true, req.Enabled)
|
||||
retBytes, _ := json.Marshal(testIngressPeer)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.Update(context.Background(), "Test", api.PutApiIngressPeersIngressPeerIdJSONRequestBody{
|
||||
Enabled: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIngressPeer, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Update_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Ingress.Update(context.Background(), "Test", api.PutApiIngressPeersIngressPeerIdJSONRequestBody{
|
||||
Enabled: true,
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Delete_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.Ingress.Delete(context.Background(), "Test")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngress_Delete_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/ingress/peers/Test", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.Ingress.Delete(context.Background(), "Test")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// InstanceAPI APIs for Instance status and version, do not use directly
|
||||
type InstanceAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// GetStatus get instance status
|
||||
// See more: https://docs.netbird.io/api/resources/instance#get-instance-status
|
||||
func (a *InstanceAPI) GetStatus(ctx context.Context) (*api.InstanceStatus, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/instance", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.InstanceStatus](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Setup perform initial instance setup
|
||||
// See more: https://docs.netbird.io/api/resources/instance#setup-instance
|
||||
func (a *InstanceAPI) Setup(ctx context.Context, request api.PostApiSetupJSONRequestBody) (*api.SetupResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/setup", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.SetupResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 (
|
||||
testInstanceStatus = api.InstanceStatus{
|
||||
SetupRequired: true,
|
||||
}
|
||||
|
||||
testSetupResponse = api.SetupResponse{
|
||||
Email: "admin@example.com",
|
||||
UserId: "user-123",
|
||||
}
|
||||
)
|
||||
|
||||
func TestInstance_GetStatus_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/instance", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(testInstanceStatus)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Instance.GetStatus(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testInstanceStatus, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInstance_GetStatus_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/instance", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Instance.GetStatus(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInstance_Setup_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/setup", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PostApiSetupJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "admin@example.com", req.Email)
|
||||
retBytes, _ := json.Marshal(testSetupResponse)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Instance.Setup(context.Background(), api.PostApiSetupJSONRequestBody{
|
||||
Email: "admin@example.com",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testSetupResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInstance_Setup_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/setup", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Instance.Setup(context.Background(), api.PostApiSetupJSONRequestBody{
|
||||
Email: "admin@example.com",
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// MSPAPI APIs for MSP tenant management
|
||||
type MSPAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// ListTenants retrieves all MSP tenants
|
||||
// See more: https://docs.netbird.io/api/resources/msp#list-all-tenants
|
||||
func (a *MSPAPI) ListTenants(ctx context.Context) (*api.GetTenantsResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/msp/tenants", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.GetTenantsResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// CreateTenant creates a new MSP tenant
|
||||
// See more: https://docs.netbird.io/api/resources/msp#create-a-tenant
|
||||
func (a *MSPAPI) CreateTenant(ctx context.Context, request api.CreateTenantRequest) (*api.TenantResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/msp/tenants", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.TenantResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// UpdateTenant updates an existing MSP tenant
|
||||
// See more: https://docs.netbird.io/api/resources/msp#update-a-tenant
|
||||
func (a *MSPAPI) UpdateTenant(ctx context.Context, tenantID string, request api.UpdateTenantRequest) (*api.TenantResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/integrations/msp/tenants/"+tenantID, bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.TenantResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// DeleteTenant deletes an MSP tenant
|
||||
// See more: https://docs.netbird.io/api/resources/msp#delete-a-tenant
|
||||
func (a *MSPAPI) DeleteTenant(ctx context.Context, tenantID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/integrations/msp/tenants/"+tenantID, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnlinkTenant unlinks a tenant from the MSP account
|
||||
// See more: https://docs.netbird.io/api/resources/msp#unlink-a-tenant
|
||||
func (a *MSPAPI) UnlinkTenant(ctx context.Context, tenantID, owner string) error {
|
||||
params := map[string]string{"owner": owner}
|
||||
requestBytes, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/msp/tenants/"+tenantID+"/unlink", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyTenantDNS verifies a tenant domain DNS challenge
|
||||
// See more: https://docs.netbird.io/api/resources/msp#verify-tenant-dns
|
||||
func (a *MSPAPI) VerifyTenantDNS(ctx context.Context, tenantID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/msp/tenants/"+tenantID+"/dns", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InviteTenant invites an existing account as a tenant to the MSP account
|
||||
// See more: https://docs.netbird.io/api/resources/msp#invite-a-tenant
|
||||
func (a *MSPAPI) InviteTenant(ctx context.Context, tenantID string) (*api.TenantResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/msp/tenants/"+tenantID+"/invite", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.TenantResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 (
|
||||
testTenant = api.TenantResponse{
|
||||
Id: "tenant-1",
|
||||
Name: "Test Tenant",
|
||||
Domain: "test.example.com",
|
||||
DnsChallenge: "challenge-123",
|
||||
Status: "active",
|
||||
Groups: []api.TenantGroupResponse{},
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
)
|
||||
|
||||
func TestMSP_ListTenants_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal([]api.TenantResponse{testTenant})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.ListTenants(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, *ret, 1)
|
||||
assert.Equal(t, testTenant, (*ret)[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_ListTenants_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.ListTenants(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_CreateTenant_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.CreateTenantRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Test Tenant", req.Name)
|
||||
assert.Equal(t, "test.example.com", req.Domain)
|
||||
retBytes, _ := json.Marshal(testTenant)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.CreateTenant(context.Background(), api.CreateTenantRequest{
|
||||
Name: "Test Tenant",
|
||||
Domain: "test.example.com",
|
||||
Groups: []api.TenantGroupResponse{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testTenant, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_CreateTenant_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.CreateTenant(context.Background(), api.CreateTenantRequest{
|
||||
Name: "Test Tenant",
|
||||
Domain: "test.example.com",
|
||||
Groups: []api.TenantGroupResponse{},
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_UpdateTenant_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.UpdateTenantRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Updated Tenant", req.Name)
|
||||
retBytes, _ := json.Marshal(testTenant)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.UpdateTenant(context.Background(), "tenant-1", api.UpdateTenantRequest{
|
||||
Name: "Updated Tenant",
|
||||
Groups: []api.TenantGroupResponse{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testTenant, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_UpdateTenant_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.UpdateTenant(context.Background(), "tenant-1", api.UpdateTenantRequest{
|
||||
Name: "Updated Tenant",
|
||||
Groups: []api.TenantGroupResponse{},
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_DeleteTenant_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.MSP.DeleteTenant(context.Background(), "tenant-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_DeleteTenant_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.MSP.DeleteTenant(context.Background(), "tenant-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_UnlinkTenant_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1/unlink", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.MSP.UnlinkTenant(context.Background(), "tenant-1", "owner-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_UnlinkTenant_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1/unlink", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.MSP.UnlinkTenant(context.Background(), "tenant-1", "owner-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_VerifyTenantDNS_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1/dns", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.MSP.VerifyTenantDNS(context.Background(), "tenant-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_VerifyTenantDNS_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1/dns", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Failed", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.MSP.VerifyTenantDNS(context.Background(), "tenant-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Failed", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_InviteTenant_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1/invite", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testTenant)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.InviteTenant(context.Background(), "tenant-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testTenant, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMSP_InviteTenant_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/msp/tenants/tenant-1/invite", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.MSP.InviteTenant(context.Background(), "tenant-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
@@ -91,20 +91,6 @@ func (a *NetworksAPI) Delete(ctx context.Context, networkID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAllRouters list all routers across all networks
|
||||
// See more: https://docs.netbird.io/api/resources/networks#list-all-network-routers
|
||||
func (a *NetworksAPI) ListAllRouters(ctx context.Context) ([]api.NetworkRouter, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/networks/routers", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.NetworkRouter](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// NetworkResourcesAPI APIs for Network Resources, do not use directly
|
||||
type NetworkResourcesAPI struct {
|
||||
c *Client
|
||||
|
||||
@@ -219,35 +219,6 @@ func TestNetworks_Integration(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestNetworks_ListAllRouters_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/networks/routers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.NetworkRouter{testNetworkRouter})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Networks.ListAllRouters(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testNetworkRouter, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestNetworks_ListAllRouters_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/networks/routers", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Networks.ListAllRouters(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestNetworkResources_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/networks/Meow/resources", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -106,173 +106,3 @@ func (a *PeersAPI) ListAccessiblePeers(ctx context.Context, peerID string) ([]ap
|
||||
ret, err := parseResponse[[]api.Peer](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// CreateTemporaryAccess create temporary access for a peer
|
||||
// See more: https://docs.netbird.io/api/resources/peers#create-temporary-access
|
||||
func (a *PeersAPI) CreateTemporaryAccess(ctx context.Context, peerID string, request api.PostApiPeersPeerIdTemporaryAccessJSONRequestBody) (*api.PeerTemporaryAccessResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/peers/"+peerID+"/temporary-access", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.PeerTemporaryAccessResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// PeerIngressPortsAPI APIs for Peer Ingress Ports, do not use directly
|
||||
type PeerIngressPortsAPI struct {
|
||||
c *Client
|
||||
peerID string
|
||||
}
|
||||
|
||||
// IngressPorts APIs for peer ingress ports
|
||||
func (a *PeersAPI) IngressPorts(peerID string) *PeerIngressPortsAPI {
|
||||
return &PeerIngressPortsAPI{
|
||||
c: a.c,
|
||||
peerID: peerID,
|
||||
}
|
||||
}
|
||||
|
||||
// List list all ingress port allocations for a peer
|
||||
// See more: https://docs.netbird.io/api/resources/peers#list-all-ingress-port-allocations
|
||||
func (a *PeerIngressPortsAPI) List(ctx context.Context) ([]api.IngressPortAllocation, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/peers/"+a.peerID+"/ingress/ports", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.IngressPortAllocation](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// Get get ingress port allocation info
|
||||
// See more: https://docs.netbird.io/api/resources/peers#retrieve-an-ingress-port-allocation
|
||||
func (a *PeerIngressPortsAPI) Get(ctx context.Context, allocationID string) (*api.IngressPortAllocation, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/peers/"+a.peerID+"/ingress/ports/"+allocationID, nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IngressPortAllocation](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Create create new ingress port allocation
|
||||
// See more: https://docs.netbird.io/api/resources/peers#create-an-ingress-port-allocation
|
||||
func (a *PeerIngressPortsAPI) Create(ctx context.Context, request api.PostApiPeersPeerIdIngressPortsJSONRequestBody) (*api.IngressPortAllocation, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/peers/"+a.peerID+"/ingress/ports", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IngressPortAllocation](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Update update ingress port allocation
|
||||
// See more: https://docs.netbird.io/api/resources/peers#update-an-ingress-port-allocation
|
||||
func (a *PeerIngressPortsAPI) Update(ctx context.Context, allocationID string, request api.PutApiPeersPeerIdIngressPortsAllocationIdJSONRequestBody) (*api.IngressPortAllocation, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/peers/"+a.peerID+"/ingress/ports/"+allocationID, bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.IngressPortAllocation](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Delete delete ingress port allocation
|
||||
// See more: https://docs.netbird.io/api/resources/peers#delete-an-ingress-port-allocation
|
||||
func (a *PeerIngressPortsAPI) Delete(ctx context.Context, allocationID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/peers/"+a.peerID+"/ingress/ports/"+allocationID, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PeerJobsAPI APIs for Peer Jobs, do not use directly
|
||||
type PeerJobsAPI struct {
|
||||
c *Client
|
||||
peerID string
|
||||
}
|
||||
|
||||
// Jobs APIs for peer jobs
|
||||
func (a *PeersAPI) Jobs(peerID string) *PeerJobsAPI {
|
||||
return &PeerJobsAPI{
|
||||
c: a.c,
|
||||
peerID: peerID,
|
||||
}
|
||||
}
|
||||
|
||||
// List list all jobs for a peer
|
||||
// See more: https://docs.netbird.io/api/resources/peers#list-all-peer-jobs
|
||||
func (a *PeerJobsAPI) List(ctx context.Context) ([]api.JobResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/peers/"+a.peerID+"/jobs", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.JobResponse](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// Get get job info
|
||||
// See more: https://docs.netbird.io/api/resources/peers#retrieve-a-peer-job
|
||||
func (a *PeerJobsAPI) Get(ctx context.Context, jobID string) (*api.JobResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/peers/"+a.peerID+"/jobs/"+jobID, nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.JobResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Create create new job for a peer
|
||||
// See more: https://docs.netbird.io/api/resources/peers#create-a-peer-job
|
||||
func (a *PeerJobsAPI) Create(ctx context.Context, request api.PostApiPeersPeerIdJobsJSONRequestBody) (*api.JobResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/peers/"+a.peerID+"/jobs", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.JobResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
@@ -25,21 +25,6 @@ var (
|
||||
DnsLabel: "test",
|
||||
Id: "Test",
|
||||
}
|
||||
|
||||
testPeerTemporaryAccess = api.PeerTemporaryAccessResponse{
|
||||
Id: "Test",
|
||||
Name: "test-peer",
|
||||
}
|
||||
|
||||
testIngressPortAllocation = api.IngressPortAllocation{
|
||||
Enabled: true,
|
||||
Id: "alloc-1",
|
||||
}
|
||||
|
||||
testJobResponse = api.JobResponse{
|
||||
Id: "job-1",
|
||||
Status: "pending",
|
||||
}
|
||||
)
|
||||
|
||||
func TestPeers_List_200(t *testing.T) {
|
||||
@@ -192,264 +177,6 @@ func TestPeers_ListAccessiblePeers_Err(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeers_CreateTemporaryAccess_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/temporary-access", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testPeerTemporaryAccess)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.CreateTemporaryAccess(context.Background(), "Test", api.PostApiPeersPeerIdTemporaryAccessJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testPeerTemporaryAccess, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeers_CreateTemporaryAccess_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/temporary-access", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.CreateTemporaryAccess(context.Background(), "Test", api.PostApiPeersPeerIdTemporaryAccessJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.IngressPortAllocation{testIngressPortAllocation})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testIngressPortAllocation, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Get_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports/alloc-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(testIngressPortAllocation)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").Get(context.Background(), "alloc-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIngressPortAllocation, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Get_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports/alloc-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").Get(context.Background(), "alloc-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Create_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testIngressPortAllocation)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").Create(context.Background(), api.PostApiPeersPeerIdIngressPortsJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIngressPortAllocation, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Create_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").Create(context.Background(), api.PostApiPeersPeerIdIngressPortsJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Update_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports/alloc-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
retBytes, _ := json.Marshal(testIngressPortAllocation)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").Update(context.Background(), "alloc-1", api.PutApiPeersPeerIdIngressPortsAllocationIdJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIngressPortAllocation, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Update_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports/alloc-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.IngressPorts("Test").Update(context.Background(), "alloc-1", api.PutApiPeersPeerIdIngressPortsAllocationIdJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Delete_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports/alloc-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.Peers.IngressPorts("Test").Delete(context.Background(), "alloc-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerIngressPorts_Delete_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/ingress/ports/alloc-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.Peers.IngressPorts("Test").Delete(context.Background(), "alloc-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerJobs_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/jobs", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.JobResponse{testJobResponse})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.Jobs("Test").List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testJobResponse.Id, ret[0].Id)
|
||||
assert.Equal(t, testJobResponse.Status, ret[0].Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerJobs_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/jobs", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.Jobs("Test").List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerJobs_Get_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/jobs/job-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(testJobResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.Jobs("Test").Get(context.Background(), "job-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testJobResponse.Id, ret.Id)
|
||||
assert.Equal(t, testJobResponse.Status, ret.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerJobs_Get_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/jobs/job-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.Jobs("Test").Get(context.Background(), "job-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerJobs_Create_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/jobs", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testJobResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.Jobs("Test").Create(context.Background(), api.PostApiPeersPeerIdJobsJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testJobResponse.Id, ret.Id)
|
||||
assert.Equal(t, testJobResponse.Status, ret.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerJobs_Create_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/peers/Test/jobs", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Peers.Jobs("Test").Create(context.Background(), api.PostApiPeersPeerIdJobsJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeers_Integration(t *testing.T) {
|
||||
withBlackBoxServer(t, func(c *rest.Client) {
|
||||
peers, err := c.Peers.List(context.Background())
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/management/http/api"
|
||||
)
|
||||
|
||||
// SCIMAPI APIs for SCIM IDP integrations
|
||||
type SCIMAPI struct {
|
||||
c *Client
|
||||
}
|
||||
|
||||
// List retrieves all SCIM IDP integrations
|
||||
// See more: https://docs.netbird.io/api/resources/scim#list-all-scim-integrations
|
||||
func (a *SCIMAPI) List(ctx context.Context) ([]api.ScimIntegration, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/scim-idp", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.ScimIntegration](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// Get retrieves a specific SCIM IDP integration by ID
|
||||
// See more: https://docs.netbird.io/api/resources/scim#retrieve-a-scim-integration
|
||||
func (a *SCIMAPI) Get(ctx context.Context, integrationID string) (*api.ScimIntegration, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/scim-idp/"+integrationID, nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.ScimIntegration](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Create creates a new SCIM IDP integration
|
||||
// See more: https://docs.netbird.io/api/resources/scim#create-a-scim-integration
|
||||
func (a *SCIMAPI) Create(ctx context.Context, request api.CreateScimIntegrationRequest) (*api.ScimIntegration, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/scim-idp", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.ScimIntegration](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Update updates an existing SCIM IDP integration
|
||||
// See more: https://docs.netbird.io/api/resources/scim#update-a-scim-integration
|
||||
func (a *SCIMAPI) Update(ctx context.Context, integrationID string, request api.UpdateScimIntegrationRequest) (*api.ScimIntegration, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/integrations/scim-idp/"+integrationID, bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.ScimIntegration](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Delete deletes a SCIM IDP integration
|
||||
// See more: https://docs.netbird.io/api/resources/scim#delete-a-scim-integration
|
||||
func (a *SCIMAPI) Delete(ctx context.Context, integrationID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/integrations/scim-idp/"+integrationID, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegenerateToken regenerates the SCIM API token for an integration
|
||||
// See more: https://docs.netbird.io/api/resources/scim#regenerate-scim-token
|
||||
func (a *SCIMAPI) RegenerateToken(ctx context.Context, integrationID string) (*api.ScimTokenResponse, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/integrations/scim-idp/"+integrationID+"/token", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.ScimTokenResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// GetLogs retrieves synchronization logs for an SCIM IDP integration
|
||||
// See more: https://docs.netbird.io/api/resources/scim#get-scim-sync-logs
|
||||
func (a *SCIMAPI) GetLogs(ctx context.Context, integrationID string) ([]api.IdpIntegrationSyncLog, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/integrations/scim-idp/"+integrationID+"/logs", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.IdpIntegrationSyncLog](resp)
|
||||
return ret, err
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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 (
|
||||
testScimIntegration = api.ScimIntegration{
|
||||
Id: 1,
|
||||
AuthToken: "****",
|
||||
Enabled: true,
|
||||
GroupPrefixes: []string{"eng-"},
|
||||
UserGroupPrefixes: []string{"dev-"},
|
||||
Provider: "okta",
|
||||
LastSyncedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
|
||||
testScimToken = api.ScimTokenResponse{
|
||||
AuthToken: "new-token-123",
|
||||
}
|
||||
|
||||
testSyncLog = api.IdpIntegrationSyncLog{
|
||||
Id: 1,
|
||||
Level: "info",
|
||||
Message: "Sync completed",
|
||||
Timestamp: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
)
|
||||
|
||||
func TestSCIM_List_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal([]api.ScimIntegration{testScimIntegration})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testScimIntegration, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_List_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.List(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Get_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal(testScimIntegration)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.Get(context.Background(), "int-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testScimIntegration, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Get_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.Get(context.Background(), "int-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Create_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.CreateScimIntegrationRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "okta", req.Provider)
|
||||
assert.Equal(t, "scim-", req.Prefix)
|
||||
retBytes, _ := json.Marshal(testScimIntegration)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.Create(context.Background(), api.CreateScimIntegrationRequest{
|
||||
Provider: "okta",
|
||||
Prefix: "scim-",
|
||||
GroupPrefixes: &[]string{"eng-"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testScimIntegration, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Create_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.Create(context.Background(), api.CreateScimIntegrationRequest{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Update_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.UpdateScimIntegrationRequest
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, true, *req.Enabled)
|
||||
retBytes, _ := json.Marshal(testScimIntegration)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.Update(context.Background(), "int-1", api.UpdateScimIntegrationRequest{
|
||||
Enabled: ptr(true),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testScimIntegration, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Update_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.Update(context.Background(), "int-1", api.UpdateScimIntegrationRequest{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Delete_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.SCIM.Delete(context.Background(), "int-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_Delete_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.SCIM.Delete(context.Background(), "int-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_RegenerateToken_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testScimToken)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.RegenerateToken(context.Background(), "int-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testScimToken, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_RegenerateToken_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.RegenerateToken(context.Background(), "int-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_GetLogs_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1/logs", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "GET", r.Method)
|
||||
retBytes, _ := json.Marshal([]api.IdpIntegrationSyncLog{testSyncLog})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.GetLogs(context.Background(), "int-1")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testSyncLog, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestSCIM_GetLogs_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/integrations/scim-idp/int-1/logs", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.SCIM.GetLogs(context.Background(), "int-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
@@ -105,145 +105,3 @@ func (a *UsersAPI) Current(ctx context.Context) (*api.User, error) {
|
||||
ret, err := parseResponse[api.User](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// ListInvites list all user invites
|
||||
// See more: https://docs.netbird.io/api/resources/users#list-all-user-invites
|
||||
func (a *UsersAPI) ListInvites(ctx context.Context) ([]api.UserInvite, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/users/invites", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[[]api.UserInvite](resp)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
// CreateInvite create a user invite
|
||||
// See more: https://docs.netbird.io/api/resources/users#create-a-user-invite
|
||||
func (a *UsersAPI) CreateInvite(ctx context.Context, request api.PostApiUsersInvitesJSONRequestBody) (*api.UserInvite, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/users/invites", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.UserInvite](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// DeleteInvite delete a user invite
|
||||
// See more: https://docs.netbird.io/api/resources/users#delete-a-user-invite
|
||||
func (a *UsersAPI) DeleteInvite(ctx context.Context, inviteID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/users/invites/"+inviteID, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegenerateInvite regenerate a user invite token
|
||||
// See more: https://docs.netbird.io/api/resources/users#regenerate-a-user-invite
|
||||
func (a *UsersAPI) RegenerateInvite(ctx context.Context, inviteID string, request api.PostApiUsersInvitesInviteIdRegenerateJSONRequestBody) (*api.UserInviteRegenerateResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/users/invites/"+inviteID+"/regenerate", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.UserInviteRegenerateResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// GetInviteByToken get a user invite by token
|
||||
// See more: https://docs.netbird.io/api/resources/users#get-a-user-invite-by-token
|
||||
func (a *UsersAPI) GetInviteByToken(ctx context.Context, token string) (*api.UserInviteInfo, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "GET", "/api/users/invites/"+token, nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.UserInviteInfo](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// AcceptInvite accept a user invite
|
||||
// See more: https://docs.netbird.io/api/resources/users#accept-a-user-invite
|
||||
func (a *UsersAPI) AcceptInvite(ctx context.Context, token string, request api.PostApiUsersInvitesTokenAcceptJSONRequestBody) (*api.UserInviteAcceptResponse, error) {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/users/invites/"+token+"/accept", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.UserInviteAcceptResponse](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// Approve approve a pending user
|
||||
// See more: https://docs.netbird.io/api/resources/users#approve-a-user
|
||||
func (a *UsersAPI) Approve(ctx context.Context, userID string) (*api.User, error) {
|
||||
resp, err := a.c.NewRequest(ctx, "POST", "/api/users/"+userID+"/approve", nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
ret, err := parseResponse[api.User](resp)
|
||||
return &ret, err
|
||||
}
|
||||
|
||||
// ChangePassword change a user's password
|
||||
// See more: https://docs.netbird.io/api/resources/users#change-user-password
|
||||
func (a *UsersAPI) ChangePassword(ctx context.Context, userID string, request api.PutApiUsersUserIdPasswordJSONRequestBody) error {
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := a.c.NewRequest(ctx, "PUT", "/api/users/"+userID+"/password", bytes.NewReader(requestBytes), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reject reject a pending user
|
||||
// See more: https://docs.netbird.io/api/resources/users#reject-a-user
|
||||
func (a *UsersAPI) Reject(ctx context.Context, userID string) error {
|
||||
resp, err := a.c.NewRequest(ctx, "DELETE", "/api/users/"+userID+"/reject", nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -32,23 +32,6 @@ var (
|
||||
Role: "user",
|
||||
Status: api.UserStatusActive,
|
||||
}
|
||||
|
||||
testUserInvite = api.UserInvite{
|
||||
AutoGroups: []string{"group1"},
|
||||
Id: "invite-1",
|
||||
}
|
||||
|
||||
testUserInviteInfo = api.UserInviteInfo{
|
||||
Email: "invite@test.com",
|
||||
}
|
||||
|
||||
testUserInviteAcceptResponse = api.UserInviteAcceptResponse{
|
||||
Success: true,
|
||||
}
|
||||
|
||||
testUserInviteRegenerateResponse = api.UserInviteRegenerateResponse{
|
||||
InviteToken: "new-token",
|
||||
}
|
||||
)
|
||||
|
||||
func TestUsers_List_200(t *testing.T) {
|
||||
@@ -237,269 +220,6 @@ func TestUsers_Current_Err(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_ListInvites_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal([]api.UserInvite{testUserInvite})
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.ListInvites(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ret, 1)
|
||||
assert.Equal(t, testUserInvite, ret[0])
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_ListInvites_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.ListInvites(context.Background())
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_CreateInvite_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PostApiUsersInvitesJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "invite@test.com", req.Email)
|
||||
retBytes, _ := json.Marshal(testUserInvite)
|
||||
_, err = w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.CreateInvite(context.Background(), api.PostApiUsersInvitesJSONRequestBody{
|
||||
Email: "invite@test.com",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testUserInvite, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_CreateInvite_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.CreateInvite(context.Background(), api.PostApiUsersInvitesJSONRequestBody{
|
||||
Email: "invite@test.com",
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_DeleteInvite_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/invite-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.Users.DeleteInvite(context.Background(), "invite-1")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_DeleteInvite_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/invite-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "Not found", Code: 404})
|
||||
w.WriteHeader(404)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.Users.DeleteInvite(context.Background(), "invite-1")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "Not found", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_RegenerateInvite_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/invite-1/regenerate", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testUserInviteRegenerateResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.RegenerateInvite(context.Background(), "invite-1", api.PostApiUsersInvitesInviteIdRegenerateJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testUserInviteRegenerateResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_RegenerateInvite_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/invite-1/regenerate", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.RegenerateInvite(context.Background(), "invite-1", api.PostApiUsersInvitesInviteIdRegenerateJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_GetInviteByToken_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/some-token", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(testUserInviteInfo)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.GetInviteByToken(context.Background(), "some-token")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testUserInviteInfo, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_GetInviteByToken_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/some-token", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.GetInviteByToken(context.Background(), "some-token")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Empty(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_AcceptInvite_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/some-token/accept", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testUserInviteAcceptResponse)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.AcceptInvite(context.Background(), "some-token", api.PostApiUsersInvitesTokenAcceptJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testUserInviteAcceptResponse, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_AcceptInvite_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/invites/some-token/accept", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.AcceptInvite(context.Background(), "some-token", api.PostApiUsersInvitesTokenAcceptJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_Approve_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/Test/approve", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "POST", r.Method)
|
||||
retBytes, _ := json.Marshal(testUser)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.Approve(context.Background(), "Test")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testUser, *ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_Approve_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/Test/approve", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
ret, err := c.Users.Approve(context.Background(), "Test")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
assert.Nil(t, ret)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_ChangePassword_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/Test/password", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "PUT", r.Method)
|
||||
reqBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
var req api.PutApiUsersUserIdPasswordJSONRequestBody
|
||||
err = json.Unmarshal(reqBytes, &req)
|
||||
require.NoError(t, err)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.Users.ChangePassword(context.Background(), "Test", api.PutApiUsersUserIdPasswordJSONRequestBody{})
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_ChangePassword_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/Test/password", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.Users.ChangePassword(context.Background(), "Test", api.PutApiUsersUserIdPasswordJSONRequestBody{})
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_Reject_200(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/Test/reject", func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "DELETE", r.Method)
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
err := c.Users.Reject(context.Background(), "Test")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_Reject_Err(t *testing.T) {
|
||||
withMockClient(func(c *rest.Client, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/users/Test/reject", func(w http.ResponseWriter, r *http.Request) {
|
||||
retBytes, _ := json.Marshal(util.ErrorResponse{Message: "No", Code: 400})
|
||||
w.WriteHeader(400)
|
||||
_, err := w.Write(retBytes)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
err := c.Users.Reject(context.Background(), "Test")
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "No", err.Error())
|
||||
})
|
||||
}
|
||||
|
||||
func TestUsers_Integration(t *testing.T) {
|
||||
withBlackBoxServer(t, func(c *rest.Client) {
|
||||
// rest client PAT is owner's
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,14 +16,6 @@ const (
|
||||
TokenAuthScopes = "TokenAuth.Scopes"
|
||||
)
|
||||
|
||||
// Defines values for CreateIntegrationRequestPlatform.
|
||||
const (
|
||||
CreateIntegrationRequestPlatformDatadog CreateIntegrationRequestPlatform = "datadog"
|
||||
CreateIntegrationRequestPlatformFirehose CreateIntegrationRequestPlatform = "firehose"
|
||||
CreateIntegrationRequestPlatformGenericHttp CreateIntegrationRequestPlatform = "generic_http"
|
||||
CreateIntegrationRequestPlatformS3 CreateIntegrationRequestPlatform = "s3"
|
||||
)
|
||||
|
||||
// Defines values for DNSRecordType.
|
||||
const (
|
||||
DNSRecordTypeA DNSRecordType = "A"
|
||||
@@ -199,20 +191,6 @@ const (
|
||||
IngressPortAllocationRequestPortRangeProtocolUdp IngressPortAllocationRequestPortRangeProtocol = "udp"
|
||||
)
|
||||
|
||||
// Defines values for IntegrationResponsePlatform.
|
||||
const (
|
||||
IntegrationResponsePlatformDatadog IntegrationResponsePlatform = "datadog"
|
||||
IntegrationResponsePlatformFirehose IntegrationResponsePlatform = "firehose"
|
||||
IntegrationResponsePlatformGenericHttp IntegrationResponsePlatform = "generic_http"
|
||||
IntegrationResponsePlatformS3 IntegrationResponsePlatform = "s3"
|
||||
)
|
||||
|
||||
// Defines values for InvoiceResponseType.
|
||||
const (
|
||||
InvoiceResponseTypeAccount InvoiceResponseType = "account"
|
||||
InvoiceResponseTypeTenants InvoiceResponseType = "tenants"
|
||||
)
|
||||
|
||||
// Defines values for JobResponseStatus.
|
||||
const (
|
||||
JobResponseStatusFailed JobResponseStatus = "failed"
|
||||
@@ -297,13 +275,6 @@ const (
|
||||
ReverseProxyDomainTypeFree ReverseProxyDomainType = "free"
|
||||
)
|
||||
|
||||
// Defines values for SentinelOneMatchAttributesNetworkStatus.
|
||||
const (
|
||||
SentinelOneMatchAttributesNetworkStatusConnected SentinelOneMatchAttributesNetworkStatus = "connected"
|
||||
SentinelOneMatchAttributesNetworkStatusDisconnected SentinelOneMatchAttributesNetworkStatus = "disconnected"
|
||||
SentinelOneMatchAttributesNetworkStatusQuarantined SentinelOneMatchAttributesNetworkStatus = "quarantined"
|
||||
)
|
||||
|
||||
// Defines values for ServiceMetaStatus.
|
||||
const (
|
||||
ServiceMetaStatusActive ServiceMetaStatus = "active"
|
||||
@@ -326,14 +297,6 @@ const (
|
||||
ServiceTargetTargetTypeResource ServiceTargetTargetType = "resource"
|
||||
)
|
||||
|
||||
// Defines values for TenantResponseStatus.
|
||||
const (
|
||||
TenantResponseStatusActive TenantResponseStatus = "active"
|
||||
TenantResponseStatusExisting TenantResponseStatus = "existing"
|
||||
TenantResponseStatusInvited TenantResponseStatus = "invited"
|
||||
TenantResponseStatusPending TenantResponseStatus = "pending"
|
||||
)
|
||||
|
||||
// Defines values for UserStatus.
|
||||
const (
|
||||
UserStatusActive UserStatus = "active"
|
||||
@@ -384,12 +347,6 @@ const (
|
||||
GetApiEventsProxyParamsStatusSuccess GetApiEventsProxyParamsStatus = "success"
|
||||
)
|
||||
|
||||
// Defines values for PutApiIntegrationsMspTenantsIdInviteJSONBodyValue.
|
||||
const (
|
||||
PutApiIntegrationsMspTenantsIdInviteJSONBodyValueAccept PutApiIntegrationsMspTenantsIdInviteJSONBodyValue = "accept"
|
||||
PutApiIntegrationsMspTenantsIdInviteJSONBodyValueDecline PutApiIntegrationsMspTenantsIdInviteJSONBodyValue = "decline"
|
||||
)
|
||||
|
||||
// AccessiblePeer defines model for AccessiblePeer.
|
||||
type AccessiblePeer struct {
|
||||
// CityName Commonly used English name of the city
|
||||
@@ -590,21 +547,6 @@ type BundleWorkloadResponse struct {
|
||||
Type WorkloadType `json:"type"`
|
||||
}
|
||||
|
||||
// BypassResponse Response for bypassed peer operations.
|
||||
type BypassResponse struct {
|
||||
// PeerId The ID of the bypassed peer.
|
||||
PeerId string `json:"peer_id"`
|
||||
}
|
||||
|
||||
// CheckoutResponse defines model for CheckoutResponse.
|
||||
type CheckoutResponse struct {
|
||||
// SessionId The unique identifier for the checkout session.
|
||||
SessionId string `json:"session_id"`
|
||||
|
||||
// Url URL to redirect the user to the checkout session.
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
// Checks List of objects that perform the actual checks
|
||||
type Checks struct {
|
||||
// GeoLocationCheck Posture check for geo location
|
||||
@@ -647,36 +589,6 @@ type Country struct {
|
||||
// CountryCode 2-letter ISO 3166-1 alpha-2 code that represents the country
|
||||
type CountryCode = string
|
||||
|
||||
// CreateIntegrationRequest Request payload for creating a new event streaming integration. Also used as the structure for the PUT request body, but not all fields are applicable for updates (see PUT operation description).
|
||||
type CreateIntegrationRequest struct {
|
||||
// Config Platform-specific configuration as key-value pairs. For creation, all necessary credentials and settings must be provided. For updates, provide the fields to change or the entire new configuration.
|
||||
Config map[string]string `json:"config"`
|
||||
|
||||
// Enabled Specifies whether the integration is enabled. During creation (POST), this value is sent by the client, but the provided backend manager function `CreateIntegration` does not appear to use it directly, so its effect on creation should be verified. During updates (PUT), this field is used to enable or disable the integration.
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Platform The event streaming platform to integrate with (e.g., "datadog", "s3", "firehose"). This field is used for creation. For updates (PUT), this field, if sent, is ignored by the backend.
|
||||
Platform CreateIntegrationRequestPlatform `json:"platform"`
|
||||
}
|
||||
|
||||
// CreateIntegrationRequestPlatform The event streaming platform to integrate with (e.g., "datadog", "s3", "firehose"). This field is used for creation. For updates (PUT), this field, if sent, is ignored by the backend.
|
||||
type CreateIntegrationRequestPlatform string
|
||||
|
||||
// CreateScimIntegrationRequest Request payload for creating an SCIM IDP integration
|
||||
type CreateScimIntegrationRequest struct {
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes *[]string `json:"group_prefixes,omitempty"`
|
||||
|
||||
// Prefix The connection prefix used for the SCIM provider
|
||||
Prefix string `json:"prefix"`
|
||||
|
||||
// Provider Name of the SCIM identity provider
|
||||
Provider string `json:"provider"`
|
||||
|
||||
// UserGroupPrefixes List of start_with string patterns for groups which users to sync
|
||||
UserGroupPrefixes *[]string `json:"user_group_prefixes,omitempty"`
|
||||
}
|
||||
|
||||
// CreateSetupKeyRequest defines model for CreateSetupKeyRequest.
|
||||
type CreateSetupKeyRequest struct {
|
||||
// AllowExtraDnsLabels Allow extra DNS labels to be added to the peer
|
||||
@@ -701,24 +613,6 @@ type CreateSetupKeyRequest struct {
|
||||
UsageLimit int `json:"usage_limit"`
|
||||
}
|
||||
|
||||
// CreateTenantRequest defines model for CreateTenantRequest.
|
||||
type CreateTenantRequest struct {
|
||||
// Domain The name for the MSP tenant
|
||||
Domain string `json:"domain"`
|
||||
|
||||
// Groups MSP users Groups that can access the Tenant and Roles to assume
|
||||
Groups []TenantGroupResponse `json:"groups"`
|
||||
|
||||
// Name The name for the MSP tenant
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// DNSChallengeResponse defines model for DNSChallengeResponse.
|
||||
type DNSChallengeResponse struct {
|
||||
// DnsChallenge The DNS challenge to set in a TXT record
|
||||
DnsChallenge string `json:"dns_challenge"`
|
||||
}
|
||||
|
||||
// DNSRecord defines model for DNSRecord.
|
||||
type DNSRecord struct {
|
||||
// Content DNS record content (IP address for A/AAAA, domain for CNAME)
|
||||
@@ -761,234 +655,6 @@ type DNSSettings struct {
|
||||
DisabledManagementGroups []string `json:"disabled_management_groups"`
|
||||
}
|
||||
|
||||
// EDRFalconRequest Request payload for creating or updating a EDR Falcon integration
|
||||
type EDRFalconRequest struct {
|
||||
// ClientId CrowdStrike API client ID
|
||||
ClientId string `json:"client_id"`
|
||||
|
||||
// CloudId CrowdStrike cloud identifier (e.g., "us-1", "us-2", "eu-1")
|
||||
CloudId string `json:"cloud_id"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// Groups The Groups this integration applies to
|
||||
Groups []string `json:"groups"`
|
||||
|
||||
// Secret CrowdStrike API client secret
|
||||
Secret string `json:"secret"`
|
||||
|
||||
// ZtaScoreThreshold The minimum Zero Trust Assessment score required for agent approval (0-100)
|
||||
ZtaScoreThreshold int `json:"zta_score_threshold"`
|
||||
}
|
||||
|
||||
// EDRFalconResponse Represents a Falcon EDR integration
|
||||
type EDRFalconResponse struct {
|
||||
// AccountId The identifier of the account this integration belongs to.
|
||||
AccountId string `json:"account_id"`
|
||||
|
||||
// CloudId CrowdStrike cloud identifier
|
||||
CloudId string `json:"cloud_id"`
|
||||
|
||||
// CreatedAt Timestamp of when the integration was created.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// CreatedBy The user id that created the integration
|
||||
CreatedBy string `json:"created_by"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Groups List of groups
|
||||
Groups []Group `json:"groups"`
|
||||
|
||||
// Id The unique numeric identifier for the integration.
|
||||
Id int64 `json:"id"`
|
||||
|
||||
// LastSyncedAt Timestamp of when the integration was last synced.
|
||||
LastSyncedAt time.Time `json:"last_synced_at"`
|
||||
|
||||
// UpdatedAt Timestamp of when the integration was last updated.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// ZtaScoreThreshold The minimum Zero Trust Assessment score required for agent approval (0-100)
|
||||
ZtaScoreThreshold int `json:"zta_score_threshold"`
|
||||
}
|
||||
|
||||
// EDRHuntressRequest Request payload for creating or updating a EDR Huntress integration
|
||||
type EDRHuntressRequest struct {
|
||||
// ApiKey Huntress API key
|
||||
ApiKey string `json:"api_key"`
|
||||
|
||||
// ApiSecret Huntress API secret
|
||||
ApiSecret string `json:"api_secret"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// Groups The Groups this integrations applies to
|
||||
Groups []string `json:"groups"`
|
||||
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours. Minimum value is 24 hours
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// MatchAttributes Attribute conditions to match when approving agents
|
||||
MatchAttributes HuntressMatchAttributes `json:"match_attributes"`
|
||||
}
|
||||
|
||||
// EDRHuntressResponse Represents a Huntress EDR integration configuration
|
||||
type EDRHuntressResponse struct {
|
||||
// AccountId The identifier of the account this integration belongs to.
|
||||
AccountId string `json:"account_id"`
|
||||
|
||||
// CreatedAt Timestamp of when the integration was created.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// CreatedBy The user id that created the integration
|
||||
CreatedBy string `json:"created_by"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Groups List of groups
|
||||
Groups []Group `json:"groups"`
|
||||
|
||||
// Id The unique numeric identifier for the integration.
|
||||
Id int64 `json:"id"`
|
||||
|
||||
// LastSyncedAt Timestamp of when the integration was last synced.
|
||||
LastSyncedAt time.Time `json:"last_synced_at"`
|
||||
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours.
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// MatchAttributes Attribute conditions to match when approving agents
|
||||
MatchAttributes HuntressMatchAttributes `json:"match_attributes"`
|
||||
|
||||
// UpdatedAt Timestamp of when the integration was last updated.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// EDRIntuneRequest Request payload for creating or updating a EDR Intune integration.
|
||||
type EDRIntuneRequest struct {
|
||||
// ClientId The Azure application client id
|
||||
ClientId string `json:"client_id"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// Groups The Groups this integrations applies to
|
||||
Groups []string `json:"groups"`
|
||||
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours. Minimum value is 24 hours.
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// Secret The Azure application client secret
|
||||
Secret string `json:"secret"`
|
||||
|
||||
// TenantId The Azure tenant id
|
||||
TenantId string `json:"tenant_id"`
|
||||
}
|
||||
|
||||
// EDRIntuneResponse Represents a Intune EDR integration configuration
|
||||
type EDRIntuneResponse struct {
|
||||
// AccountId The identifier of the account this integration belongs to.
|
||||
AccountId string `json:"account_id"`
|
||||
|
||||
// ClientId The Azure application client id
|
||||
ClientId string `json:"client_id"`
|
||||
|
||||
// CreatedAt Timestamp of when the integration was created.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// CreatedBy The user id that created the integration
|
||||
CreatedBy string `json:"created_by"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Groups List of groups
|
||||
Groups []Group `json:"groups"`
|
||||
|
||||
// Id The unique numeric identifier for the integration.
|
||||
Id int64 `json:"id"`
|
||||
|
||||
// LastSyncedAt Timestamp of when the integration was last synced.
|
||||
LastSyncedAt time.Time `json:"last_synced_at"`
|
||||
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours.
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// TenantId The Azure tenant id
|
||||
TenantId string `json:"tenant_id"`
|
||||
|
||||
// UpdatedAt Timestamp of when the integration was last updated.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// EDRSentinelOneRequest Request payload for creating or updating a EDR SentinelOne integration
|
||||
type EDRSentinelOneRequest struct {
|
||||
// ApiToken SentinelOne API token
|
||||
ApiToken string `json:"api_token"`
|
||||
|
||||
// ApiUrl The Base URL of SentinelOne API
|
||||
ApiUrl string `json:"api_url"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// Groups The Groups this integrations applies to
|
||||
Groups []string `json:"groups"`
|
||||
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours. Minimum value is 24 hours.
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// MatchAttributes Attribute conditions to match when approving agents
|
||||
MatchAttributes SentinelOneMatchAttributes `json:"match_attributes"`
|
||||
}
|
||||
|
||||
// EDRSentinelOneResponse Represents a SentinelOne EDR integration configuration
|
||||
type EDRSentinelOneResponse struct {
|
||||
// AccountId The identifier of the account this integration belongs to.
|
||||
AccountId string `json:"account_id"`
|
||||
|
||||
// ApiUrl The Base URL of SentinelOne API
|
||||
ApiUrl string `json:"api_url"`
|
||||
|
||||
// CreatedAt Timestamp of when the integration was created.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// CreatedBy The user id that created the integration
|
||||
CreatedBy string `json:"created_by"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Groups List of groups
|
||||
Groups []Group `json:"groups"`
|
||||
|
||||
// Id The unique numeric identifier for the integration.
|
||||
Id int64 `json:"id"`
|
||||
|
||||
// LastSyncedAt Timestamp of when the integration was last synced.
|
||||
LastSyncedAt time.Time `json:"last_synced_at"`
|
||||
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours.
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// MatchAttributes Attribute conditions to match when approving agents
|
||||
MatchAttributes SentinelOneMatchAttributes `json:"match_attributes"`
|
||||
|
||||
// UpdatedAt Timestamp of when the integration was last updated.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ErrorResponse Standard error response. Note: The exact structure of this error response is inferred from `util.WriteErrorResponse` and `util.WriteError` usage in the provided Go code, as a specific Go struct for errors was not provided.
|
||||
type ErrorResponse struct {
|
||||
// Message A human-readable error message.
|
||||
Message *string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// Event defines model for Event.
|
||||
type Event struct {
|
||||
// Activity The activity that occurred during the event
|
||||
@@ -1034,9 +700,6 @@ type GeoLocationCheck struct {
|
||||
// GeoLocationCheckAction Action to take upon policy match
|
||||
type GeoLocationCheckAction string
|
||||
|
||||
// GetTenantsResponse defines model for GetTenantsResponse.
|
||||
type GetTenantsResponse = []TenantResponse
|
||||
|
||||
// Group defines model for Group.
|
||||
type Group struct {
|
||||
// Id Group ID
|
||||
@@ -1093,21 +756,6 @@ type GroupRequest struct {
|
||||
Resources *[]Resource `json:"resources,omitempty"`
|
||||
}
|
||||
|
||||
// HuntressMatchAttributes Attribute conditions to match when approving agents
|
||||
type HuntressMatchAttributes struct {
|
||||
// DefenderPolicyStatus Policy status of Defender AV for Managed Antivirus.
|
||||
DefenderPolicyStatus *string `json:"defender_policy_status,omitempty"`
|
||||
|
||||
// DefenderStatus Status of Defender AV Managed Antivirus.
|
||||
DefenderStatus *string `json:"defender_status,omitempty"`
|
||||
|
||||
// DefenderSubstatus Sub-status of Defender AV Managed Antivirus.
|
||||
DefenderSubstatus *string `json:"defender_substatus,omitempty"`
|
||||
|
||||
// FirewallStatus Status of agent firewall. Can be one of Disabled, Enabled, Pending Isolation, Isolated, Pending Release.
|
||||
FirewallStatus *string `json:"firewall_status,omitempty"`
|
||||
}
|
||||
|
||||
// IdentityProvider defines model for IdentityProvider.
|
||||
type IdentityProvider struct {
|
||||
// ClientId OAuth2 client ID
|
||||
@@ -1147,21 +795,6 @@ type IdentityProviderRequest struct {
|
||||
// IdentityProviderType Type of identity provider
|
||||
type IdentityProviderType string
|
||||
|
||||
// IdpIntegrationSyncLog Represents a synchronization log entry for an integration
|
||||
type IdpIntegrationSyncLog struct {
|
||||
// Id The unique identifier for the sync log
|
||||
Id int64 `json:"id"`
|
||||
|
||||
// Level The log level
|
||||
Level string `json:"level"`
|
||||
|
||||
// Message Log message
|
||||
Message string `json:"message"`
|
||||
|
||||
// Timestamp Timestamp of when the log was created
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// IngressPeer defines model for IngressPeer.
|
||||
type IngressPeer struct {
|
||||
AvailablePorts AvailablePorts `json:"available_ports"`
|
||||
@@ -1316,57 +949,6 @@ type InstanceVersionInfo struct {
|
||||
ManagementUpdateAvailable bool `json:"management_update_available"`
|
||||
}
|
||||
|
||||
// IntegrationResponse Represents an event streaming integration.
|
||||
type IntegrationResponse struct {
|
||||
// AccountId The identifier of the account this integration belongs to.
|
||||
AccountId *string `json:"account_id,omitempty"`
|
||||
|
||||
// Config Configuration for the integration. Sensitive keys (like API keys, secret keys) are masked with '****' in responses, as indicated by the GetIntegration handler logic.
|
||||
Config *map[string]string `json:"config,omitempty"`
|
||||
|
||||
// CreatedAt Timestamp of when the integration was created.
|
||||
CreatedAt *time.Time `json:"created_at,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is currently active.
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// Id The unique numeric identifier for the integration.
|
||||
Id *int64 `json:"id,omitempty"`
|
||||
|
||||
// Platform The event streaming platform.
|
||||
Platform *IntegrationResponsePlatform `json:"platform,omitempty"`
|
||||
|
||||
// UpdatedAt Timestamp of when the integration was last updated.
|
||||
UpdatedAt *time.Time `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// IntegrationResponsePlatform The event streaming platform.
|
||||
type IntegrationResponsePlatform string
|
||||
|
||||
// InvoicePDFResponse defines model for InvoicePDFResponse.
|
||||
type InvoicePDFResponse struct {
|
||||
// Url URL to redirect the user to invoice.
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
// InvoiceResponse defines model for InvoiceResponse.
|
||||
type InvoiceResponse struct {
|
||||
// Id The Stripe invoice id
|
||||
Id string `json:"id"`
|
||||
|
||||
// PeriodEnd The end date of the invoice period.
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
|
||||
// PeriodStart The start date of the invoice period.
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
|
||||
// Type The invoice type
|
||||
Type InvoiceResponseType `json:"type"`
|
||||
}
|
||||
|
||||
// InvoiceResponseType The invoice type
|
||||
type InvoiceResponseType string
|
||||
|
||||
// JobRequest defines model for JobRequest.
|
||||
type JobRequest struct {
|
||||
Workload WorkloadRequest `json:"workload"`
|
||||
@@ -2296,15 +1878,6 @@ type PolicyUpdate struct {
|
||||
SourcePostureChecks *[]string `json:"source_posture_checks,omitempty"`
|
||||
}
|
||||
|
||||
// PortalResponse defines model for PortalResponse.
|
||||
type PortalResponse struct {
|
||||
// SessionId The unique identifier for the customer portal session.
|
||||
SessionId string `json:"session_id"`
|
||||
|
||||
// Url URL to redirect the user to the customer portal.
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
// PostureCheck defines model for PostureCheck.
|
||||
type PostureCheck struct {
|
||||
// Checks List of objects that perform the actual checks
|
||||
@@ -2332,21 +1905,6 @@ type PostureCheckUpdate struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Price defines model for Price.
|
||||
type Price struct {
|
||||
// Currency Currency code for this price.
|
||||
Currency string `json:"currency"`
|
||||
|
||||
// Price Price amount in minor units (e.g., cents).
|
||||
Price int `json:"price"`
|
||||
|
||||
// PriceId Unique identifier for the price.
|
||||
PriceId string `json:"price_id"`
|
||||
|
||||
// Unit Unit of measurement for this price (e.g., per user).
|
||||
Unit string `json:"unit"`
|
||||
}
|
||||
|
||||
// Process Describes the operational activity within a peer's system.
|
||||
type Process struct {
|
||||
// LinuxPath Path to the process executable file in a Linux operating system
|
||||
@@ -2364,24 +1922,6 @@ type ProcessCheck struct {
|
||||
Processes []Process `json:"processes"`
|
||||
}
|
||||
|
||||
// Product defines model for Product.
|
||||
type Product struct {
|
||||
// Description Detailed description of the product.
|
||||
Description string `json:"description"`
|
||||
|
||||
// Features List of features provided by the product.
|
||||
Features []string `json:"features"`
|
||||
|
||||
// Free Indicates whether the product is free or not.
|
||||
Free bool `json:"free"`
|
||||
|
||||
// Name Name of the product.
|
||||
Name string `json:"name"`
|
||||
|
||||
// Prices List of prices for the product in different currencies
|
||||
Prices []Price `json:"prices"`
|
||||
}
|
||||
|
||||
// ProxyAccessLog defines model for ProxyAccessLog.
|
||||
type ProxyAccessLog struct {
|
||||
// AuthMethodUsed Authentication method used (e.g., password, pin, oidc)
|
||||
@@ -2593,66 +2133,6 @@ type RulePortRange struct {
|
||||
Start int `json:"start"`
|
||||
}
|
||||
|
||||
// ScimIntegration Represents a SCIM IDP integration
|
||||
type ScimIntegration struct {
|
||||
// AuthToken SCIM API token (full on creation, masked otherwise)
|
||||
AuthToken string `json:"auth_token"`
|
||||
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes []string `json:"group_prefixes"`
|
||||
|
||||
// Id The unique identifier for the integration
|
||||
Id int64 `json:"id"`
|
||||
|
||||
// LastSyncedAt Timestamp of when the integration was last synced
|
||||
LastSyncedAt time.Time `json:"last_synced_at"`
|
||||
|
||||
// Provider Name of the SCIM identity provider
|
||||
Provider string `json:"provider"`
|
||||
|
||||
// UserGroupPrefixes List of start_with string patterns for groups which users to sync
|
||||
UserGroupPrefixes []string `json:"user_group_prefixes"`
|
||||
}
|
||||
|
||||
// ScimTokenResponse Response containing the regenerated SCIM token
|
||||
type ScimTokenResponse struct {
|
||||
// AuthToken The newly generated SCIM API token
|
||||
AuthToken string `json:"auth_token"`
|
||||
}
|
||||
|
||||
// SentinelOneMatchAttributes Attribute conditions to match when approving agents
|
||||
type SentinelOneMatchAttributes struct {
|
||||
// ActiveThreats The maximum allowed number of active threats on the agent
|
||||
ActiveThreats *int `json:"active_threats,omitempty"`
|
||||
|
||||
// EncryptedApplications Whether disk encryption is enabled on the agent
|
||||
EncryptedApplications *bool `json:"encrypted_applications,omitempty"`
|
||||
|
||||
// FirewallEnabled Whether the agent firewall is enabled
|
||||
FirewallEnabled *bool `json:"firewall_enabled,omitempty"`
|
||||
|
||||
// Infected Whether the agent is currently flagged as infected
|
||||
Infected *bool `json:"infected,omitempty"`
|
||||
|
||||
// IsActive Whether the agent has been recently active and reporting
|
||||
IsActive *bool `json:"is_active,omitempty"`
|
||||
|
||||
// IsUpToDate Whether the agent is running the latest available version
|
||||
IsUpToDate *bool `json:"is_up_to_date,omitempty"`
|
||||
|
||||
// NetworkStatus The current network connectivity status of the device
|
||||
NetworkStatus *SentinelOneMatchAttributesNetworkStatus `json:"network_status,omitempty"`
|
||||
|
||||
// OperationalState The current operational state of the agent
|
||||
OperationalState *string `json:"operational_state,omitempty"`
|
||||
}
|
||||
|
||||
// SentinelOneMatchAttributesNetworkStatus The current network connectivity status of the device
|
||||
type SentinelOneMatchAttributesNetworkStatus string
|
||||
|
||||
// Service defines model for Service.
|
||||
type Service struct {
|
||||
Auth ServiceAuthConfig `json:"auth"`
|
||||
@@ -2930,117 +2410,6 @@ type SetupResponse struct {
|
||||
UserId string `json:"user_id"`
|
||||
}
|
||||
|
||||
// Subscription defines model for Subscription.
|
||||
type Subscription struct {
|
||||
// Active Indicates whether the subscription is active or not.
|
||||
Active bool `json:"active"`
|
||||
|
||||
// Currency Currency code of the subscription.
|
||||
Currency string `json:"currency"`
|
||||
|
||||
// Features List of features included in the subscription.
|
||||
Features *[]string `json:"features,omitempty"`
|
||||
|
||||
// PlanTier The tier of the plan for the subscription.
|
||||
PlanTier string `json:"plan_tier"`
|
||||
|
||||
// Price Price amount in minor units (e.g., cents).
|
||||
Price int `json:"price"`
|
||||
|
||||
// PriceId Unique identifier for the price of the subscription.
|
||||
PriceId string `json:"price_id"`
|
||||
|
||||
// Provider The provider of the subscription.
|
||||
Provider string `json:"provider"`
|
||||
|
||||
// RemainingTrial The remaining time for the trial period, in seconds.
|
||||
RemainingTrial *int `json:"remaining_trial,omitempty"`
|
||||
|
||||
// UpdatedAt The date and time when the subscription was last updated.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TenantGroupResponse defines model for TenantGroupResponse.
|
||||
type TenantGroupResponse struct {
|
||||
// Id The Group ID
|
||||
Id string `json:"id"`
|
||||
|
||||
// Role The Role name
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
// TenantResponse defines model for TenantResponse.
|
||||
type TenantResponse struct {
|
||||
// ActivatedAt The date and time when the tenant was activated.
|
||||
ActivatedAt *time.Time `json:"activated_at,omitempty"`
|
||||
|
||||
// CreatedAt The date and time when the tenant was created.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// DnsChallenge The DNS challenge to set in a TXT record
|
||||
DnsChallenge string `json:"dns_challenge"`
|
||||
|
||||
// Domain The tenant account domain
|
||||
Domain string `json:"domain"`
|
||||
|
||||
// Groups MSP users Groups that can access the Tenant and Roles to assume
|
||||
Groups []TenantGroupResponse `json:"groups"`
|
||||
|
||||
// Id The updated MSP tenant account ID
|
||||
Id string `json:"id"`
|
||||
|
||||
// InvitedAt The date and time when the existing tenant was invited.
|
||||
InvitedAt *time.Time `json:"invited_at,omitempty"`
|
||||
|
||||
// Name The name for the MSP tenant
|
||||
Name string `json:"name"`
|
||||
|
||||
// Status The status of the tenant
|
||||
Status TenantResponseStatus `json:"status"`
|
||||
|
||||
// UpdatedAt The date and time when the tenant was last updated.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TenantResponseStatus The status of the tenant
|
||||
type TenantResponseStatus string
|
||||
|
||||
// UpdateScimIntegrationRequest Request payload for updating an SCIM IDP integration
|
||||
type UpdateScimIntegrationRequest struct {
|
||||
// Enabled Indicates whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes *[]string `json:"group_prefixes,omitempty"`
|
||||
|
||||
// UserGroupPrefixes List of start_with string patterns for groups which users to sync
|
||||
UserGroupPrefixes *[]string `json:"user_group_prefixes,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateTenantRequest defines model for UpdateTenantRequest.
|
||||
type UpdateTenantRequest struct {
|
||||
// Groups MSP users Groups that can access the Tenant and Roles to assume
|
||||
Groups []TenantGroupResponse `json:"groups"`
|
||||
|
||||
// Name The name for the MSP tenant
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// UsageStats defines model for UsageStats.
|
||||
type UsageStats struct {
|
||||
// ActivePeers Number of active peers.
|
||||
ActivePeers int64 `json:"active_peers"`
|
||||
|
||||
// ActiveUsers Number of active users.
|
||||
ActiveUsers int64 `json:"active_users"`
|
||||
|
||||
// TotalPeers Total number of peers.
|
||||
TotalPeers int64 `json:"total_peers"`
|
||||
|
||||
// TotalUsers Total number of users.
|
||||
TotalUsers int64 `json:"total_users"`
|
||||
}
|
||||
|
||||
// User defines model for User.
|
||||
type User struct {
|
||||
// AutoGroups Group IDs to auto-assign to peers registered by this user
|
||||
@@ -3378,66 +2747,6 @@ type GetApiGroupsParams struct {
|
||||
Name *string `form:"name,omitempty" json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// PostApiIntegrationsBillingAwsMarketplaceActivateJSONBody defines parameters for PostApiIntegrationsBillingAwsMarketplaceActivate.
|
||||
type PostApiIntegrationsBillingAwsMarketplaceActivateJSONBody struct {
|
||||
// PlanTier The plan tier to activate the subscription for.
|
||||
PlanTier string `json:"plan_tier"`
|
||||
}
|
||||
|
||||
// PostApiIntegrationsBillingAwsMarketplaceEnrichJSONBody defines parameters for PostApiIntegrationsBillingAwsMarketplaceEnrich.
|
||||
type PostApiIntegrationsBillingAwsMarketplaceEnrichJSONBody struct {
|
||||
// AwsUserId The AWS user ID.
|
||||
AwsUserId string `json:"aws_user_id"`
|
||||
}
|
||||
|
||||
// PostApiIntegrationsBillingCheckoutJSONBody defines parameters for PostApiIntegrationsBillingCheckout.
|
||||
type PostApiIntegrationsBillingCheckoutJSONBody struct {
|
||||
// BaseURL The base URL for the redirect after checkout.
|
||||
BaseURL string `json:"baseURL"`
|
||||
|
||||
// EnableTrial Enables a 14-day trial for the account.
|
||||
EnableTrial *bool `json:"enableTrial,omitempty"`
|
||||
|
||||
// PriceID The Price ID for checkout.
|
||||
PriceID string `json:"priceID"`
|
||||
}
|
||||
|
||||
// GetApiIntegrationsBillingPortalParams defines parameters for GetApiIntegrationsBillingPortal.
|
||||
type GetApiIntegrationsBillingPortalParams struct {
|
||||
// BaseURL The base URL for the redirect after accessing the portal.
|
||||
BaseURL string `form:"baseURL" json:"baseURL"`
|
||||
}
|
||||
|
||||
// PutApiIntegrationsBillingSubscriptionJSONBody defines parameters for PutApiIntegrationsBillingSubscription.
|
||||
type PutApiIntegrationsBillingSubscriptionJSONBody struct {
|
||||
// PlanTier The plan tier to change the subscription to.
|
||||
PlanTier *string `json:"plan_tier,omitempty"`
|
||||
|
||||
// PriceID The Price ID to change the subscription to.
|
||||
PriceID *string `json:"priceID,omitempty"`
|
||||
}
|
||||
|
||||
// PutApiIntegrationsMspTenantsIdInviteJSONBody defines parameters for PutApiIntegrationsMspTenantsIdInvite.
|
||||
type PutApiIntegrationsMspTenantsIdInviteJSONBody struct {
|
||||
// Value Accept or decline the invitation.
|
||||
Value PutApiIntegrationsMspTenantsIdInviteJSONBodyValue `json:"value"`
|
||||
}
|
||||
|
||||
// PutApiIntegrationsMspTenantsIdInviteJSONBodyValue defines parameters for PutApiIntegrationsMspTenantsIdInvite.
|
||||
type PutApiIntegrationsMspTenantsIdInviteJSONBodyValue string
|
||||
|
||||
// PostApiIntegrationsMspTenantsIdSubscriptionJSONBody defines parameters for PostApiIntegrationsMspTenantsIdSubscription.
|
||||
type PostApiIntegrationsMspTenantsIdSubscriptionJSONBody struct {
|
||||
// PriceID The Price ID to change the subscription to.
|
||||
PriceID string `json:"priceID"`
|
||||
}
|
||||
|
||||
// PostApiIntegrationsMspTenantsIdUnlinkJSONBody defines parameters for PostApiIntegrationsMspTenantsIdUnlink.
|
||||
type PostApiIntegrationsMspTenantsIdUnlinkJSONBody struct {
|
||||
// Owner The new owners user ID.
|
||||
Owner string `json:"owner"`
|
||||
}
|
||||
|
||||
// GetApiPeersParams defines parameters for GetApiPeers.
|
||||
type GetApiPeersParams struct {
|
||||
// Name Filter peers by name
|
||||
@@ -3483,12 +2792,6 @@ type PostApiDnsZonesZoneIdRecordsJSONRequestBody = DNSRecordRequest
|
||||
// PutApiDnsZonesZoneIdRecordsRecordIdJSONRequestBody defines body for PutApiDnsZonesZoneIdRecordsRecordId for application/json ContentType.
|
||||
type PutApiDnsZonesZoneIdRecordsRecordIdJSONRequestBody = DNSRecordRequest
|
||||
|
||||
// CreateIntegrationJSONRequestBody defines body for CreateIntegration for application/json ContentType.
|
||||
type CreateIntegrationJSONRequestBody = CreateIntegrationRequest
|
||||
|
||||
// UpdateIntegrationJSONRequestBody defines body for UpdateIntegration for application/json ContentType.
|
||||
type UpdateIntegrationJSONRequestBody = CreateIntegrationRequest
|
||||
|
||||
// PostApiGroupsJSONRequestBody defines body for PostApiGroups for application/json ContentType.
|
||||
type PostApiGroupsJSONRequestBody = GroupRequest
|
||||
|
||||
@@ -3507,63 +2810,6 @@ type PostApiIngressPeersJSONRequestBody = IngressPeerCreateRequest
|
||||
// PutApiIngressPeersIngressPeerIdJSONRequestBody defines body for PutApiIngressPeersIngressPeerId for application/json ContentType.
|
||||
type PutApiIngressPeersIngressPeerIdJSONRequestBody = IngressPeerUpdateRequest
|
||||
|
||||
// PostApiIntegrationsBillingAwsMarketplaceActivateJSONRequestBody defines body for PostApiIntegrationsBillingAwsMarketplaceActivate for application/json ContentType.
|
||||
type PostApiIntegrationsBillingAwsMarketplaceActivateJSONRequestBody PostApiIntegrationsBillingAwsMarketplaceActivateJSONBody
|
||||
|
||||
// PostApiIntegrationsBillingAwsMarketplaceEnrichJSONRequestBody defines body for PostApiIntegrationsBillingAwsMarketplaceEnrich for application/json ContentType.
|
||||
type PostApiIntegrationsBillingAwsMarketplaceEnrichJSONRequestBody PostApiIntegrationsBillingAwsMarketplaceEnrichJSONBody
|
||||
|
||||
// PostApiIntegrationsBillingCheckoutJSONRequestBody defines body for PostApiIntegrationsBillingCheckout for application/json ContentType.
|
||||
type PostApiIntegrationsBillingCheckoutJSONRequestBody PostApiIntegrationsBillingCheckoutJSONBody
|
||||
|
||||
// PutApiIntegrationsBillingSubscriptionJSONRequestBody defines body for PutApiIntegrationsBillingSubscription for application/json ContentType.
|
||||
type PutApiIntegrationsBillingSubscriptionJSONRequestBody PutApiIntegrationsBillingSubscriptionJSONBody
|
||||
|
||||
// CreateFalconEDRIntegrationJSONRequestBody defines body for CreateFalconEDRIntegration for application/json ContentType.
|
||||
type CreateFalconEDRIntegrationJSONRequestBody = EDRFalconRequest
|
||||
|
||||
// UpdateFalconEDRIntegrationJSONRequestBody defines body for UpdateFalconEDRIntegration for application/json ContentType.
|
||||
type UpdateFalconEDRIntegrationJSONRequestBody = EDRFalconRequest
|
||||
|
||||
// CreateHuntressEDRIntegrationJSONRequestBody defines body for CreateHuntressEDRIntegration for application/json ContentType.
|
||||
type CreateHuntressEDRIntegrationJSONRequestBody = EDRHuntressRequest
|
||||
|
||||
// UpdateHuntressEDRIntegrationJSONRequestBody defines body for UpdateHuntressEDRIntegration for application/json ContentType.
|
||||
type UpdateHuntressEDRIntegrationJSONRequestBody = EDRHuntressRequest
|
||||
|
||||
// CreateEDRIntegrationJSONRequestBody defines body for CreateEDRIntegration for application/json ContentType.
|
||||
type CreateEDRIntegrationJSONRequestBody = EDRIntuneRequest
|
||||
|
||||
// UpdateEDRIntegrationJSONRequestBody defines body for UpdateEDRIntegration for application/json ContentType.
|
||||
type UpdateEDRIntegrationJSONRequestBody = EDRIntuneRequest
|
||||
|
||||
// CreateSentinelOneEDRIntegrationJSONRequestBody defines body for CreateSentinelOneEDRIntegration for application/json ContentType.
|
||||
type CreateSentinelOneEDRIntegrationJSONRequestBody = EDRSentinelOneRequest
|
||||
|
||||
// UpdateSentinelOneEDRIntegrationJSONRequestBody defines body for UpdateSentinelOneEDRIntegration for application/json ContentType.
|
||||
type UpdateSentinelOneEDRIntegrationJSONRequestBody = EDRSentinelOneRequest
|
||||
|
||||
// PostApiIntegrationsMspTenantsJSONRequestBody defines body for PostApiIntegrationsMspTenants for application/json ContentType.
|
||||
type PostApiIntegrationsMspTenantsJSONRequestBody = CreateTenantRequest
|
||||
|
||||
// PutApiIntegrationsMspTenantsIdJSONRequestBody defines body for PutApiIntegrationsMspTenantsId for application/json ContentType.
|
||||
type PutApiIntegrationsMspTenantsIdJSONRequestBody = UpdateTenantRequest
|
||||
|
||||
// PutApiIntegrationsMspTenantsIdInviteJSONRequestBody defines body for PutApiIntegrationsMspTenantsIdInvite for application/json ContentType.
|
||||
type PutApiIntegrationsMspTenantsIdInviteJSONRequestBody PutApiIntegrationsMspTenantsIdInviteJSONBody
|
||||
|
||||
// PostApiIntegrationsMspTenantsIdSubscriptionJSONRequestBody defines body for PostApiIntegrationsMspTenantsIdSubscription for application/json ContentType.
|
||||
type PostApiIntegrationsMspTenantsIdSubscriptionJSONRequestBody PostApiIntegrationsMspTenantsIdSubscriptionJSONBody
|
||||
|
||||
// PostApiIntegrationsMspTenantsIdUnlinkJSONRequestBody defines body for PostApiIntegrationsMspTenantsIdUnlink for application/json ContentType.
|
||||
type PostApiIntegrationsMspTenantsIdUnlinkJSONRequestBody PostApiIntegrationsMspTenantsIdUnlinkJSONBody
|
||||
|
||||
// CreateSCIMIntegrationJSONRequestBody defines body for CreateSCIMIntegration for application/json ContentType.
|
||||
type CreateSCIMIntegrationJSONRequestBody = CreateScimIntegrationRequest
|
||||
|
||||
// UpdateSCIMIntegrationJSONRequestBody defines body for UpdateSCIMIntegration for application/json ContentType.
|
||||
type UpdateSCIMIntegrationJSONRequestBody = UpdateScimIntegrationRequest
|
||||
|
||||
// PostApiNetworksJSONRequestBody defines body for PostApiNetworks for application/json ContentType.
|
||||
type PostApiNetworksJSONRequestBody = NetworkRequest
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
const (
|
||||
bufferSize = 8820
|
||||
serverResponseTimeout = 8 * time.Second
|
||||
connChannelSize = 100
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -70,37 +69,15 @@ type connContainer struct {
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func newConnContainer(log *log.Entry, c *Client, peerID messages.PeerID, instanceURL *RelayAddr) *connContainer {
|
||||
func newConnContainer(log *log.Entry, conn *Conn, messages chan Msg) *connContainer {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
msgChan := make(chan Msg, connChannelSize)
|
||||
cn := &Conn{
|
||||
dstID: peerID,
|
||||
messageChan: msgChan,
|
||||
instanceURL: instanceURL,
|
||||
}
|
||||
cc := &connContainer{
|
||||
return &connContainer{
|
||||
log: log,
|
||||
conn: cn,
|
||||
messages: msgChan,
|
||||
conn: conn,
|
||||
messages: messages,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
|
||||
// bind conn to client
|
||||
cn.writeFn = func(dstID messages.PeerID, payload []byte) (int, error) {
|
||||
return c.writeTo(cc, dstID, payload)
|
||||
}
|
||||
cn.closeFn = func(dstID messages.PeerID) error {
|
||||
return c.closeConn(cc, dstID)
|
||||
}
|
||||
cn.localAddrFn = func() net.Addr {
|
||||
return c.relayConn.LocalAddr()
|
||||
}
|
||||
return cc
|
||||
}
|
||||
|
||||
func (cc *connContainer) netConn() net.Conn {
|
||||
return cc.conn
|
||||
}
|
||||
|
||||
func (cc *connContainer) writeMsg(msg Msg) {
|
||||
@@ -153,7 +130,6 @@ type Client struct {
|
||||
|
||||
relayConn net.Conn
|
||||
conns map[messages.PeerID]*connContainer
|
||||
earlyMsgs *earlyMsgBuffer
|
||||
serviceIsRunning bool
|
||||
mu sync.Mutex // protect serviceIsRunning and conns
|
||||
readLoopMutex sync.Mutex
|
||||
@@ -189,8 +165,6 @@ func NewClient(serverURL string, authTokenStore *auth.TokenStore, peerID string,
|
||||
conns: make(map[messages.PeerID]*connContainer),
|
||||
}
|
||||
|
||||
c.earlyMsgs = newEarlyMsgBuffer()
|
||||
|
||||
c.log.Infof("create new relay connection: local peerID: %s, local peer hashedID: %s", peerID, hashedID)
|
||||
return c
|
||||
}
|
||||
@@ -258,16 +232,12 @@ func (c *Client) OpenConn(ctx context.Context, dstPeerID string) (net.Conn, erro
|
||||
instanceURL := c.instanceURL
|
||||
c.muInstanceURL.Unlock()
|
||||
|
||||
container := newConnContainer(c.log, c, peerID, instanceURL)
|
||||
msgChannel := make(chan Msg, 100)
|
||||
conn := NewConn(c, peerID, msgChannel, instanceURL)
|
||||
container := newConnContainer(c.log, conn, msgChannel)
|
||||
c.conns[peerID] = container
|
||||
earlyMsg, hasEarly := c.earlyMsgs.pop(peerID)
|
||||
c.mu.Unlock()
|
||||
|
||||
if hasEarly {
|
||||
container.writeMsg(earlyMsg)
|
||||
c.log.Tracef("flushed buffered early message for peer: %s", peerID)
|
||||
}
|
||||
|
||||
if err := c.stateSubscription.WaitToBeOnlineAndSubscribe(ctx, peerID); err != nil {
|
||||
c.log.Errorf("peer not available: %s, %s", peerID, err)
|
||||
c.mu.Lock()
|
||||
@@ -291,7 +261,7 @@ func (c *Client) OpenConn(ctx context.Context, dstPeerID string) (net.Conn, erro
|
||||
c.mu.Unlock()
|
||||
|
||||
c.log.Infof("remote peer is available: %s", peerID)
|
||||
return container.netConn(), nil
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// ServerInstanceURL returns the address of the relay server. It could change after the close and reopen the connection.
|
||||
@@ -496,20 +466,10 @@ func (c *Client) handleTransportMsg(buf []byte, bufPtr *[]byte, internallyStoppe
|
||||
return false
|
||||
}
|
||||
container, ok := c.conns[*peerID]
|
||||
earlyBuf := c.earlyMsgs
|
||||
c.mu.Unlock()
|
||||
if !ok {
|
||||
msg := Msg{
|
||||
bufPool: c.bufPool,
|
||||
bufPtr: bufPtr,
|
||||
Payload: payload,
|
||||
}
|
||||
if earlyBuf == nil || !earlyBuf.put(*peerID, msg) {
|
||||
c.log.Warnf("failed to buffer early message for peer: %s", peerID.String())
|
||||
c.bufPool.Put(bufPtr)
|
||||
} else {
|
||||
c.log.Debugf("buffered early transport message for peer: %s", peerID.String())
|
||||
}
|
||||
c.log.Errorf("peer not found: %s", peerID.String())
|
||||
c.bufPool.Put(bufPtr)
|
||||
return true
|
||||
}
|
||||
msg := Msg{
|
||||
@@ -521,15 +481,15 @@ func (c *Client) handleTransportMsg(buf []byte, bufPtr *[]byte, internallyStoppe
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Client) writeTo(containerRef *connContainer, dstID messages.PeerID, payload []byte) (int, error) {
|
||||
func (c *Client) writeTo(connReference *Conn, dstID messages.PeerID, payload []byte) (int, error) {
|
||||
c.mu.Lock()
|
||||
current, ok := c.conns[dstID]
|
||||
conn, ok := c.conns[dstID]
|
||||
c.mu.Unlock()
|
||||
if !ok {
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
|
||||
if current != containerRef {
|
||||
if conn.conn != connReference {
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
|
||||
@@ -577,9 +537,6 @@ func (c *Client) closeAllConns() {
|
||||
container.close()
|
||||
}
|
||||
c.conns = make(map[messages.PeerID]*connContainer)
|
||||
|
||||
c.earlyMsgs.close()
|
||||
c.earlyMsgs = newEarlyMsgBuffer()
|
||||
}
|
||||
|
||||
func (c *Client) closeConnsByPeerID(peerIDs []messages.PeerID) {
|
||||
@@ -603,26 +560,26 @@ func (c *Client) closeConnsByPeerID(peerIDs []messages.PeerID) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) closeConn(containerRef *connContainer, id messages.PeerID) error {
|
||||
func (c *Client) closeConn(connReference *Conn, id messages.PeerID) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
current, ok := c.conns[id]
|
||||
container, ok := c.conns[id]
|
||||
if !ok {
|
||||
return net.ErrClosed
|
||||
}
|
||||
|
||||
if current != containerRef {
|
||||
if container.conn != connReference {
|
||||
return fmt.Errorf("conn reference mismatch")
|
||||
}
|
||||
|
||||
if err := c.stateSubscription.UnsubscribeStateChange([]messages.PeerID{id}); err != nil {
|
||||
current.log.Errorf("failed to unsubscribe from peer state change: %s", err)
|
||||
container.log.Errorf("failed to unsubscribe from peer state change: %s", err)
|
||||
}
|
||||
|
||||
c.log.Infof("free up connection to peer: %s", id)
|
||||
delete(c.conns, id)
|
||||
current.close()
|
||||
container.close()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -9,35 +9,49 @@ import (
|
||||
|
||||
// Conn represent a connection to a relayed remote peer.
|
||||
type Conn struct {
|
||||
client *Client
|
||||
dstID messages.PeerID
|
||||
messageChan chan Msg
|
||||
instanceURL *RelayAddr
|
||||
writeFn func(messages.PeerID, []byte) (int, error)
|
||||
closeFn func(messages.PeerID) error
|
||||
localAddrFn func() net.Addr
|
||||
}
|
||||
|
||||
// NewConn creates a new connection to a relayed remote peer.
|
||||
// client: the client instance, it used to send messages to the destination peer
|
||||
// dstID: the destination peer ID
|
||||
// messageChan: the channel where the messages will be received
|
||||
// instanceURL: the relay instance URL, it used to get the proper server instance address for the remote peer
|
||||
func NewConn(client *Client, dstID messages.PeerID, messageChan chan Msg, instanceURL *RelayAddr) *Conn {
|
||||
c := &Conn{
|
||||
client: client,
|
||||
dstID: dstID,
|
||||
messageChan: messageChan,
|
||||
instanceURL: instanceURL,
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Conn) Write(p []byte) (n int, err error) {
|
||||
return c.writeFn(c.dstID, p)
|
||||
return c.client.writeTo(c, c.dstID, p)
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (n int, err error) {
|
||||
m, ok := <-c.messageChan
|
||||
msg, ok := <-c.messageChan
|
||||
if !ok {
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
|
||||
n = copy(b, m.Payload)
|
||||
m.Free()
|
||||
n = copy(b, msg.Payload)
|
||||
msg.Free()
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
return c.closeFn(c.dstID)
|
||||
return c.client.closeConn(c, c.dstID)
|
||||
}
|
||||
|
||||
func (c *Conn) LocalAddr() net.Addr {
|
||||
return c.localAddrFn()
|
||||
return c.client.relayConn.LocalAddr()
|
||||
}
|
||||
|
||||
func (c *Conn) RemoteAddr() net.Addr {
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/relay/messages"
|
||||
)
|
||||
|
||||
const (
|
||||
earlyMsgTTL = 5 * time.Second
|
||||
earlyMsgCapacity = 1000
|
||||
)
|
||||
|
||||
// earlyMsgBuffer buffers transport messages that arrive before the corresponding
|
||||
// OpenConn call. This happens during reconnection when the remote peer sends data
|
||||
// before the local side has set up the relay connection.
|
||||
//
|
||||
// It stores at most one message per peer (the first WireGuard handshake) and
|
||||
// caps the total number of entries to prevent unbounded memory growth.
|
||||
// A cleanup timer runs only when there are buffered entries and fires when the
|
||||
// oldest entry expires. Entries are kept in a linked list ordered by insertion
|
||||
// time so cleanup only needs to walk from the front.
|
||||
type earlyMsgBuffer struct {
|
||||
mu sync.Mutex
|
||||
index map[messages.PeerID]*list.Element
|
||||
order *list.List // front = oldest
|
||||
timer *time.Timer
|
||||
closed bool
|
||||
}
|
||||
|
||||
type earlyMsg struct {
|
||||
peerID messages.PeerID
|
||||
msg Msg
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
func newEarlyMsgBuffer() *earlyMsgBuffer {
|
||||
return &earlyMsgBuffer{
|
||||
index: make(map[messages.PeerID]*list.Element),
|
||||
order: list.New(),
|
||||
}
|
||||
}
|
||||
|
||||
// put stores or overwrites a message for the given peer. If a message for the
|
||||
// peer already exists, it is replaced with the new one. Returns false if the
|
||||
// message was not stored (buffer full or buffer closed).
|
||||
func (b *earlyMsgBuffer) put(peerID messages.PeerID, msg Msg) bool {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
if b.closed {
|
||||
return false
|
||||
}
|
||||
|
||||
if existing, exists := b.index[peerID]; exists {
|
||||
old := b.order.Remove(existing).(earlyMsg)
|
||||
old.msg.Free()
|
||||
delete(b.index, peerID)
|
||||
}
|
||||
|
||||
if b.order.Len() >= earlyMsgCapacity {
|
||||
return false
|
||||
}
|
||||
|
||||
entry := earlyMsg{
|
||||
peerID: peerID,
|
||||
msg: msg,
|
||||
createdAt: time.Now(),
|
||||
}
|
||||
elem := b.order.PushBack(entry)
|
||||
b.index[peerID] = elem
|
||||
|
||||
// Start the cleanup timer if this is the first entry
|
||||
if b.order.Len() == 1 {
|
||||
b.scheduleCleanup(earlyMsgTTL)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// pop retrieves and removes the buffered message for the given peer.
|
||||
// Returns the message and true if found, zero value and false otherwise.
|
||||
func (b *earlyMsgBuffer) pop(peerID messages.PeerID) (Msg, bool) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
elem, ok := b.index[peerID]
|
||||
if !ok {
|
||||
return Msg{}, false
|
||||
}
|
||||
|
||||
entry := b.order.Remove(elem).(earlyMsg)
|
||||
delete(b.index, peerID)
|
||||
|
||||
if b.order.Len() == 0 {
|
||||
b.stopCleanup()
|
||||
}
|
||||
|
||||
return entry.msg, true
|
||||
}
|
||||
|
||||
// close stops the cleanup timer and frees all buffered messages.
|
||||
func (b *earlyMsgBuffer) close() {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
if b.closed {
|
||||
return
|
||||
}
|
||||
b.closed = true
|
||||
b.stopCleanup()
|
||||
|
||||
for elem := b.order.Front(); elem != nil; elem = elem.Next() {
|
||||
entry := elem.Value.(earlyMsg)
|
||||
entry.msg.Free()
|
||||
}
|
||||
b.order.Init()
|
||||
b.index = make(map[messages.PeerID]*list.Element)
|
||||
}
|
||||
|
||||
// scheduleCleanup starts or resets the timer. Caller must hold b.mu.
|
||||
func (b *earlyMsgBuffer) scheduleCleanup(d time.Duration) {
|
||||
if b.timer != nil {
|
||||
b.timer.Stop()
|
||||
}
|
||||
b.timer = time.AfterFunc(d, b.removeExpired)
|
||||
}
|
||||
|
||||
// stopCleanup stops the timer. Caller must hold b.mu.
|
||||
func (b *earlyMsgBuffer) stopCleanup() {
|
||||
if b.timer != nil {
|
||||
b.timer.Stop()
|
||||
b.timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (b *earlyMsgBuffer) removeExpired() {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
if b.closed {
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
for elem := b.order.Front(); elem != nil; {
|
||||
entry := elem.Value.(earlyMsg)
|
||||
if now.Sub(entry.createdAt) <= earlyMsgTTL {
|
||||
// Entries are ordered by time, so the rest are newer
|
||||
break
|
||||
}
|
||||
next := elem.Next()
|
||||
b.order.Remove(elem)
|
||||
delete(b.index, entry.peerID)
|
||||
entry.msg.Free()
|
||||
elem = next
|
||||
}
|
||||
|
||||
if b.order.Len() == 0 {
|
||||
b.timer = nil
|
||||
return
|
||||
}
|
||||
|
||||
// Schedule next cleanup based on when the oldest entry expires
|
||||
front := b.order.Front()
|
||||
if front == nil {
|
||||
b.timer = nil
|
||||
return
|
||||
}
|
||||
oldest := front.Value.(earlyMsg).createdAt
|
||||
nextCleanup := earlyMsgTTL - now.Sub(oldest)
|
||||
b.scheduleCleanup(nextCleanup)
|
||||
}
|
||||
@@ -1,485 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/netbirdio/netbird/shared/relay/messages"
|
||||
)
|
||||
|
||||
func newTestPool() *sync.Pool {
|
||||
return &sync.Pool{
|
||||
New: func() any {
|
||||
buf := make([]byte, 64)
|
||||
return &buf
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newTestMsg(pool *sync.Pool, payload string) Msg {
|
||||
bufPtr := pool.Get().(*[]byte)
|
||||
copy(*bufPtr, payload)
|
||||
return Msg{
|
||||
bufPool: pool,
|
||||
bufPtr: bufPtr,
|
||||
Payload: (*bufPtr)[:len(payload)],
|
||||
}
|
||||
}
|
||||
|
||||
func peerID(id string) messages.PeerID {
|
||||
return messages.HashID(id)
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_PutAndPop(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
peer := peerID("peer1")
|
||||
msg := newTestMsg(pool, "hello")
|
||||
|
||||
if !buf.put(peer, msg) {
|
||||
t.Fatal("put should succeed")
|
||||
}
|
||||
|
||||
got, ok := buf.pop(peer)
|
||||
if !ok {
|
||||
t.Fatal("pop should find the message")
|
||||
}
|
||||
if string(got.Payload) != "hello" {
|
||||
t.Fatalf("expected payload 'hello', got '%s'", got.Payload)
|
||||
}
|
||||
got.Free()
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_PopNotFound(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
_, ok := buf.pop(peerID("nonexistent"))
|
||||
if ok {
|
||||
t.Fatal("pop should return false for unknown peer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_PopAfterPopReturnsFalse(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
peer := peerID("peer1")
|
||||
|
||||
buf.put(peer, newTestMsg(pool, "data"))
|
||||
|
||||
got, ok := buf.pop(peer)
|
||||
if !ok {
|
||||
t.Fatal("first pop should succeed")
|
||||
}
|
||||
got.Free()
|
||||
|
||||
_, ok = buf.pop(peer)
|
||||
if ok {
|
||||
t.Fatal("second pop for the same peer should return false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_OverwriteSamePeer(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
peer := peerID("peer1")
|
||||
|
||||
if !buf.put(peer, newTestMsg(pool, "first")) {
|
||||
t.Fatal("first put should succeed")
|
||||
}
|
||||
if !buf.put(peer, newTestMsg(pool, "second")) {
|
||||
t.Fatal("second put (overwrite) should succeed")
|
||||
}
|
||||
|
||||
got, ok := buf.pop(peer)
|
||||
if !ok {
|
||||
t.Fatal("pop should find the message")
|
||||
}
|
||||
if string(got.Payload) != "second" {
|
||||
t.Fatalf("expected payload 'second', got '%s'", got.Payload)
|
||||
}
|
||||
got.Free()
|
||||
|
||||
// No more messages should be present for this peer
|
||||
_, ok = buf.pop(peer)
|
||||
if ok {
|
||||
t.Fatal("pop should return false after the only message was already popped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_MultiplePeers(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
peers := []messages.PeerID{peerID("a"), peerID("b"), peerID("c")}
|
||||
|
||||
for i, p := range peers {
|
||||
msg := newTestMsg(pool, fmt.Sprintf("msg-%d", i))
|
||||
if !buf.put(p, msg) {
|
||||
t.Fatalf("put should succeed for peer %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Pop in reverse order to verify independence
|
||||
for i := len(peers) - 1; i >= 0; i-- {
|
||||
got, ok := buf.pop(peers[i])
|
||||
if !ok {
|
||||
t.Fatalf("pop should find message for peer %d", i)
|
||||
}
|
||||
expected := fmt.Sprintf("msg-%d", i)
|
||||
if string(got.Payload) != expected {
|
||||
t.Fatalf("expected payload '%s', got '%s'", expected, got.Payload)
|
||||
}
|
||||
got.Free()
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_Capacity(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
|
||||
// Fill to capacity
|
||||
for i := 0; i < earlyMsgCapacity; i++ {
|
||||
peer := peerID(fmt.Sprintf("peer-%d", i))
|
||||
msg := newTestMsg(pool, fmt.Sprintf("msg-%d", i))
|
||||
if !buf.put(peer, msg) {
|
||||
t.Fatalf("put should succeed for peer %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Next put for a new peer should fail
|
||||
msg := newTestMsg(pool, "overflow")
|
||||
if buf.put(peerID("overflow-peer"), msg) {
|
||||
t.Fatal("put should fail when buffer is at capacity")
|
||||
}
|
||||
msg.Free()
|
||||
|
||||
// Overwriting an existing peer should still work (it removes then adds)
|
||||
overwrite := newTestMsg(pool, "overwritten")
|
||||
if !buf.put(peerID("peer-0"), overwrite) {
|
||||
t.Fatal("overwrite should succeed even at capacity")
|
||||
}
|
||||
|
||||
got, ok := buf.pop(peerID("peer-0"))
|
||||
if !ok {
|
||||
t.Fatal("pop should find overwritten message")
|
||||
}
|
||||
if string(got.Payload) != "overwritten" {
|
||||
t.Fatalf("expected 'overwritten', got '%s'", got.Payload)
|
||||
}
|
||||
got.Free()
|
||||
|
||||
// Clean up remaining
|
||||
for i := 1; i < earlyMsgCapacity; i++ {
|
||||
peer := peerID(fmt.Sprintf("peer-%d", i))
|
||||
if m, ok := buf.pop(peer); ok {
|
||||
m.Free()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_CapacityAfterPop(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
|
||||
// Fill to capacity
|
||||
for i := 0; i < earlyMsgCapacity; i++ {
|
||||
peer := peerID(fmt.Sprintf("peer-%d", i))
|
||||
if !buf.put(peer, newTestMsg(pool, "x")) {
|
||||
t.Fatalf("put should succeed for peer %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Pop one entry to free a slot
|
||||
got, ok := buf.pop(peerID("peer-0"))
|
||||
if !ok {
|
||||
t.Fatal("pop should succeed")
|
||||
}
|
||||
got.Free()
|
||||
|
||||
// Now a new peer should fit
|
||||
if !buf.put(peerID("new-peer"), newTestMsg(pool, "new")) {
|
||||
t.Fatal("put should succeed after popping one entry")
|
||||
}
|
||||
|
||||
// Clean up
|
||||
for i := 1; i < earlyMsgCapacity; i++ {
|
||||
if m, ok := buf.pop(peerID(fmt.Sprintf("peer-%d", i))); ok {
|
||||
m.Free()
|
||||
}
|
||||
}
|
||||
if m, ok := buf.pop(peerID("new-peer")); ok {
|
||||
m.Free()
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_PutAfterClose(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
|
||||
pool := newTestPool()
|
||||
buf.close()
|
||||
|
||||
msg := newTestMsg(pool, "too late")
|
||||
if buf.put(peerID("peer1"), msg) {
|
||||
t.Fatal("put should fail after close")
|
||||
}
|
||||
msg.Free()
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_PopAfterClose(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
|
||||
pool := newTestPool()
|
||||
buf.put(peerID("peer1"), newTestMsg(pool, "data"))
|
||||
buf.close()
|
||||
|
||||
// Messages are freed on close, so pop should not find anything
|
||||
_, ok := buf.pop(peerID("peer1"))
|
||||
if ok {
|
||||
t.Fatal("pop should return false after close")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_DoubleClose(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
buf.close()
|
||||
buf.close() // should not panic
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_TTLExpiry(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
peer := peerID("peer1")
|
||||
|
||||
buf.put(peer, newTestMsg(pool, "expiring"))
|
||||
|
||||
// Wait for the TTL to expire plus some margin
|
||||
time.Sleep(earlyMsgTTL + 500*time.Millisecond)
|
||||
|
||||
_, ok := buf.pop(peer)
|
||||
if ok {
|
||||
t.Fatal("message should have been expired by cleanup")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_PartialExpiry(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
|
||||
// Insert first message
|
||||
buf.put(peerID("peer1"), newTestMsg(pool, "old"))
|
||||
|
||||
// Wait half the TTL, then insert second message
|
||||
time.Sleep(earlyMsgTTL / 2)
|
||||
|
||||
buf.put(peerID("peer2"), newTestMsg(pool, "new"))
|
||||
|
||||
// Wait for the first to expire but not the second
|
||||
time.Sleep(earlyMsgTTL/2 + 500*time.Millisecond)
|
||||
|
||||
// First should be gone
|
||||
_, ok := buf.pop(peerID("peer1"))
|
||||
if ok {
|
||||
t.Fatal("peer1 message should have expired")
|
||||
}
|
||||
|
||||
// Second should still be there
|
||||
got, ok := buf.pop(peerID("peer2"))
|
||||
if !ok {
|
||||
t.Fatal("peer2 message should still be present")
|
||||
}
|
||||
if string(got.Payload) != "new" {
|
||||
t.Fatalf("expected payload 'new', got '%s'", got.Payload)
|
||||
}
|
||||
got.Free()
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_BulkExpiry(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
|
||||
for i := 0; i < 50; i++ {
|
||||
peer := peerID(fmt.Sprintf("peer-%d", i))
|
||||
buf.put(peer, newTestMsg(pool, fmt.Sprintf("msg-%d", i)))
|
||||
}
|
||||
|
||||
// All should expire together
|
||||
time.Sleep(earlyMsgTTL + 500*time.Millisecond)
|
||||
|
||||
for i := 0; i < 50; i++ {
|
||||
_, ok := buf.pop(peerID(fmt.Sprintf("peer-%d", i)))
|
||||
if ok {
|
||||
t.Fatalf("peer-%d should have expired", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_ConcurrentPutAndPop(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
pool := newTestPool()
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Concurrent puts
|
||||
for i := 0; i < 100; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
peer := peerID(fmt.Sprintf("peer-%d", id))
|
||||
msg := newTestMsg(pool, fmt.Sprintf("msg-%d", id))
|
||||
if !buf.put(peer, msg) {
|
||||
msg.Free()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Concurrent pops
|
||||
var popped int64
|
||||
var mu sync.Mutex
|
||||
for i := 0; i < 100; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
peer := peerID(fmt.Sprintf("peer-%d", id))
|
||||
if msg, ok := buf.pop(peer); ok {
|
||||
msg.Free()
|
||||
mu.Lock()
|
||||
popped++
|
||||
mu.Unlock()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if popped != 100 {
|
||||
t.Fatalf("expected to pop 100 messages, got %d", popped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_ConcurrentPutPopAndClose(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
|
||||
pool := newTestPool()
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Concurrent puts
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
peer := peerID(fmt.Sprintf("peer-%d", id))
|
||||
msg := newTestMsg(pool, fmt.Sprintf("msg-%d", id))
|
||||
if !buf.put(peer, msg) {
|
||||
msg.Free()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Concurrent pops
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
peer := peerID(fmt.Sprintf("peer-%d", id))
|
||||
if msg, ok := buf.pop(peer); ok {
|
||||
msg.Free()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Close concurrently
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
buf.close()
|
||||
}()
|
||||
|
||||
wg.Wait() // should not panic or deadlock
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_OverwriteDoesNotLeak(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
// Use a dedicated pool to detect that overwritten message's Free was called
|
||||
freeCalled := make(chan struct{}, 1)
|
||||
origPool := &sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 64)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
b := make([]byte, 64)
|
||||
copy(b, "original")
|
||||
bufPtr := &b
|
||||
origMsg := Msg{
|
||||
bufPool: origPool,
|
||||
bufPtr: bufPtr,
|
||||
Payload: b[:8],
|
||||
}
|
||||
|
||||
peer := peerID("peer1")
|
||||
buf.put(peer, origMsg)
|
||||
|
||||
// Now check if the original buffer was freed by trying to get from pool
|
||||
// We need a wrapper pool that signals when Put is called
|
||||
trackPool := &sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 64)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
_ = trackPool
|
||||
|
||||
// Simpler approach: overwrite and check that only new value is returned
|
||||
newPool := newTestPool()
|
||||
buf.put(peer, newTestMsg(newPool, "replaced"))
|
||||
|
||||
// After overwrite, only the new message should be retrievable
|
||||
got, ok := buf.pop(peer)
|
||||
if !ok {
|
||||
t.Fatal("pop should find the message")
|
||||
}
|
||||
if string(got.Payload) != "replaced" {
|
||||
t.Fatalf("expected 'replaced', got '%s'", got.Payload)
|
||||
}
|
||||
got.Free()
|
||||
close(freeCalled)
|
||||
}
|
||||
|
||||
func TestEarlyMsgBuffer_EmptyBuffer(t *testing.T) {
|
||||
buf := newEarlyMsgBuffer()
|
||||
defer buf.close()
|
||||
|
||||
// Pop from empty buffer
|
||||
_, ok := buf.pop(peerID("anything"))
|
||||
if ok {
|
||||
t.Fatal("pop from empty buffer should return false")
|
||||
}
|
||||
|
||||
// Close empty buffer should be fine
|
||||
buf2 := newEarlyMsgBuffer()
|
||||
buf2.close()
|
||||
}
|
||||
Reference in new issue
Block a user