mirror of
https://github.com/h44z/wg-portal.git
synced 2025-10-06 16:36:18 +00:00
Compare commits
8 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
897a2bacf0 | ||
|
759cf3a0bc | ||
|
a07457b41f | ||
|
d7b52eba1c | ||
|
04bc0b7a81 | ||
|
19c58fb5af | ||
|
93db475eee | ||
|
9147fe33cb |
@@ -1,20 +1,85 @@
|
||||
version: 2.1
|
||||
|
||||
jobs:
|
||||
build:
|
||||
working_directory: ~/repo
|
||||
docker:
|
||||
- image: circleci/golang:1.16.7
|
||||
build-latest:
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
keys:
|
||||
- go-mod-v4-{{ checksum "go.sum" }}
|
||||
- go-mod-latest-v4-{{ checksum "go.sum" }}
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
command: |
|
||||
make dep
|
||||
- save_cache:
|
||||
key: go-mod-v4-{{ checksum "go.sum" }}
|
||||
key: go-mod-latest-v4-{{ checksum "go.sum" }}
|
||||
paths:
|
||||
- "~/go/pkg/mod"
|
||||
- run:
|
||||
name: Build AMD64
|
||||
command: |
|
||||
VERSION=$CIRCLE_BRANCH
|
||||
if [ ! -z "${CIRCLE_TAG}" ]; then VERSION=$CIRCLE_TAG; fi
|
||||
make ENV_BUILD_IDENTIFIER=$VERSION ENV_BUILD_VERSION=$(echo $CIRCLE_SHA1 | cut -c1-7) build
|
||||
- run:
|
||||
name: Install Cross-Platform Dependencies
|
||||
command: |
|
||||
sudo apt-get update
|
||||
sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install gcc-arm-linux-gnueabi libc6-dev-armel-cross gcc-arm-linux-gnueabihf libc6-dev-armhf-cross gcc-aarch64-linux-gnu libc6-dev-arm64-cross
|
||||
sudo ln -s /usr/include/asm-generic /usr/include/asm
|
||||
- run:
|
||||
name: Build ARM
|
||||
command: |
|
||||
VERSION=$CIRCLE_BRANCH
|
||||
if [ ! -z "${CIRCLE_TAG}" ]; then VERSION=$CIRCLE_TAG; fi
|
||||
make ENV_BUILD_IDENTIFIER=$VERSION ENV_BUILD_VERSION=$(echo $CIRCLE_SHA1 | cut -c1-7) build-cross-plat
|
||||
- store_artifacts:
|
||||
path: ~/repo/dist
|
||||
- run:
|
||||
name: "Publish Release on GitHub"
|
||||
command: |
|
||||
if [ ! -z "${CIRCLE_TAG}" ]; then
|
||||
go get github.com/tcnksm/ghr
|
||||
ghr -t ${GITHUB_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} -replace $CIRCLE_TAG ~/repo/dist
|
||||
fi
|
||||
working_directory: ~/repo
|
||||
docker:
|
||||
- image: cimg/go:1.17
|
||||
build-116: # just to validate compatibility with minimum go version
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
keys:
|
||||
- go-mod-116-v4-{{ checksum "go.sum" }}
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
command: |
|
||||
make dep
|
||||
- save_cache:
|
||||
key: go-mod-116-v4-{{ checksum "go.sum" }}
|
||||
paths:
|
||||
- "~/go/pkg/mod"
|
||||
- run:
|
||||
name: Build AMD64
|
||||
command: |
|
||||
VERSION=$CIRCLE_BRANCH
|
||||
if [ ! -z "${CIRCLE_TAG}" ]; then VERSION=$CIRCLE_TAG; fi
|
||||
make ENV_BUILD_IDENTIFIER=$VERSION ENV_BUILD_VERSION=$(echo $CIRCLE_SHA1 | cut -c1-7) build
|
||||
working_directory: ~/repo116
|
||||
docker:
|
||||
- image: cimg/go:1.16
|
||||
build-legacy:
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
keys:
|
||||
- go-mod-legacy-v4-{{ checksum "go.sum" }}
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
command: |
|
||||
make dep
|
||||
- save_cache:
|
||||
key: go-mod-legacy-v4-{{ checksum "go.sum" }}
|
||||
paths:
|
||||
- "/go/pkg/mod"
|
||||
- run:
|
||||
@@ -35,21 +100,40 @@ jobs:
|
||||
if [ ! -z "${CIRCLE_TAG}" ]; then VERSION=$CIRCLE_TAG; fi
|
||||
make ENV_BUILD_IDENTIFIER=$VERSION ENV_BUILD_VERSION=$(echo $CIRCLE_SHA1 | cut -c1-7) build-cross-plat
|
||||
- store_artifacts:
|
||||
path: ~/repo/dist
|
||||
path: ~/repolegacy/dist
|
||||
- run:
|
||||
name: "Publish Release on GitHub"
|
||||
name: "Publish Legacy Release on GitHub"
|
||||
command: |
|
||||
rm ~/repolegacy/dist/wg-portal.service ~/repolegacy/dist/wg-portal.env
|
||||
mv ~/repolegacy/dist/wg-portal-amd64 ~/repolegacy/dist/wg-portal-amd64-legacy
|
||||
mv ~/repolegacy/dist/wg-portal-arm ~/repolegacy/dist/wg-portal-arm-legacy
|
||||
mv ~/repolegacy/dist/wg-portal-arm64 ~/repolegacy/dist/wg-portal-arm64-legacy
|
||||
if [ ! -z "${CIRCLE_TAG}" ]; then
|
||||
go get github.com/tcnksm/ghr
|
||||
ghr -t ${GITHUB_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} -replace $CIRCLE_TAG ~/repo/dist
|
||||
ghr -t ${GITHUB_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} $CIRCLE_TAG ~/repolegacy/dist
|
||||
fi
|
||||
working_directory: ~/repolegacy
|
||||
docker:
|
||||
- image: circleci/golang:1.16-stretch
|
||||
|
||||
|
||||
workflows:
|
||||
build-and-release:
|
||||
jobs:
|
||||
#--------------- BUILD ---------------#
|
||||
- build:
|
||||
name: build
|
||||
- build-latest:
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- build-116:
|
||||
requires:
|
||||
- build-latest
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
||||
- build-legacy:
|
||||
requires:
|
||||
- build-latest
|
||||
filters:
|
||||
tags:
|
||||
only: /^v.*/
|
2
Makefile
2
Makefile
@@ -52,7 +52,7 @@ docker-push:
|
||||
docker push $(IMAGE)
|
||||
|
||||
api-docs:
|
||||
cd internal/server; swag init --parseDependency --parseInternal --generalInfo api.go
|
||||
cd internal/server; swag init --propertyStrategy pascalcase --parseDependency --parseInternal --generalInfo api.go
|
||||
$(GOCMD) fmt internal/server/docs/docs.go
|
||||
|
||||
$(BUILDDIR)/%-amd64: cmd/%/main.go dep phony
|
||||
|
@@ -115,6 +115,7 @@ The following configuration options are available:
|
||||
| WEBSITE_TITLE | title | core | WireGuard VPN | The website title. |
|
||||
| COMPANY_NAME | company | core | WireGuard Portal | The company name (for branding). |
|
||||
| MAIL_FROM | mailFrom | core | WireGuard VPN <noreply@company.com> | The email address from which emails are sent. |
|
||||
| LOGO_URL | logoUrl | core | /img/header-logo.png | The logo displayed in the page's header. |
|
||||
| ADMIN_USER | adminUser | core | admin@wgportal.local | The administrator user. Must be a valid email address. |
|
||||
| ADMIN_PASS | adminPass | core | wgportal | The administrator password. If unchanged, a random password will be set on first startup. |
|
||||
| EDITABLE_KEYS | editableKeys | core | true | Allow to edit key-pairs in the UI. |
|
||||
@@ -199,7 +200,9 @@ wg:
|
||||
### RESTful API
|
||||
WireGuard Portal offers a RESTful API to interact with.
|
||||
The API is documented using OpenAPI 2.0, the Swagger UI can be found
|
||||
under the URL `http://<your wg-portal ip/domain>/swagger/index.html`.
|
||||
under the URL `http://<your wg-portal ip/domain>/swagger/index.html?displayOperationId=true`.
|
||||
|
||||
The [API's unittesting](tests/test_API.py) may serve as an example how to make use of the API with python3 & pyswagger.
|
||||
|
||||
## What is out of scope
|
||||
* Creating or removing WireGuard (wgX) interfaces.
|
||||
|
@@ -64,6 +64,11 @@ pre{background:#f7f7f9}iframe{overflow:hidden;border:none}@media (min-width: 768
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
|
||||
.navbar-brand > img {
|
||||
height: 2rem;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.disabled-peer {
|
||||
color: #d03131;
|
||||
}
|
||||
|
@@ -1,3 +1,8 @@
|
||||
.navbar {
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
|
||||
.navbar-brand > img {
|
||||
height: 2rem;
|
||||
width: auto;
|
||||
}
|
@@ -28,7 +28,7 @@
|
||||
<div id="configContent" class="tab-content">
|
||||
<!-- server mode -->
|
||||
<div class="tab-pane fade {{if eq .Device.Type "server"}}active show{{end}}" id="server">
|
||||
<form method="post" enctype="multipart/form-data">
|
||||
<form method="post" enctype="multipart/form-data" name="server">
|
||||
<input type="hidden" name="_csrf" value="{{.Csrf}}">
|
||||
<input type="hidden" name="device" value="{{.Device.DeviceName}}">
|
||||
<input type="hidden" name="devicetype" value="server">
|
||||
@@ -162,7 +162,7 @@
|
||||
|
||||
<!-- client mode -->
|
||||
<div class="tab-pane fade {{if eq .Device.Type "client"}}active show{{end}}" id="client">
|
||||
<form method="post" enctype="multipart/form-data">
|
||||
<form method="post" enctype="multipart/form-data" name="client">
|
||||
<input type="hidden" name="_csrf" value="{{.Csrf}}">
|
||||
<input type="hidden" name="device" value="{{.Device.DeviceName}}">
|
||||
<input type="hidden" name="devicetype" value="client">
|
||||
|
@@ -15,7 +15,7 @@
|
||||
{{template "prt_nav.html" .}}
|
||||
<div class="container mt-2">
|
||||
<div class="page-header">
|
||||
<h1>WireGuard VPN Portal</h1>
|
||||
<h1>{{ .Static.WebsiteTitle }}</h1>
|
||||
</div>
|
||||
{{template "prt_flashes.html" .}}
|
||||
<p class="lead">WireGuard® is an extremely simple yet fast and modern VPN that utilizes state-of-the-art cryptography. It aims to be faster, simpler, leaner, and more useful than IPsec, while avoiding the massive headache. It intends to be considerably more performant than OpenVPN. </p>
|
||||
|
@@ -27,11 +27,11 @@
|
||||
<div class="card mt-5">
|
||||
<div class="card-header">Please sign in</div>
|
||||
<div class="card-body">
|
||||
<form class="form-signin" method="post">
|
||||
<form class="form-signin" method="post" name="login">
|
||||
<input type="hidden" name="_csrf" value="{{.Csrf}}">
|
||||
<div class="form-group">
|
||||
<label for="inputUsername">Email</label>
|
||||
<input type="text" name="username" class="form-control" id="inputUsername" aria-describedby="usernameHelp" placeholder="Enter email">
|
||||
<label for="inputUsername">Username</label>
|
||||
<input type="text" name="username" class="form-control" id="inputUsername" aria-describedby="usernameHelp" placeholder="Enter username or email">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="inputPassword">Password</label>
|
||||
|
@@ -1,5 +1,10 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
gldap "github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
|
||||
type Type string
|
||||
|
||||
const (
|
||||
@@ -24,4 +29,5 @@ type Config struct {
|
||||
LoginFilter string `yaml:"loginFilter" envconfig:"LDAP_LOGIN_FILTER"` // {{login_identifier}} gets replaced with the login email address
|
||||
SyncFilter string `yaml:"syncFilter" envconfig:"LDAP_SYNC_FILTER"`
|
||||
AdminLdapGroup string `yaml:"adminGroup" envconfig:"LDAP_ADMIN_GROUP"` // Members of this group receive admin rights in WG-Portal
|
||||
AdminLdapGroup_ *gldap.DN `yaml:"-"`
|
||||
}
|
||||
|
@@ -50,6 +50,7 @@ type ApiError struct {
|
||||
// GetUsers godoc
|
||||
// @Tags Users
|
||||
// @Summary Retrieves all users
|
||||
// @ID GetUsers
|
||||
// @Produce json
|
||||
// @Success 200 {object} []users.User
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -66,8 +67,9 @@ func (s *ApiServer) GetUsers(c *gin.Context) {
|
||||
// GetUser godoc
|
||||
// @Tags Users
|
||||
// @Summary Retrieves user based on given Email
|
||||
// @ID GetUser
|
||||
// @Produce json
|
||||
// @Param email query string true "User Email"
|
||||
// @Param Email query string true "User Email"
|
||||
// @Success 200 {object} users.User
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -76,9 +78,9 @@ func (s *ApiServer) GetUsers(c *gin.Context) {
|
||||
// @Router /backend/user [get]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) GetUser(c *gin.Context) {
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("email")))
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("Email")))
|
||||
if email == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "email parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "Email parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -93,9 +95,10 @@ func (s *ApiServer) GetUser(c *gin.Context) {
|
||||
// PostUser godoc
|
||||
// @Tags Users
|
||||
// @Summary Creates a new user based on the given user model
|
||||
// @ID PostUser
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param user body users.User true "User Model"
|
||||
// @Param User body users.User true "User Model"
|
||||
// @Success 200 {object} users.User
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -106,7 +109,7 @@ func (s *ApiServer) GetUser(c *gin.Context) {
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) PostUser(c *gin.Context) {
|
||||
newUser := users.User{}
|
||||
if err := c.BindJSON(&newUser); err != nil {
|
||||
if err := c.ShouldBindJSON(&newUser); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -132,10 +135,11 @@ func (s *ApiServer) PostUser(c *gin.Context) {
|
||||
// PutUser godoc
|
||||
// @Tags Users
|
||||
// @Summary Updates a user based on the given user model
|
||||
// @ID PutUser
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param email query string true "User Email"
|
||||
// @Param user body users.User true "User Model"
|
||||
// @Param Email query string true "User Email"
|
||||
// @Param User body users.User true "User Model"
|
||||
// @Success 200 {object} users.User
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -145,21 +149,21 @@ func (s *ApiServer) PostUser(c *gin.Context) {
|
||||
// @Router /backend/user [put]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) PutUser(c *gin.Context) {
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("email")))
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("Email")))
|
||||
if email == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "email parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "Email parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
updateUser := users.User{}
|
||||
if err := c.BindJSON(&updateUser); err != nil {
|
||||
if err := c.ShouldBindJSON(&updateUser); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Changing email address is not allowed
|
||||
if email != updateUser.Email {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "email parameter must match the model email address"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "Email parameter must match the model email address"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -184,10 +188,11 @@ func (s *ApiServer) PutUser(c *gin.Context) {
|
||||
// PatchUser godoc
|
||||
// @Tags Users
|
||||
// @Summary Updates a user based on the given partial user model
|
||||
// @ID PatchUser
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param email query string true "User Email"
|
||||
// @Param user body users.User true "User Model"
|
||||
// @Param Email query string true "User Email"
|
||||
// @Param User body users.User true "User Model"
|
||||
// @Success 200 {object} users.User
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -197,7 +202,7 @@ func (s *ApiServer) PutUser(c *gin.Context) {
|
||||
// @Router /backend/user [patch]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) PatchUser(c *gin.Context) {
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("email")))
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("Email")))
|
||||
if email == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "email parameter must be specified"})
|
||||
return
|
||||
@@ -250,8 +255,9 @@ func (s *ApiServer) PatchUser(c *gin.Context) {
|
||||
// DeleteUser godoc
|
||||
// @Tags Users
|
||||
// @Summary Deletes the specified user
|
||||
// @ID DeleteUser
|
||||
// @Produce json
|
||||
// @Param email query string true "User Email"
|
||||
// @Param Email query string true "User Email"
|
||||
// @Success 204 "No content"
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -261,7 +267,7 @@ func (s *ApiServer) PatchUser(c *gin.Context) {
|
||||
// @Router /backend/user [delete]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) DeleteUser(c *gin.Context) {
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("email")))
|
||||
email := strings.ToLower(strings.TrimSpace(c.Query("Email")))
|
||||
if email == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "email parameter must be specified"})
|
||||
return
|
||||
@@ -284,8 +290,9 @@ func (s *ApiServer) DeleteUser(c *gin.Context) {
|
||||
// GetPeers godoc
|
||||
// @Tags Peers
|
||||
// @Summary Retrieves all peers for the given interface
|
||||
// @ID GetPeers
|
||||
// @Produce json
|
||||
// @Param device query string true "Device Name"
|
||||
// @Param DeviceName query string true "Device Name"
|
||||
// @Success 200 {object} []wireguard.Peer
|
||||
// @Failure 401 {object} ApiError
|
||||
// @Failure 403 {object} ApiError
|
||||
@@ -293,9 +300,9 @@ func (s *ApiServer) DeleteUser(c *gin.Context) {
|
||||
// @Router /backend/peers [get]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) GetPeers(c *gin.Context) {
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("device")))
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("DeviceName")))
|
||||
if deviceName == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -312,8 +319,9 @@ func (s *ApiServer) GetPeers(c *gin.Context) {
|
||||
// GetPeer godoc
|
||||
// @Tags Peers
|
||||
// @Summary Retrieves the peer for the given public key
|
||||
// @ID GetPeer
|
||||
// @Produce json
|
||||
// @Param pkey query string true "Public Key (Base 64)"
|
||||
// @Param PublicKey query string true "Public Key (Base 64)"
|
||||
// @Success 200 {object} wireguard.Peer
|
||||
// @Failure 401 {object} ApiError
|
||||
// @Failure 403 {object} ApiError
|
||||
@@ -321,9 +329,9 @@ func (s *ApiServer) GetPeers(c *gin.Context) {
|
||||
// @Router /backend/peer [get]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) GetPeer(c *gin.Context) {
|
||||
pkey := c.Query("pkey")
|
||||
pkey := c.Query("PublicKey")
|
||||
if pkey == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "PublicKey parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -338,10 +346,11 @@ func (s *ApiServer) GetPeer(c *gin.Context) {
|
||||
// PostPeer godoc
|
||||
// @Tags Peers
|
||||
// @Summary Creates a new peer based on the given peer model
|
||||
// @ID PostPeer
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param device query string true "Device Name"
|
||||
// @Param peer body wireguard.Peer true "Peer Model"
|
||||
// @Param DeviceName query string true "Device Name"
|
||||
// @Param Peer body wireguard.Peer true "Peer Model"
|
||||
// @Success 200 {object} wireguard.Peer
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -351,9 +360,9 @@ func (s *ApiServer) GetPeer(c *gin.Context) {
|
||||
// @Router /backend/peers [post]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) PostPeer(c *gin.Context) {
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("device")))
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("DeviceName")))
|
||||
if deviceName == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -364,7 +373,7 @@ func (s *ApiServer) PostPeer(c *gin.Context) {
|
||||
}
|
||||
|
||||
newPeer := wireguard.Peer{}
|
||||
if err := c.BindJSON(&newPeer); err != nil {
|
||||
if err := c.ShouldBindJSON(&newPeer); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -390,10 +399,11 @@ func (s *ApiServer) PostPeer(c *gin.Context) {
|
||||
// PutPeer godoc
|
||||
// @Tags Peers
|
||||
// @Summary Updates the given peer based on the given peer model
|
||||
// @ID PutPeer
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param pkey query string true "Public Key"
|
||||
// @Param peer body wireguard.Peer true "Peer Model"
|
||||
// @Param PublicKey query string true "Public Key"
|
||||
// @Param Peer body wireguard.Peer true "Peer Model"
|
||||
// @Success 200 {object} wireguard.Peer
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -404,14 +414,14 @@ func (s *ApiServer) PostPeer(c *gin.Context) {
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) PutPeer(c *gin.Context) {
|
||||
updatePeer := wireguard.Peer{}
|
||||
if err := c.BindJSON(&updatePeer); err != nil {
|
||||
if err := c.ShouldBindJSON(&updatePeer); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
pkey := c.Query("pkey")
|
||||
pkey := c.Query("PublicKey")
|
||||
if pkey == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "PublicKey parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -422,7 +432,7 @@ func (s *ApiServer) PutPeer(c *gin.Context) {
|
||||
|
||||
// Changing public key is not allowed
|
||||
if pkey != updatePeer.PublicKey {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must match the model public key"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "PublicKey parameter must match the model public key"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -446,10 +456,11 @@ func (s *ApiServer) PutPeer(c *gin.Context) {
|
||||
// PatchPeer godoc
|
||||
// @Tags Peers
|
||||
// @Summary Updates the given peer based on the given partial peer model
|
||||
// @ID PatchPeer
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param pkey query string true "Public Key"
|
||||
// @Param peer body wireguard.Peer true "Peer Model"
|
||||
// @Param PublicKey query string true "Public Key"
|
||||
// @Param Peer body wireguard.Peer true "Peer Model"
|
||||
// @Success 200 {object} wireguard.Peer
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -465,7 +476,7 @@ func (s *ApiServer) PatchPeer(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
pkey := c.Query("pkey")
|
||||
pkey := c.Query("PublicKey")
|
||||
if pkey == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must be specified"})
|
||||
return
|
||||
@@ -498,7 +509,7 @@ func (s *ApiServer) PatchPeer(c *gin.Context) {
|
||||
|
||||
// Changing public key is not allowed
|
||||
if pkey != mergedPeer.PublicKey {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must match the model public key"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "PublicKey parameter must match the model public key"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -522,8 +533,9 @@ func (s *ApiServer) PatchPeer(c *gin.Context) {
|
||||
// DeletePeer godoc
|
||||
// @Tags Peers
|
||||
// @Summary Updates the given peer based on the given partial peer model
|
||||
// @ID DeletePeer
|
||||
// @Produce json
|
||||
// @Param pkey query string true "Public Key"
|
||||
// @Param PublicKey query string true "Public Key"
|
||||
// @Success 202 "No Content"
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -533,9 +545,9 @@ func (s *ApiServer) PatchPeer(c *gin.Context) {
|
||||
// @Router /backend/peer [delete]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) DeletePeer(c *gin.Context) {
|
||||
pkey := c.Query("pkey")
|
||||
pkey := c.Query("PublicKey")
|
||||
if pkey == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "PublicKey parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -556,6 +568,7 @@ func (s *ApiServer) DeletePeer(c *gin.Context) {
|
||||
// GetDevices godoc
|
||||
// @Tags Interface
|
||||
// @Summary Get all devices
|
||||
// @ID GetDevices
|
||||
// @Produce json
|
||||
// @Success 200 {object} []wireguard.Device
|
||||
// @Failure 400 {object} ApiError
|
||||
@@ -580,8 +593,9 @@ func (s *ApiServer) GetDevices(c *gin.Context) {
|
||||
// GetDevice godoc
|
||||
// @Tags Interface
|
||||
// @Summary Get the given device
|
||||
// @ID GetDevice
|
||||
// @Produce json
|
||||
// @Param device query string true "Device Name"
|
||||
// @Param DeviceName query string true "Device Name"
|
||||
// @Success 200 {object} wireguard.Device
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -590,9 +604,9 @@ func (s *ApiServer) GetDevices(c *gin.Context) {
|
||||
// @Router /backend/device [get]
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) GetDevice(c *gin.Context) {
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("device")))
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("DeviceName")))
|
||||
if deviceName == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -614,10 +628,11 @@ func (s *ApiServer) GetDevice(c *gin.Context) {
|
||||
// PutDevice godoc
|
||||
// @Tags Interface
|
||||
// @Summary Updates the given device based on the given device model (UNIMPLEMENTED)
|
||||
// @ID PutDevice
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param device query string true "Device Name"
|
||||
// @Param body body wireguard.Device true "Device Model"
|
||||
// @Param DeviceName query string true "Device Name"
|
||||
// @Param Device body wireguard.Device true "Device Model"
|
||||
// @Success 200 {object} wireguard.Device
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -628,14 +643,14 @@ func (s *ApiServer) GetDevice(c *gin.Context) {
|
||||
// @Security ApiBasicAuth
|
||||
func (s *ApiServer) PutDevice(c *gin.Context) {
|
||||
updateDevice := wireguard.Device{}
|
||||
if err := c.BindJSON(&updateDevice); err != nil {
|
||||
if err := c.ShouldBindJSON(&updateDevice); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("device")))
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("DeviceName")))
|
||||
if deviceName == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -653,7 +668,7 @@ func (s *ApiServer) PutDevice(c *gin.Context) {
|
||||
|
||||
// Changing device name is not allowed
|
||||
if deviceName != updateDevice.DeviceName {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must match the model device name"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must match the model device name"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -665,10 +680,11 @@ func (s *ApiServer) PutDevice(c *gin.Context) {
|
||||
// PatchDevice godoc
|
||||
// @Tags Interface
|
||||
// @Summary Updates the given device based on the given partial device model (UNIMPLEMENTED)
|
||||
// @ID PatchDevice
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param device query string true "Device Name"
|
||||
// @Param body body wireguard.Device true "Device Model"
|
||||
// @Param DeviceName query string true "Device Name"
|
||||
// @Param Device body wireguard.Device true "Device Model"
|
||||
// @Success 200 {object} wireguard.Device
|
||||
// @Failure 400 {object} ApiError
|
||||
// @Failure 401 {object} ApiError
|
||||
@@ -684,9 +700,9 @@ func (s *ApiServer) PatchDevice(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("device")))
|
||||
deviceName := strings.ToLower(strings.TrimSpace(c.Query("DeviceName")))
|
||||
if deviceName == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -723,7 +739,7 @@ func (s *ApiServer) PatchDevice(c *gin.Context) {
|
||||
|
||||
// Changing device name is not allowed
|
||||
if deviceName != mergedDevice.DeviceName {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "device parameter must match the model device name"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "DeviceName parameter must match the model device name"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -742,8 +758,9 @@ type PeerDeploymentInformation struct {
|
||||
// GetPeerDeploymentInformation godoc
|
||||
// @Tags Provisioning
|
||||
// @Summary Retrieves all active peers for the given email address
|
||||
// @ID GetPeerDeploymentInformation
|
||||
// @Produce json
|
||||
// @Param email query string true "Email Address"
|
||||
// @Param Email query string true "Email Address"
|
||||
// @Success 200 {object} []PeerDeploymentInformation "All active WireGuard peers"
|
||||
// @Failure 401 {object} ApiError
|
||||
// @Failure 403 {object} ApiError
|
||||
@@ -751,9 +768,9 @@ type PeerDeploymentInformation struct {
|
||||
// @Router /provisioning/peers [get]
|
||||
// @Security GeneralBasicAuth
|
||||
func (s *ApiServer) GetPeerDeploymentInformation(c *gin.Context) {
|
||||
email := c.Query("email")
|
||||
email := c.Query("Email")
|
||||
if email == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "email parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "Email parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -792,8 +809,9 @@ func (s *ApiServer) GetPeerDeploymentInformation(c *gin.Context) {
|
||||
// GetPeerDeploymentConfig godoc
|
||||
// @Tags Provisioning
|
||||
// @Summary Retrieves the peer config for the given public key
|
||||
// @ID GetPeerDeploymentConfig
|
||||
// @Produce plain
|
||||
// @Param pkey query string true "Public Key (Base 64)"
|
||||
// @Param PublicKey query string true "Public Key (Base 64)"
|
||||
// @Success 200 {object} string "The WireGuard configuration file"
|
||||
// @Failure 401 {object} ApiError
|
||||
// @Failure 403 {object} ApiError
|
||||
@@ -801,9 +819,9 @@ func (s *ApiServer) GetPeerDeploymentInformation(c *gin.Context) {
|
||||
// @Router /provisioning/peer [get]
|
||||
// @Security GeneralBasicAuth
|
||||
func (s *ApiServer) GetPeerDeploymentConfig(c *gin.Context) {
|
||||
pkey := c.Query("pkey")
|
||||
pkey := c.Query("PublicKey")
|
||||
if pkey == "" {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "pkey parameter must be specified"})
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: "PublicKey parameter must be specified"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -849,9 +867,10 @@ type ProvisioningRequest struct {
|
||||
// PostPeerDeploymentConfig godoc
|
||||
// @Tags Provisioning
|
||||
// @Summary Creates the requested peer config and returns the config file
|
||||
// @ID PostPeerDeploymentConfig
|
||||
// @Accept json
|
||||
// @Produce plain
|
||||
// @Param body body ProvisioningRequest true "Provisioning Request Model"
|
||||
// @Param ProvisioningRequest body ProvisioningRequest true "Provisioning Request Model"
|
||||
// @Success 200 {object} string "The WireGuard configuration file"
|
||||
// @Failure 401 {object} ApiError
|
||||
// @Failure 403 {object} ApiError
|
||||
@@ -860,7 +879,7 @@ type ProvisioningRequest struct {
|
||||
// @Security GeneralBasicAuth
|
||||
func (s *ApiServer) PostPeerDeploymentConfig(c *gin.Context) {
|
||||
req := ProvisioningRequest{}
|
||||
if err := c.BindJSON(&req); err != nil {
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, ApiError{Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
@@ -12,6 +12,8 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
gldap "github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
var ErrInvalidSpecification = errors.New("specification must be a struct pointer")
|
||||
@@ -67,6 +69,7 @@ type Config struct {
|
||||
SelfProvisioningAllowed bool `yaml:"selfProvisioning" envconfig:"SELF_PROVISIONING"`
|
||||
LdapEnabled bool `yaml:"ldapEnabled" envconfig:"LDAP_ENABLED"`
|
||||
SessionSecret string `yaml:"sessionSecret" envconfig:"SESSION_SECRET"`
|
||||
LogoUrl string `yaml:"logoUrl" envconfig:"LOGO_URL"`
|
||||
} `yaml:"core"`
|
||||
Database common.DatabaseConfig `yaml:"database"`
|
||||
Email common.MailConfig `yaml:"email"`
|
||||
@@ -81,6 +84,7 @@ func NewConfig() *Config {
|
||||
cfg.Core.ListeningAddress = ":8123"
|
||||
cfg.Core.Title = "WireGuard VPN"
|
||||
cfg.Core.CompanyName = "WireGuard Portal"
|
||||
cfg.Core.LogoUrl = "/img/header-logo.png"
|
||||
cfg.Core.ExternalUrl = "http://localhost:8123"
|
||||
cfg.Core.MailFrom = "WireGuard VPN <noreply@company.com>"
|
||||
cfg.Core.AdminUser = "admin@wgportal.local"
|
||||
@@ -128,6 +132,10 @@ func NewConfig() *Config {
|
||||
if err != nil {
|
||||
logrus.Warnf("unable to load environment config: %v", err)
|
||||
}
|
||||
cfg.LDAP.AdminLdapGroup_, err = gldap.ParseDN(cfg.LDAP.AdminLdapGroup)
|
||||
if err != nil {
|
||||
logrus.Warnf("Parsing AdminLDAPGroup failed: %v", err)
|
||||
}
|
||||
|
||||
if cfg.WG.ManageIPAddresses && runtime.GOOS != "linux" {
|
||||
logrus.Warnf("managing IP addresses only works on linux, feature disabled...")
|
||||
|
@@ -1,14 +1,13 @@
|
||||
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
// This file was generated by swaggo/swag
|
||||
|
||||
package docs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/alecthomas/template"
|
||||
"github.com/swaggo/swag"
|
||||
)
|
||||
|
||||
@@ -16,7 +15,7 @@ var doc = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "{{.Description}}",
|
||||
"description": "{{escape .Description}}",
|
||||
"title": "{{.Title}}",
|
||||
"contact": {
|
||||
"name": "WireGuard Portal Project",
|
||||
@@ -45,11 +44,12 @@ var doc = `{
|
||||
"Interface"
|
||||
],
|
||||
"summary": "Get the given device",
|
||||
"operationId": "GetDevice",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Device Name",
|
||||
"name": "device",
|
||||
"name": "DeviceName",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -103,17 +103,18 @@ var doc = `{
|
||||
"Interface"
|
||||
],
|
||||
"summary": "Updates the given device based on the given device model (UNIMPLEMENTED)",
|
||||
"operationId": "PutDevice",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Device Name",
|
||||
"name": "device",
|
||||
"name": "DeviceName",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Device Model",
|
||||
"name": "body",
|
||||
"name": "Device",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -176,17 +177,18 @@ var doc = `{
|
||||
"Interface"
|
||||
],
|
||||
"summary": "Updates the given device based on the given partial device model (UNIMPLEMENTED)",
|
||||
"operationId": "PatchDevice",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Device Name",
|
||||
"name": "device",
|
||||
"name": "DeviceName",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Device Model",
|
||||
"name": "body",
|
||||
"name": "Device",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -248,6 +250,7 @@ var doc = `{
|
||||
"Interface"
|
||||
],
|
||||
"summary": "Get all devices",
|
||||
"operationId": "GetDevices",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
@@ -299,11 +302,12 @@ var doc = `{
|
||||
"Peers"
|
||||
],
|
||||
"summary": "Retrieves the peer for the given public key",
|
||||
"operationId": "GetPeer",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Public Key (Base 64)",
|
||||
"name": "pkey",
|
||||
"name": "PublicKey",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -351,17 +355,18 @@ var doc = `{
|
||||
"Peers"
|
||||
],
|
||||
"summary": "Updates the given peer based on the given peer model",
|
||||
"operationId": "PutPeer",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Public Key",
|
||||
"name": "pkey",
|
||||
"name": "PublicKey",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Peer Model",
|
||||
"name": "peer",
|
||||
"name": "Peer",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -421,11 +426,12 @@ var doc = `{
|
||||
"Peers"
|
||||
],
|
||||
"summary": "Updates the given peer based on the given partial peer model",
|
||||
"operationId": "DeletePeer",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Public Key",
|
||||
"name": "pkey",
|
||||
"name": "PublicKey",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -482,17 +488,18 @@ var doc = `{
|
||||
"Peers"
|
||||
],
|
||||
"summary": "Updates the given peer based on the given partial peer model",
|
||||
"operationId": "PatchPeer",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Public Key",
|
||||
"name": "pkey",
|
||||
"name": "PublicKey",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Peer Model",
|
||||
"name": "peer",
|
||||
"name": "Peer",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -554,11 +561,12 @@ var doc = `{
|
||||
"Peers"
|
||||
],
|
||||
"summary": "Retrieves all peers for the given interface",
|
||||
"operationId": "GetPeers",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Device Name",
|
||||
"name": "device",
|
||||
"name": "DeviceName",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -609,17 +617,18 @@ var doc = `{
|
||||
"Peers"
|
||||
],
|
||||
"summary": "Creates a new peer based on the given peer model",
|
||||
"operationId": "PostPeer",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Device Name",
|
||||
"name": "device",
|
||||
"name": "DeviceName",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Peer Model",
|
||||
"name": "peer",
|
||||
"name": "Peer",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -681,11 +690,12 @@ var doc = `{
|
||||
"Users"
|
||||
],
|
||||
"summary": "Retrieves user based on given Email",
|
||||
"operationId": "GetUser",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "User Email",
|
||||
"name": "email",
|
||||
"name": "Email",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -739,17 +749,18 @@ var doc = `{
|
||||
"Users"
|
||||
],
|
||||
"summary": "Updates a user based on the given user model",
|
||||
"operationId": "PutUser",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "User Email",
|
||||
"name": "email",
|
||||
"name": "Email",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "User Model",
|
||||
"name": "user",
|
||||
"name": "User",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -809,11 +820,12 @@ var doc = `{
|
||||
"Users"
|
||||
],
|
||||
"summary": "Deletes the specified user",
|
||||
"operationId": "DeleteUser",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "User Email",
|
||||
"name": "email",
|
||||
"name": "Email",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -870,17 +882,18 @@ var doc = `{
|
||||
"Users"
|
||||
],
|
||||
"summary": "Updates a user based on the given partial user model",
|
||||
"operationId": "PatchUser",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "User Email",
|
||||
"name": "email",
|
||||
"name": "Email",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "User Model",
|
||||
"name": "user",
|
||||
"name": "User",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -942,6 +955,7 @@ var doc = `{
|
||||
"Users"
|
||||
],
|
||||
"summary": "Retrieves all users",
|
||||
"operationId": "GetUsers",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
@@ -988,10 +1002,11 @@ var doc = `{
|
||||
"Users"
|
||||
],
|
||||
"summary": "Creates a new user based on the given user model",
|
||||
"operationId": "PostUser",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "User Model",
|
||||
"name": "user",
|
||||
"name": "User",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -1053,11 +1068,12 @@ var doc = `{
|
||||
"Provisioning"
|
||||
],
|
||||
"summary": "Retrieves the peer config for the given public key",
|
||||
"operationId": "GetPeerDeploymentConfig",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Public Key (Base 64)",
|
||||
"name": "pkey",
|
||||
"name": "PublicKey",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -1104,11 +1120,12 @@ var doc = `{
|
||||
"Provisioning"
|
||||
],
|
||||
"summary": "Retrieves all active peers for the given email address",
|
||||
"operationId": "GetPeerDeploymentInformation",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Email Address",
|
||||
"name": "email",
|
||||
"name": "Email",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
@@ -1159,10 +1176,11 @@ var doc = `{
|
||||
"Provisioning"
|
||||
],
|
||||
"summary": "Creates the requested peer config and returns the config file",
|
||||
"operationId": "PostPeerDeploymentConfig",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Provisioning Request Model",
|
||||
"name": "body",
|
||||
"name": "ProvisioningRequest",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
@@ -1200,22 +1218,10 @@ var doc = `{
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"gorm.DeletedAt": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"time": {
|
||||
"type": "string"
|
||||
},
|
||||
"valid": {
|
||||
"description": "Valid is true if Time is not NULL",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"server.ApiError": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"message": {
|
||||
"Message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1223,16 +1229,16 @@ var doc = `{
|
||||
"server.PeerDeploymentInformation": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"device": {
|
||||
"Device": {
|
||||
"type": "string"
|
||||
},
|
||||
"deviceIdentifier": {
|
||||
"DeviceIdentifier": {
|
||||
"type": "string"
|
||||
},
|
||||
"identifier": {
|
||||
"Identifier": {
|
||||
"type": "string"
|
||||
},
|
||||
"publicKey": {
|
||||
"PublicKey": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1240,30 +1246,30 @@ var doc = `{
|
||||
"server.ProvisioningRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
"identifier"
|
||||
"Email",
|
||||
"Identifier"
|
||||
],
|
||||
"properties": {
|
||||
"allowedIPsStr": {
|
||||
"AllowedIPsStr": {
|
||||
"type": "string"
|
||||
},
|
||||
"deviceName": {
|
||||
"DNSStr": {
|
||||
"type": "string"
|
||||
},
|
||||
"DeviceName": {
|
||||
"description": "DeviceName is optional, if not specified, the configured default device will be used.",
|
||||
"type": "string"
|
||||
},
|
||||
"dnsstr": {
|
||||
"Email": {
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"Identifier": {
|
||||
"type": "string"
|
||||
},
|
||||
"identifier": {
|
||||
"type": "string"
|
||||
},
|
||||
"mtu": {
|
||||
"Mtu": {
|
||||
"type": "integer"
|
||||
},
|
||||
"persistentKeepalive": {
|
||||
"PersistentKeepalive": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
@@ -1271,43 +1277,43 @@ var doc = `{
|
||||
"users.User": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
"firstname",
|
||||
"lastname"
|
||||
"Email",
|
||||
"Firstname",
|
||||
"Lastname"
|
||||
],
|
||||
"properties": {
|
||||
"createdAt": {
|
||||
"CreatedAt": {
|
||||
"description": "database internal fields",
|
||||
"type": "string"
|
||||
},
|
||||
"deletedAt": {
|
||||
"$ref": "#/definitions/gorm.DeletedAt"
|
||||
"DeletedAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"Email": {
|
||||
"description": "required fields",
|
||||
"type": "string"
|
||||
},
|
||||
"firstname": {
|
||||
"Firstname": {
|
||||
"description": "optional fields",
|
||||
"type": "string"
|
||||
},
|
||||
"isAdmin": {
|
||||
"IsAdmin": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"lastname": {
|
||||
"Lastname": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"Password": {
|
||||
"description": "optional, integrated password authentication",
|
||||
"type": "string"
|
||||
},
|
||||
"phone": {
|
||||
"Phone": {
|
||||
"type": "string"
|
||||
},
|
||||
"source": {
|
||||
"Source": {
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"UpdatedAt": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1315,87 +1321,87 @@ var doc = `{
|
||||
"wireguard.Device": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"deviceName",
|
||||
"ipsStr",
|
||||
"privateKey",
|
||||
"publicKey",
|
||||
"type"
|
||||
"DeviceName",
|
||||
"IPsStr",
|
||||
"PrivateKey",
|
||||
"PublicKey",
|
||||
"Type"
|
||||
],
|
||||
"properties": {
|
||||
"createdAt": {
|
||||
"CreatedAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"defaultAllowedIPsStr": {
|
||||
"description": "comma separated list of IPs that are used in the client config file",
|
||||
"type": "string"
|
||||
},
|
||||
"defaultEndpoint": {
|
||||
"description": "Settings that are applied to all peer by default",
|
||||
"type": "string"
|
||||
},
|
||||
"defaultPersistentKeepalive": {
|
||||
"type": "integer"
|
||||
},
|
||||
"deviceName": {
|
||||
"type": "string"
|
||||
},
|
||||
"displayName": {
|
||||
"type": "string"
|
||||
},
|
||||
"dnsstr": {
|
||||
"DNSStr": {
|
||||
"description": "comma separated list of the DNS servers of the client, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"firewallMark": {
|
||||
"DefaultAllowedIPsStr": {
|
||||
"description": "comma separated list of IPs that are used in the client config file",
|
||||
"type": "string"
|
||||
},
|
||||
"DefaultEndpoint": {
|
||||
"description": "Settings that are applied to all peer by default",
|
||||
"type": "string"
|
||||
},
|
||||
"DefaultPersistentKeepalive": {
|
||||
"type": "integer"
|
||||
},
|
||||
"ipsStr": {
|
||||
"DeviceName": {
|
||||
"type": "string"
|
||||
},
|
||||
"DisplayName": {
|
||||
"type": "string"
|
||||
},
|
||||
"FirewallMark": {
|
||||
"type": "integer"
|
||||
},
|
||||
"IPsStr": {
|
||||
"description": "comma separated list of the IPs of the client, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"listenPort": {
|
||||
"ListenPort": {
|
||||
"type": "integer"
|
||||
},
|
||||
"mtu": {
|
||||
"Mtu": {
|
||||
"description": "the interface MTU, wg-quick addition",
|
||||
"type": "integer"
|
||||
},
|
||||
"postDown": {
|
||||
"PostDown": {
|
||||
"description": "post down script, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"postUp": {
|
||||
"PostUp": {
|
||||
"description": "post up script, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"preDown": {
|
||||
"PreDown": {
|
||||
"description": "pre down script, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"preUp": {
|
||||
"PreUp": {
|
||||
"description": "pre up script, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"privateKey": {
|
||||
"PrivateKey": {
|
||||
"description": "Core WireGuard Settings (Interface section)",
|
||||
"type": "string"
|
||||
},
|
||||
"publicKey": {
|
||||
"PublicKey": {
|
||||
"description": "Misc. WireGuard Settings",
|
||||
"type": "string"
|
||||
},
|
||||
"routingTable": {
|
||||
"RoutingTable": {
|
||||
"description": "the routing table, wg-quick addition",
|
||||
"type": "string"
|
||||
},
|
||||
"saveConfig": {
|
||||
"SaveConfig": {
|
||||
"description": "if set to ` + "`" + `true', the configuration is saved from the current state of the interface upon shutdown, wg-quick addition",
|
||||
"type": "boolean"
|
||||
},
|
||||
"type": {
|
||||
"Type": {
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"UpdatedAt": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1403,71 +1409,84 @@ var doc = `{
|
||||
"wireguard.Peer": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"deviceName",
|
||||
"email",
|
||||
"identifier",
|
||||
"publicKey"
|
||||
"DeviceName",
|
||||
"DeviceType",
|
||||
"Email",
|
||||
"Identifier",
|
||||
"PublicKey",
|
||||
"UID"
|
||||
],
|
||||
"properties": {
|
||||
"allowedIPsStr": {
|
||||
"AllowedIPsSrvStr": {
|
||||
"description": "a comma separated list of IPs that are used in the server config file",
|
||||
"type": "string"
|
||||
},
|
||||
"AllowedIPsStr": {
|
||||
"description": "a comma separated list of IPs that are used in the client config file",
|
||||
"type": "string"
|
||||
},
|
||||
"createdAt": {
|
||||
"CreatedAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"createdBy": {
|
||||
"CreatedBy": {
|
||||
"type": "string"
|
||||
},
|
||||
"deactivatedAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"deviceName": {
|
||||
"type": "string"
|
||||
},
|
||||
"dnsstr": {
|
||||
"DNSStr": {
|
||||
"description": "comma separated list of the DNS servers for the client",
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"DeactivatedAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"endpoint": {
|
||||
"DeviceName": {
|
||||
"type": "string"
|
||||
},
|
||||
"identifier": {
|
||||
"description": "Identifier AND Email make a WireGuard peer unique",
|
||||
"DeviceType": {
|
||||
"type": "string"
|
||||
},
|
||||
"ignoreGlobalSettings": {
|
||||
"type": "boolean"
|
||||
"Email": {
|
||||
"type": "string"
|
||||
},
|
||||
"ipsStr": {
|
||||
"Endpoint": {
|
||||
"type": "string"
|
||||
},
|
||||
"IPsStr": {
|
||||
"description": "a comma separated list of IPs of the client",
|
||||
"type": "string"
|
||||
},
|
||||
"mtu": {
|
||||
"Identifier": {
|
||||
"description": "Identifier AND Email make a WireGuard peer unique",
|
||||
"type": "string"
|
||||
},
|
||||
"IgnoreGlobalSettings": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"Mtu": {
|
||||
"description": "Global Device Settings (can be ignored, only make sense if device is in server mode)",
|
||||
"type": "integer"
|
||||
},
|
||||
"persistentKeepalive": {
|
||||
"PersistentKeepalive": {
|
||||
"type": "integer"
|
||||
},
|
||||
"presharedKey": {
|
||||
"PresharedKey": {
|
||||
"type": "string"
|
||||
},
|
||||
"privateKey": {
|
||||
"PrivateKey": {
|
||||
"description": "Misc. WireGuard Settings",
|
||||
"type": "string"
|
||||
},
|
||||
"publicKey": {
|
||||
"PublicKey": {
|
||||
"description": "Core WireGuard Settings",
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"UID": {
|
||||
"description": "uid for html identification",
|
||||
"type": "string"
|
||||
},
|
||||
"updatedBy": {
|
||||
"UpdatedAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"UpdatedBy": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
@@ -1513,6 +1532,13 @@ func (s *s) ReadDoc() string {
|
||||
a, _ := json.Marshal(v)
|
||||
return string(a)
|
||||
},
|
||||
"escape": func(v interface{}) string {
|
||||
// escape tabs
|
||||
str := strings.Replace(v.(string), "\t", "\\t", -1)
|
||||
// replace " with \", and if that results in \\", replace that with \\\"
|
||||
str = strings.Replace(str, "\"", "\\\"", -1)
|
||||
return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1)
|
||||
},
|
||||
}).Parse(doc)
|
||||
if err != nil {
|
||||
return doc
|
||||
|
@@ -8,6 +8,8 @@ import (
|
||||
"github.com/h44z/wg-portal/internal/users"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
|
||||
gldap "github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
func (s *Server) SyncLdapWithUserDatabase() {
|
||||
@@ -42,6 +44,19 @@ func (s *Server) SyncLdapWithUserDatabase() {
|
||||
logrus.Info("ldap user synchronization stopped")
|
||||
}
|
||||
|
||||
func (s Server)userIsInAdminGroup(ldapData *ldap.RawLdapData) bool {
|
||||
if s.config.LDAP.AdminLdapGroup_ == nil {
|
||||
return false
|
||||
}
|
||||
for _, group := range ldapData.RawAttributes[s.config.LDAP.GroupMemberAttribute] {
|
||||
var dn,_ = gldap.ParseDN(string(group))
|
||||
if s.config.LDAP.AdminLdapGroup_.Equal(dn) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s Server) userChangedInLdap(user *users.User, ldapData *ldap.RawLdapData) bool {
|
||||
if user.Firstname != ldapData.Attributes[s.config.LDAP.FirstNameAttribute] {
|
||||
return true
|
||||
@@ -63,14 +78,7 @@ func (s Server) userChangedInLdap(user *users.User, ldapData *ldap.RawLdapData)
|
||||
return true
|
||||
}
|
||||
|
||||
ldapAdmin := false
|
||||
for _, group := range ldapData.RawAttributes[s.config.LDAP.GroupMemberAttribute] {
|
||||
if string(group) == s.config.LDAP.AdminLdapGroup {
|
||||
ldapAdmin = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if user.IsAdmin != ldapAdmin {
|
||||
if user.IsAdmin != s.userIsInAdminGroup(ldapData) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -143,17 +151,10 @@ func (s *Server) updateLdapUsers(ldapUsers []ldap.RawLdapData) {
|
||||
user.Lastname = ldapUsers[i].Attributes[s.config.LDAP.LastNameAttribute]
|
||||
user.Email = ldapUsers[i].Attributes[s.config.LDAP.EmailAttribute]
|
||||
user.Phone = ldapUsers[i].Attributes[s.config.LDAP.PhoneAttribute]
|
||||
user.IsAdmin = false
|
||||
user.IsAdmin = s.userIsInAdminGroup(&ldapUsers[i])
|
||||
user.Source = users.UserSourceLdap
|
||||
user.DeletedAt = gorm.DeletedAt{} // Not deleted
|
||||
|
||||
for _, group := range ldapUsers[i].RawAttributes[s.config.LDAP.GroupMemberAttribute] {
|
||||
if string(group) == s.config.LDAP.AdminLdapGroup {
|
||||
user.IsAdmin = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err = s.users.UpdateUser(user); err != nil {
|
||||
logrus.Errorf("failed to update ldap user %s in database: %v", user.Email, err)
|
||||
continue
|
||||
|
@@ -253,7 +253,7 @@ func (s *Server) getExecutableDirectory() string {
|
||||
func (s *Server) getStaticData() StaticData {
|
||||
return StaticData{
|
||||
WebsiteTitle: s.config.Core.Title,
|
||||
WebsiteLogo: "/img/header-logo.png",
|
||||
WebsiteLogo: s.config.Core.LogoUrl,
|
||||
CompanyName: s.config.Core.CompanyName,
|
||||
Year: time.Now().Year(),
|
||||
Version: Version,
|
||||
|
@@ -42,5 +42,5 @@ type User struct {
|
||||
// database internal fields
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:",omitempty"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:",omitempty" swaggertype:"string"`
|
||||
}
|
||||
|
@@ -66,9 +66,9 @@ type Peer struct {
|
||||
Peer *wgtypes.Peer `gorm:"-" json:"-"` // WireGuard peer
|
||||
Config string `gorm:"-" json:"-"`
|
||||
|
||||
UID string `form:"uid" binding:"required,alphanum" json:"-"` // uid for html identification
|
||||
UID string `form:"uid" binding:"required,alphanum"` // uid for html identification
|
||||
DeviceName string `gorm:"index" form:"device" binding:"required"`
|
||||
DeviceType DeviceType `gorm:"-" form:"devicetype" binding:"required,oneof=client server" json:"-"`
|
||||
DeviceType DeviceType `gorm:"-" form:"devicetype" binding:"required,oneof=client server"`
|
||||
Identifier string `form:"identifier" binding:"required,max=64"` // Identifier AND Email make a WireGuard peer unique
|
||||
Email string `gorm:"index" form:"mail" binding:"required,email"`
|
||||
IgnoreGlobalSettings bool `form:"ignoreglobalsettings"`
|
||||
@@ -244,7 +244,7 @@ type Device struct {
|
||||
Peers []Peer `gorm:"foreignKey:DeviceName" binding:"-" json:"-"` // linked WireGuard peers
|
||||
|
||||
Type DeviceType `form:"devicetype" binding:"required,oneof=client server"`
|
||||
DeviceName string `form:"device" gorm:"primaryKey" binding:"required,alphanum"`
|
||||
DeviceName string `form:"device" gorm:"primaryKey" binding:"required" validator:"regexp=[0-9a-zA-Z\-]+"`
|
||||
DisplayName string `form:"displayname" binding:"omitempty,max=200"`
|
||||
|
||||
// Core WireGuard Settings (Interface section)
|
||||
|
59
tests/README.md
Normal file
59
tests/README.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# pyswagger unittests for the API & UI
|
||||
|
||||
## Requirements
|
||||
|
||||
```
|
||||
wg-quick up conf/wg-example0.conf
|
||||
sudo LOG_LEVEL=debug CONFIG_FILE=conf/config.yml ../dist/wg-portal-amd64
|
||||
|
||||
python3 -m venv ~/venv/apitest
|
||||
~/venv/apitest/bin/pip install pyswagger mechanize requests pytest PyYAML
|
||||
```
|
||||
|
||||
## Running
|
||||
|
||||
### API
|
||||
```
|
||||
~/venv/apitest/bin/python3 -m unittest test_API.TestAPI
|
||||
```
|
||||
|
||||
### UI
|
||||
```
|
||||
~/venv/lsl/bin/pytest pytest_UI.py
|
||||
```
|
||||
|
||||
|
||||
## Debugging
|
||||
Debugging for requests http request/response is included for the API unittesting.
|
||||
To use, adjust the log level for "api" logger to DEBUG
|
||||
|
||||
```python
|
||||
log.setLevel(logging.DEBUG)
|
||||
<action>
|
||||
log.setLevel(logging.INFO)
|
||||
```
|
||||
This will provide:
|
||||
```
|
||||
2021-09-29 14:55:15,585 DEBUG api HTTP
|
||||
---------------- request ----------------
|
||||
GET http://localhost:8123/api/v1/provisioning/peers?Email=test%2Bn4gbm7%40example.org
|
||||
User-Agent: python-requests/2.26.0
|
||||
Accept-Encoding: gzip, deflate
|
||||
Accept: application/json
|
||||
Connection: keep-alive
|
||||
Authorization: Basic d2dAZXhhbXBsZS5vcmc6YWJhZGNob2ljZQ==
|
||||
|
||||
None
|
||||
---------------- response ----------------
|
||||
200 OK http://localhost:8123/api/v1/provisioning/peers?Email=test%2Bn4gbm7%40example.org
|
||||
Content-Type: application/json; charset=utf-8
|
||||
Date: Wed, 29 Sep 2021 12:55:15 GMT
|
||||
Content-Length: 285
|
||||
|
||||
[{"PublicKey":"hO3pxnft/8QL6nbE+79HN464Z+L4+D/JjUvNE+8LmTs=",
|
||||
"Identifier":"Test User (Default)","Device":"wg-example0","DeviceIdentifier":"example0"},
|
||||
{"PublicKey":"RVS2gsdRpFjyOpr1nAlEkrs194lQytaPHhaxL5amQxY=",
|
||||
"Identifier":"debug","Device":"wg-example0","DeviceIdentifier":"example0"}]
|
||||
```
|
||||
|
||||
|
27
tests/conf/config.yml
Normal file
27
tests/conf/config.yml
Normal file
@@ -0,0 +1,27 @@
|
||||
core:
|
||||
listeningAddress: :8123
|
||||
externalUrl: https://wg.example.org
|
||||
title: Example WireGuard VPN
|
||||
company: Example.org
|
||||
mailFrom: WireGuard VPN <noreply+wg@example.org>
|
||||
logoUrl: /img/logo.png
|
||||
adminUser: wg@example.org
|
||||
adminPass: abadchoice
|
||||
editableKeys: true
|
||||
createDefaultPeer: true
|
||||
selfProvisioning: true
|
||||
ldapEnabled: false
|
||||
database:
|
||||
typ: sqlite
|
||||
database: test.db
|
||||
# :memory: does not work
|
||||
email:
|
||||
host: 127.0.0.1
|
||||
port: 25
|
||||
tls: false
|
||||
wg:
|
||||
devices:
|
||||
- wg-example0
|
||||
defaultDevice: wg-example0
|
||||
configDirectory: /etc/wireguard
|
||||
manageIPAddresses: true
|
16
tests/conf/wg-example0.conf
Normal file
16
tests/conf/wg-example0.conf
Normal file
@@ -0,0 +1,16 @@
|
||||
# AUTOGENERATED FILE - DO NOT EDIT
|
||||
# -WGP- Interface: wg-example / Updated: 2021-09-27 08:52:05.537618409 +0000 UTC / Created: 2021-09-24 10:06:46.903674496 +0000 UTC
|
||||
# -WGP- Interface display name: TheInterface
|
||||
# -WGP- Interface mode: server
|
||||
# -WGP- PublicKey = HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=
|
||||
|
||||
[Interface]
|
||||
|
||||
# Core settings
|
||||
PrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=
|
||||
Address = 10.0.0.0/24
|
||||
|
||||
# Misc. settings (optional)
|
||||
ListenPort = 51820
|
||||
FwMark = 1
|
||||
SaveConfig = true
|
214
tests/pytest_UI.py
Normal file
214
tests/pytest_UI.py
Normal file
@@ -0,0 +1,214 @@
|
||||
import logging.config
|
||||
import http.cookiejar
|
||||
import random
|
||||
import string
|
||||
|
||||
import mechanize
|
||||
import yaml
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def browser():
|
||||
# Fake Cookie Policy to send the Secure cookies via http
|
||||
class InSecureCookiePolicy(http.cookiejar.DefaultCookiePolicy):
|
||||
def set_ok(self, cookie, request):
|
||||
return True
|
||||
|
||||
def return_ok(self, cookie, request):
|
||||
return True
|
||||
|
||||
def domain_return_ok(self, domain, request):
|
||||
return True
|
||||
|
||||
def path_return_ok(self, path, request):
|
||||
return True
|
||||
|
||||
b = mechanize.Browser()
|
||||
b.set_cookiejar(http.cookiejar.CookieJar(InSecureCookiePolicy()))
|
||||
b.set_handle_robots(False)
|
||||
b.set_debug_http(True)
|
||||
return b
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config():
|
||||
cfg = yaml.load(open('conf/config.yml', 'r'))
|
||||
return cfg
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def admin(browser, config):
|
||||
auth = (c := config['core'])['adminUser'], c['adminPass']
|
||||
return _login(browser, auth)
|
||||
|
||||
def _create_user(admin, values):
|
||||
b = admin
|
||||
b.follow_link(text="User Management")
|
||||
b.follow_link(predicate=has_attr('Add a user'))
|
||||
|
||||
# FIXME name form
|
||||
b.select_form(predicate=lambda x: x.method == 'post')
|
||||
for k, v in values.items():
|
||||
b.form.set_value(v, k)
|
||||
b.submit()
|
||||
alert = b._factory.root.findall('body/div/div[@role="alert"]')
|
||||
assert len(alert) == 1 and alert[0].text.strip() == "user created successfully"
|
||||
return values["email"],values["password"]
|
||||
|
||||
def _destroy_user(admin, uid):
|
||||
b = admin
|
||||
b.follow_link(text="User Management")
|
||||
for user in b._factory.root.findall('body/div/div/table[@id="userTable"]/tbody/'):
|
||||
email,*_ = list(map(lambda x: x.text.strip() if x.text else '', list(user)))
|
||||
if email == uid:
|
||||
break
|
||||
else:
|
||||
assert False
|
||||
a = user.findall('td/a[@title="Edit user"]')
|
||||
assert len(a) == 1
|
||||
b.follow_link(url=a[0].attrib['href'])
|
||||
|
||||
# FIXME name form
|
||||
b.select_form(predicate=lambda x: x.method == 'post')
|
||||
disabled = b.find_control("isdisabled")
|
||||
disabled.set_single("true")
|
||||
b.submit()
|
||||
|
||||
def _destroy_peer(admin, uid):
|
||||
b = admin
|
||||
b.follow_link(text="Administration")
|
||||
peers = b._factory.root.findall('body/div/div/table[@id="userTable"]/tbody/tr')
|
||||
for idx,peer in enumerate(peers):
|
||||
if idx % 2 == 1:
|
||||
continue
|
||||
head, Identifier, PublicKey, EMail, IPs, Handshake, tail = list(map(lambda x: x.text.strip() if x.text else x, list(peer)))
|
||||
print(Identifier)
|
||||
if EMail != uid:
|
||||
continue
|
||||
peer = peers[idx+1]
|
||||
a = peer.findall('.//a[@title="Delete peer"]')
|
||||
assert len(a) == 1
|
||||
b.follow_link(url=a[0].attrib['href'])
|
||||
|
||||
|
||||
def _list_peers(user):
|
||||
r = []
|
||||
b = user
|
||||
b.follow_link(predicate=has_attr('User-Profile'))
|
||||
profiles = b._factory.root.findall('body/div/div/table[@id="userTable"]/tbody/tr')
|
||||
for idx,profile in enumerate(profiles):
|
||||
if idx % 2 == 1:
|
||||
continue
|
||||
head, Identifier, PublicKey, EMail, IPs, Handshake = list(map(lambda x: x.text.strip() if x.text else x, list(profile)))
|
||||
profile = profiles[idx+1]
|
||||
pre = profile.findall('.//pre')
|
||||
assert len(pre) == 1
|
||||
r.append((PublicKey, pre))
|
||||
return r
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def user_data():
|
||||
values = {
|
||||
"email": f"test+{randstr()}@example.org",
|
||||
"password": randstr(12),
|
||||
"firstname": randstr(8),
|
||||
"lastname": randstr(12)
|
||||
}
|
||||
return values
|
||||
|
||||
@pytest.fixture
|
||||
def user(admin, user_data, config):
|
||||
b = admin
|
||||
auth = _create_user(b, user_data)
|
||||
_logout(b)
|
||||
_login(b, auth)
|
||||
assert b.find_link(predicate=has_attr('User-Profile'))
|
||||
yield b
|
||||
_logout(b)
|
||||
auth = (c := config['core'])['adminUser'], c['adminPass']
|
||||
_login(b, auth)
|
||||
_destroy_user(b, user_data["email"])
|
||||
_destroy_peer(b, user_data["email"])
|
||||
|
||||
@pytest.fixture
|
||||
def peer(admin, user, user_data):
|
||||
pass
|
||||
|
||||
def _login(browser, auth):
|
||||
b = browser
|
||||
b.open("http://localhost:8123/")
|
||||
|
||||
b.follow_link(text="Login")
|
||||
|
||||
b.select_form(name="login")
|
||||
username, password = auth
|
||||
b.form.set_value(username, "username")
|
||||
b.form.set_value(password, "password")
|
||||
b.submit()
|
||||
return b
|
||||
|
||||
def _logout(browser):
|
||||
browser.follow_link(text="Logout")
|
||||
return browser
|
||||
|
||||
def has_attr(value, attr='title'):
|
||||
def find_attr(x):
|
||||
return any([a == (attr, value) for a in x.attrs])
|
||||
return find_attr
|
||||
|
||||
|
||||
def _server(browser, addr):
|
||||
b = browser
|
||||
b.follow_link(text="Administration")
|
||||
b.follow_link(predicate=has_attr('Edit interface settings'))
|
||||
b.select_form("server")
|
||||
|
||||
values = {
|
||||
"displayname": "example0",
|
||||
"endpoint": "wg.example.org:51280",
|
||||
"ip": addr
|
||||
}
|
||||
for k, v in values.items():
|
||||
b.form.set_value(v, k)
|
||||
|
||||
b.submit()
|
||||
return b
|
||||
|
||||
@pytest.fixture
|
||||
def server(admin):
|
||||
return _server(admin, "10.0.0.0/24")
|
||||
|
||||
def randstr(l=6):
|
||||
return ''.join([random.choice(string.ascii_lowercase + string.digits) for i in range(l)])
|
||||
|
||||
|
||||
def test_admin_login(admin):
|
||||
b = admin
|
||||
b.find_link("Administration")
|
||||
|
||||
|
||||
def test_admin_server(admin):
|
||||
ip = "10.0.0.0/28"
|
||||
b = _server(admin, ip)
|
||||
b.select_form("server")
|
||||
assert ip == b.form.get_value("ip")
|
||||
|
||||
|
||||
def test_admin_create_peer(server, user_data):
|
||||
auth = _create_user(server, user_data)
|
||||
|
||||
|
||||
def test_admin_create_user(admin, user_data):
|
||||
auth = _create_user(admin, user_data)
|
||||
|
||||
|
||||
def test_user_login(server, user):
|
||||
b = user
|
||||
b.follow_link(predicate=has_attr('User-Profile'))
|
||||
|
||||
def test_user_config(server, user):
|
||||
b = user
|
||||
peers = _list_peers(b)
|
||||
assert len(peers) >= 1
|
484
tests/test_API.py
Normal file
484
tests/test_API.py
Normal file
@@ -0,0 +1,484 @@
|
||||
import ipaddress
|
||||
import collections
|
||||
import string
|
||||
import unittest
|
||||
import datetime
|
||||
import re
|
||||
import uuid
|
||||
import subprocess
|
||||
import random
|
||||
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
import mechanize
|
||||
|
||||
from pyswagger import App, Security
|
||||
from pyswagger.contrib.client.requests import Client
|
||||
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
class HttpFormatter(logging.Formatter):
|
||||
|
||||
def _formatHeaders(self, d):
|
||||
return '\n'.join(f'{k}: {v}' for k, v in d.items())
|
||||
|
||||
def formatMessage(self, record):
|
||||
result = super().formatMessage(record)
|
||||
if record.name == 'api':
|
||||
result += '''
|
||||
---------------- request ----------------
|
||||
{req.method} {req.url}
|
||||
{reqhdrs}
|
||||
|
||||
{req.body}
|
||||
---------------- response ----------------
|
||||
{res.status_code} {res.reason} {res.url}
|
||||
{reshdrs}
|
||||
|
||||
{res.text}
|
||||
---------------- end ----------------
|
||||
'''.format(req=record.req, res=record.res, reqhdrs=self._formatHeaders(record.req.headers),
|
||||
reshdrs=self._formatHeaders(record.res.headers), )
|
||||
|
||||
return result
|
||||
|
||||
|
||||
logging.config.dictConfig(
|
||||
{
|
||||
"version": 1,
|
||||
"formatters": {
|
||||
"http": {
|
||||
"()": HttpFormatter,
|
||||
"format": "{asctime} {levelname} {name} {message}",
|
||||
"style":'{',
|
||||
},
|
||||
"detailed": {
|
||||
"class": "logging.Formatter",
|
||||
"format": "%(asctime)s %(name)-9s %(levelname)-4s %(message)s",
|
||||
},
|
||||
"plain": {
|
||||
"class": "logging.Formatter",
|
||||
"format": "%(message)s",
|
||||
}
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "detailed",
|
||||
},
|
||||
"console_http": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "http",
|
||||
},
|
||||
},
|
||||
"root": {
|
||||
"level": "DEBUG",
|
||||
"handlers": ["console"],
|
||||
"propagate": True
|
||||
},
|
||||
'loggers': {
|
||||
'api': {
|
||||
"level": "INFO",
|
||||
"handlers": ["console_http"]
|
||||
},
|
||||
"requests.packages.urllib3": {
|
||||
"level": "DEBUG",
|
||||
"handlers": ["console"],
|
||||
"propagate": True
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
class ApiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
def logHttp(response, *args, **kwargs):
|
||||
extra = {'req': response.request, 'res': response}
|
||||
log.debug('HTTP', extra=extra)
|
||||
|
||||
class WGPClient:
|
||||
def __init__(self, url, *auths):
|
||||
app = App._create_(url)
|
||||
auth = Security(app)
|
||||
for t, cred in auths:
|
||||
auth.update_with(t, cred)
|
||||
|
||||
client = Client(auth)
|
||||
self.app, self.client = app, client
|
||||
|
||||
self.client._Client__s.hooks['response'] = logHttp
|
||||
|
||||
def call(self, name, **kwargs):
|
||||
# print(f"{name} {kwargs}")
|
||||
op = self.app.op[name]
|
||||
req, resp = op(**kwargs)
|
||||
now = datetime.datetime.now()
|
||||
resp = self.client.request((req, resp))
|
||||
then = datetime.datetime.now()
|
||||
delta = then - now
|
||||
# print(f"{resp.status} {delta}")
|
||||
|
||||
if 200 <= resp.status <= 299:
|
||||
pass
|
||||
elif 400 <= resp.status <= 499:
|
||||
raise ApiError(resp.data["Message"])
|
||||
elif 500 == resp.status:
|
||||
raise ValueError(resp.data["Message"])
|
||||
elif 501 == resp.status:
|
||||
raise NotImplementedError(name)
|
||||
elif 502 <= resp.status <= 599:
|
||||
raise ApiError(resp.data["Message"])
|
||||
return resp
|
||||
|
||||
def GetDevice(self, **kwargs):
|
||||
return self.call("GetDevice", **kwargs).data
|
||||
|
||||
def PatchDevice(self, **kwargs):
|
||||
return self.call("PatchDevice", **kwargs).data
|
||||
|
||||
def PutDevice(self, **kwargs):
|
||||
return self.call("PutDevice", **kwargs).data
|
||||
|
||||
def GetDevices(self, **kwargs):
|
||||
# FIXME - could return empty list?
|
||||
return self.call("GetDevices", **kwargs).data or []
|
||||
|
||||
def DeletePeer(self, **kwargs):
|
||||
return self.call("DeletePeer", **kwargs).data
|
||||
|
||||
def GetPeer(self, **kwargs):
|
||||
return self.call("GetPeer", **kwargs).data
|
||||
|
||||
def PatchPeer(self, **kwargs):
|
||||
return self.call("PatchPeer", **kwargs).data
|
||||
|
||||
def PostPeer(self, **kwargs):
|
||||
return self.call("PostPeer", **kwargs).data
|
||||
|
||||
def PutPeer(self, **kwargs):
|
||||
return self.call("PutPeer", **kwargs).data
|
||||
|
||||
def GetPeerDeploymentConfig(self, **kwargs):
|
||||
return self.call("GetPeerDeploymentConfig", **kwargs).data
|
||||
|
||||
def PostPeerDeploymentConfig(self, **kwargs):
|
||||
return self.call("PostPeerDeploymentConfig", **kwargs).raw
|
||||
|
||||
def GetPeerDeploymentInformation(self, **kwargs):
|
||||
return self.call("GetPeerDeploymentInformation", **kwargs).data
|
||||
|
||||
def GetPeers(self, **kwargs):
|
||||
return self.call("GetPeers", **kwargs).data
|
||||
|
||||
def DeleteUser(self, **kwargs):
|
||||
return self.call("DeleteUser", **kwargs).data
|
||||
|
||||
def GetUser(self, **kwargs):
|
||||
return self.call("GetUser", **kwargs).data
|
||||
|
||||
def PatchUser(self, **kwargs):
|
||||
return self.call("PatchUser", **kwargs).data
|
||||
|
||||
def PostUser(self, **kwargs):
|
||||
return self.call("PostUser", **kwargs).data
|
||||
|
||||
def PutUser(self, **kwargs):
|
||||
return self.call("PutUser", **kwargs).data
|
||||
|
||||
def GetUsers(self, **kwargs):
|
||||
return self.call("GetUsers", **kwargs).data
|
||||
|
||||
|
||||
def generate_wireguard_keys():
|
||||
"""
|
||||
Generate a WireGuard private & public key
|
||||
Requires that the 'wg' command is available on PATH
|
||||
Returns (private_key, public_key), both strings
|
||||
"""
|
||||
privkey = subprocess.check_output("wg genkey", shell=True).decode("utf-8").strip()
|
||||
pubkey = subprocess.check_output(f"echo '{privkey}' | wg pubkey", shell=True).decode("utf-8").strip()
|
||||
return (privkey, pubkey)
|
||||
|
||||
|
||||
KeyTuple = collections.namedtuple("Keys", "private public")
|
||||
|
||||
|
||||
class TestAPI(unittest.TestCase):
|
||||
URL = 'http://localhost:8123/swagger/doc.json'
|
||||
AUTH = {
|
||||
"api": ('ApiBasicAuth', ("wg@example.org", "abadchoice")),
|
||||
"general": ('GeneralBasicAuth', ("wg@example.org", "abadchoice"))
|
||||
}
|
||||
DEVICE = "wg-example0"
|
||||
IFADDR = "10.17.0.0/24"
|
||||
log = logging.getLogger("TestAPI")
|
||||
|
||||
|
||||
def _client(self, *auth):
|
||||
auth = ["general"] if auth is None else auth
|
||||
self.c = WGPClient(self.URL, *[self.AUTH[i] for i in auth])
|
||||
|
||||
@property
|
||||
def randmail(self):
|
||||
return 'test+' + ''.join(
|
||||
[random.choice(string.ascii_lowercase + string.digits) for i in range(6)]) + '@example.org'
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.finishInstallation()
|
||||
|
||||
@classmethod
|
||||
def finishInstallation(cls) -> None:
|
||||
import http.cookiejar
|
||||
|
||||
# Fake Cookie Policy to send the Secure cookies via http
|
||||
class InSecureCookiePolicy(http.cookiejar.DefaultCookiePolicy):
|
||||
def set_ok(self, cookie, request):
|
||||
return True
|
||||
|
||||
def return_ok(self, cookie, request):
|
||||
return True
|
||||
|
||||
def domain_return_ok(self, domain, request):
|
||||
return True
|
||||
|
||||
def path_return_ok(self, path, request):
|
||||
return True
|
||||
|
||||
b = mechanize.Browser()
|
||||
b.set_cookiejar(http.cookiejar.CookieJar(InSecureCookiePolicy()))
|
||||
b.set_handle_robots(False)
|
||||
b.open("http://localhost:8123/")
|
||||
|
||||
b.follow_link(text="Login")
|
||||
|
||||
b.select_form(name="login")
|
||||
username, password = cls.AUTH['api'][1]
|
||||
b.form.set_value(username, "username")
|
||||
b.form.set_value(password, "password")
|
||||
|
||||
b.submit()
|
||||
|
||||
b.follow_link(text="Administration")
|
||||
b.follow_link(predicate=lambda x: any([a == ('title', 'Edit interface settings') for a in x.attrs]))
|
||||
b.select_form("server")
|
||||
|
||||
values = {
|
||||
"displayname": "example0",
|
||||
"endpoint": "wg.example.org:51280",
|
||||
"ip": cls.IFADDR
|
||||
}
|
||||
for k, v in values.items():
|
||||
b.form.set_value(v, k)
|
||||
|
||||
b.submit()
|
||||
|
||||
b.select_form("server")
|
||||
# cls.log.debug(b.form.get_value("ip"))
|
||||
|
||||
def setUp(self) -> None:
|
||||
self._client('api')
|
||||
self.user = self.randmail
|
||||
|
||||
# create a user …
|
||||
self.c.PostUser(User={"Firstname": "Test", "Lastname": "User", "Email": self.user})
|
||||
|
||||
self.keys = KeyTuple(*generate_wireguard_keys())
|
||||
|
||||
|
||||
def _test_generate(self):
|
||||
def key_of(op):
|
||||
a, *b = list(filter(lambda x: len(x), re.split("([A-Z][a-z]+)", op.operationId)))
|
||||
return ''.join(b), a
|
||||
|
||||
for op in sorted(self.c.app.op.values(), key=key_of):
|
||||
print(f"""
|
||||
def {op.operationId}(self, **kwargs):
|
||||
return self. call("{op.operationId}", **kwargs)
|
||||
""")
|
||||
|
||||
def test_ops(self):
|
||||
for op in sorted(self.c.app.op.values(), key=lambda op: op.operationId):
|
||||
self.assertTrue(hasattr(self.c, op.operationId), f"{op.operationId} is missing")
|
||||
|
||||
def test_Device(self):
|
||||
# FIXME device has to be completed via webif to be valid before it can be used via API
|
||||
devices = self.c.GetDevices()
|
||||
self.assertTrue(len(devices) > 0)
|
||||
|
||||
for device in devices:
|
||||
dev = self.c.GetDevice(DeviceName=device.DeviceName)
|
||||
with self.assertRaises(NotImplementedError):
|
||||
new = self.c.PutDevice(DeviceName=dev.DeviceName,
|
||||
Device={
|
||||
"DeviceName": dev.DeviceName,
|
||||
"IPsStr": dev.IPsStr,
|
||||
"PrivateKey": dev.PrivateKey,
|
||||
"Type": "client",
|
||||
"PublicKey": dev.PublicKey}
|
||||
)
|
||||
with self.assertRaises(NotImplementedError):
|
||||
new = self.c.PatchDevice(DeviceName=dev.DeviceName,
|
||||
Device={
|
||||
"DeviceName": dev.DeviceName,
|
||||
"IPsStr": dev.IPsStr,
|
||||
"PrivateKey": dev.PrivateKey,
|
||||
"Type": "client",
|
||||
"PublicKey": dev.PublicKey}
|
||||
)
|
||||
break
|
||||
|
||||
def easy_peer(self):
|
||||
data = self.c.PostPeerDeploymentConfig(ProvisioningRequest={"Email": self.user, "Identifier": "debug"})
|
||||
data = data.decode()
|
||||
pubkey = re.search("# -WGP- PublicKey: (?P<pubkey>[^\n]+)\n", data, re.MULTILINE)['pubkey']
|
||||
privkey = re.search("PrivateKey = (?P<key>[^\n]+)\n", data, re.MULTILINE)['key']
|
||||
self.keys = KeyTuple(privkey, pubkey)
|
||||
|
||||
def test_Peers(self):
|
||||
|
||||
privkey, pubkey = generate_wireguard_keys()
|
||||
peer = {"UID": uuid.uuid4().hex,
|
||||
"Identifier": uuid.uuid4().hex,
|
||||
"DeviceName": self.DEVICE,
|
||||
"PublicKey": pubkey,
|
||||
"DeviceType": "client",
|
||||
"IPsStr": str(self.IFADDR),
|
||||
"Email": self.user}
|
||||
|
||||
# keypair is created server side if private key is not submitted
|
||||
with self.assertRaisesRegex(ApiError, "peer not found"):
|
||||
self.c.PostPeer(DeviceName=self.DEVICE, Peer=peer)
|
||||
|
||||
# create
|
||||
peer["PrivateKey"] = privkey
|
||||
p = self.c.PostPeer(DeviceName=self.DEVICE, Peer=peer)
|
||||
self.assertListEqual([p.PrivateKey, p.PublicKey], [privkey, pubkey])
|
||||
|
||||
# lookup created peer
|
||||
for p in self.c.GetPeers(DeviceName=self.DEVICE):
|
||||
if pubkey == p.PublicKey:
|
||||
break
|
||||
else:
|
||||
self.assertTrue(False)
|
||||
|
||||
# get
|
||||
gp = self.c.GetPeer(PublicKey=p.PublicKey)
|
||||
self.assertListEqual([gp.PrivateKey, gp.PublicKey], [p.PrivateKey, p.PublicKey])
|
||||
|
||||
# change?
|
||||
peer['Identifier'] = 'changed'
|
||||
n = self.c.PatchPeer(PublicKey=p.PublicKey, Peer=peer)
|
||||
self.assertListEqual([n.PrivateKey, n.PublicKey], [privkey, pubkey])
|
||||
|
||||
# change ?
|
||||
peer['Identifier'] = 'changedagain'
|
||||
n = self.c.PutPeer(PublicKey=p.PublicKey, Peer=peer)
|
||||
self.assertListEqual([n.PrivateKey, n.PublicKey], [privkey, pubkey])
|
||||
|
||||
# invalid change operations
|
||||
n = peer.copy()
|
||||
n['PrivateKey'], n['PublicKey'] = generate_wireguard_keys()
|
||||
with self.assertRaisesRegex(ApiError, "PublicKey parameter must match the model public key"):
|
||||
self.c.PutPeer(PublicKey=p.PublicKey, Peer=n)
|
||||
|
||||
with self.assertRaisesRegex(ApiError, "PublicKey parameter must match the model public key"):
|
||||
self.c.PatchPeer(PublicKey=p.PublicKey, Peer=n)
|
||||
|
||||
n = self.c.DeletePeer(PublicKey=p.PublicKey)
|
||||
|
||||
def test_Deployment(self):
|
||||
log.setLevel(logging.DEBUG)
|
||||
self._client("general")
|
||||
self.easy_peer()
|
||||
|
||||
self.c.GetPeerDeploymentConfig(PublicKey=self.keys.public)
|
||||
self.c.GetPeerDeploymentInformation(Email=self.user)
|
||||
log.setLevel(logging.INFO)
|
||||
|
||||
def test_User(self):
|
||||
u = self.c.PostUser(User={"Firstname": "Test", "Lastname": "User", "Email": self.randmail})
|
||||
for i in self.c.GetUsers():
|
||||
if i.Email == u.Email:
|
||||
break
|
||||
else:
|
||||
self.assertTrue(False)
|
||||
|
||||
u = self.c.GetUser(Email=u.Email)
|
||||
self.c.PutUser(Email=u.Email, User={"Firstname": "Test", "Lastname": "User", "Email": u.Email})
|
||||
self.c.PatchUser(Email=u.Email, User={"Firstname": "Test", "Lastname": "User", "Email": u.Email})
|
||||
|
||||
# list a deleted user
|
||||
self.c.DeleteUser(Email=u.Email)
|
||||
|
||||
for i in self.c.GetUsers():
|
||||
break
|
||||
|
||||
|
||||
def _clear_peers(self):
|
||||
for p in self.c.GetPeers(DeviceName=self.DEVICE):
|
||||
self.c.DeletePeer(PublicKey=p.PublicKey)
|
||||
|
||||
def _clear_users(self):
|
||||
for p in self.c.GetUsers():
|
||||
if p.Email == self.AUTH['api'][1][0]:
|
||||
continue
|
||||
self.c.DeleteUser(Email=p.Email)
|
||||
|
||||
|
||||
def _createPeer(self):
|
||||
privkey, pubkey = generate_wireguard_keys()
|
||||
peer = {"UID": uuid.uuid4().hex,
|
||||
"Identifier": uuid.uuid4().hex,
|
||||
"DeviceName": self.DEVICE,
|
||||
"PublicKey": pubkey,
|
||||
"PrivateKey": privkey,
|
||||
"DeviceType": "client",
|
||||
# "IPsStr": str(self.ifaddr),
|
||||
"Email": self.user}
|
||||
self.c.PostPeer(DeviceName=self.DEVICE, Peer=peer)
|
||||
return pubkey
|
||||
|
||||
def test_address_exhaustion(self):
|
||||
global log
|
||||
self._clear_peers()
|
||||
self._clear_users()
|
||||
|
||||
self.NETWORK = ipaddress.ip_network("10.0.0.0/29")
|
||||
addr = ipaddress.ip_address(
|
||||
random.randrange(int(self.NETWORK.network_address) + 1, int(self.NETWORK.broadcast_address) - 1))
|
||||
self.__class__.IFADDR = str(ipaddress.ip_interface(f"{addr}/{self.NETWORK.prefixlen}"))
|
||||
|
||||
# reconfigure via web ui - set the ifaddr with less addrs in pool
|
||||
self.finishInstallation()
|
||||
|
||||
keys = set()
|
||||
EADDRESSEXHAUSTED = "failed to get available IP addresses: no more available address from cidr"
|
||||
with self.assertRaisesRegex(ValueError, EADDRESSEXHAUSTED):
|
||||
for i in range(self.NETWORK.num_addresses + 1):
|
||||
keys.add(self._createPeer())
|
||||
|
||||
n = keys.pop()
|
||||
self.c.DeletePeer(PublicKey=n)
|
||||
self._createPeer()
|
||||
|
||||
with self.assertRaisesRegex(ValueError, EADDRESSEXHAUSTED):
|
||||
self._createPeer()
|
||||
|
||||
# expand network
|
||||
self.NETWORK = ipaddress.ip_network("10.0.0.0/28")
|
||||
addr = ipaddress.ip_address(
|
||||
random.randrange(int(self.NETWORK.network_address) + 1, int(self.NETWORK.broadcast_address) - 1))
|
||||
self.__class__.IFADDR = str(ipaddress.ip_interface(f"{addr}/{self.NETWORK.prefixlen}"))
|
||||
self.finishInstallation()
|
||||
self._createPeer()
|
||||
|
Reference in New Issue
Block a user