You've already forked ionscale
mirror of
https://github.com/jsiebens/ionscale.git
synced 2026-04-06 13:02:58 +01:00
Compare commits
73 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ba540cb2c | |||
| 3577b8b46e | |||
| f24f0973fe | |||
| 12cad15a4e | |||
| d5c3c699dd | |||
| b3b21be50d | |||
| 051650ae4e | |||
| 2fc79ee0a1 | |||
| b7b3796ae6 | |||
| b0074152d1 | |||
| 4550bdbf2a | |||
| d32ece6304 | |||
| ef325dd936 | |||
| 9a55d67c7e | |||
| cbbaa31580 | |||
| 35c46eb2ec | |||
| d6a564b7a9 | |||
| 527fb34560 | |||
| 805a516626 | |||
| 0dbc81d50f | |||
| 40cc7b5648 | |||
| b62db084d1 | |||
| df23c178f9 | |||
| 9f7263abd5 | |||
| 660c684a13 | |||
| 790ef5fe1a | |||
| 61d9b40144 | |||
| a8e8d1aa49 | |||
| b2dbe3b9c5 | |||
| 8c6e9e00b9 | |||
| beb856a85d | |||
| 2345f0b1de | |||
| c8b040fcd6 | |||
| 5481d3bf4b | |||
| aac5414a21 | |||
| e74faa2605 | |||
| 9baf2ec6d1 | |||
| c73b7e13e0 | |||
| e41bac5a41 | |||
| 03abebb847 | |||
| 210cc9c8a2 | |||
| 9e38ffc44d | |||
| 06f02c1235 | |||
| 1de736144a | |||
| 2bfe95219d | |||
| e66fa7eabf | |||
| 4e96f2a5c3 | |||
| 43167c1fae | |||
| cf75b9240c | |||
| ab9439ecfe | |||
| 429798574d | |||
| aad7a8b6e8 | |||
| a2d97183d2 | |||
| af3a5f3a25 | |||
| fea6a10640 | |||
| 11af121126 | |||
| dfb91d2419 | |||
| daf577a0ee | |||
| a364188761 | |||
| ea4fe22e35 | |||
| ddc65d2df9 | |||
| c70a4cfe6a | |||
| 5bf919da12 | |||
| 6d4a7b7014 | |||
| bc1f188816 | |||
| 9522e3531e | |||
| 1e3541e7c8 | |||
| c3e1344199 | |||
| 70b9373df3 | |||
| 58de86a978 | |||
| 2e57338b54 | |||
| 7cadcc9085 | |||
| 22cfe60c7d |
@@ -9,18 +9,28 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
buf-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: Set up Buf
|
||||
uses: bufbuild/buf-setup-action@v1
|
||||
- name: Buf Lint
|
||||
uses: bufbuild/buf-lint-action@v1
|
||||
with:
|
||||
input: proto
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.19
|
||||
|
||||
go-version: "1.20"
|
||||
- name: Build
|
||||
run: |
|
||||
go test ./...
|
||||
go test -v -short ./...
|
||||
go build cmd/ionscale/main.go
|
||||
@@ -0,0 +1,23 @@
|
||||
name: docs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['main']
|
||||
paths: ['mkdocs/**']
|
||||
|
||||
permissions:
|
||||
pages: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.x
|
||||
- run: pip install mkdocs-material
|
||||
- run: cd mkdocs && mkdocs gh-deploy --force
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,32 @@
|
||||
name: Integration Tests
|
||||
|
||||
on: workflow_dispatch
|
||||
|
||||
jobs:
|
||||
integration:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
ts_version:
|
||||
- "1.36.0"
|
||||
- "1.34.1"
|
||||
- "1.32.3"
|
||||
- "1.30.2"
|
||||
- "1.28.0"
|
||||
- "1.26.2"
|
||||
- "1.24.2"
|
||||
env:
|
||||
IONSCALE_TESTS_TS_TARGET_VERSION: ${{ matrix.ts_version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: "1.20"
|
||||
- name: Run Integration Tests
|
||||
run: |
|
||||
go test -v ./tests
|
||||
@@ -26,11 +26,11 @@ jobs:
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.19
|
||||
go-version: "1.20"
|
||||
- name: Install cosign
|
||||
uses: sigstore/cosign-installer@v2.5.1
|
||||
uses: sigstore/cosign-installer@v2.8.1
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v2
|
||||
with:
|
||||
|
||||
@@ -29,11 +29,11 @@ jobs:
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.19
|
||||
go-version: "1.20"
|
||||
- name: Install cosign
|
||||
uses: sigstore/cosign-installer@v2.5.1
|
||||
uses: sigstore/cosign-installer@v2.8.1
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v2
|
||||
with:
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM --platform=${BUILDPLATFORM:-linux/amd64} alpine:3.16.2
|
||||
FROM --platform=${BUILDPLATFORM:-linux/amd64} alpine:3.17.2
|
||||
|
||||
COPY ionscale /usr/local/bin/ionscale
|
||||
|
||||
|
||||
@@ -5,4 +5,13 @@ init:
|
||||
go install github.com/bufbuild/connect-go/cmd/protoc-gen-connect-go@latest
|
||||
|
||||
generate:
|
||||
buf generate proto
|
||||
buf generate proto
|
||||
|
||||
format:
|
||||
buf format -w proto
|
||||
|
||||
lint:
|
||||
buf lint proto
|
||||
|
||||
breaking:
|
||||
buf breaking proto --against https://github.com/jsiebens/ionscale.git#subdir=proto
|
||||
|
||||
@@ -1,4 +1,39 @@
|
||||
# ionscale
|
||||
|
||||
> **Note**:
|
||||
> ionscale is currently alpha quality, actively being developed and so subject to changes
|
||||
> ionscale is currently beta quality, actively being developed and so subject to changes
|
||||
|
||||
**What is Tailscale?**
|
||||
|
||||
[Tailscale](https://tailscale.com) is a VPN service that makes the devices and applications you own accessible anywhere in the world, securely and effortlessly.
|
||||
It enables encrypted point-to-point connections using the open source [WireGuard](https://www.wireguard.com/) protocol, which means only devices on your private network can communicate with each other.
|
||||
|
||||
**What is ionscale?**
|
||||
|
||||
While the Tailscale software running on each node is open source, their centralized "coordination server" which act as a shared drop box for public keys is not.
|
||||
|
||||
_ionscale_ aims to implement such lightweight, open source alternative Tailscale control server.
|
||||
|
||||
## Features
|
||||
|
||||
- multi [tailnet](https://tailscale.com/kb/1136/tailnet/) support
|
||||
- multi user support
|
||||
- OIDC integration (not required, although recommended)
|
||||
- [Auth keys](https://tailscale.com/kb/1085/auth-keys/)
|
||||
- [Access control list](https://tailscale.com/kb/1018/acls/)
|
||||
- [DNS](https://tailscale.com/kb/1054/dns/)
|
||||
- nameservers
|
||||
- Split DNS
|
||||
- MagicDNS
|
||||
- [HTTPS Certs](https://tailscale.com/kb/1153/enabling-https/)
|
||||
- [Tailscale SSH](https://tailscale.com/kb/1193/tailscale-ssh/)
|
||||
- [Service collection](https://tailscale.com/kb/1100/services/)
|
||||
- [Taildrop](https://tailscale.com/kb/1106/taildrop/)
|
||||
|
||||
## Documentation
|
||||
|
||||
Some documentation can be found [here](https://jsiebens.github.io/ionscale)
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This is not an official Tailscale or Tailscale Inc. project.
|
||||
@@ -1,60 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"github.com/muesli/coral"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := rootCommand()
|
||||
if err := cmd.Execute(); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func rootCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
Use: "pg-ionscale-events",
|
||||
}
|
||||
|
||||
var url string
|
||||
command.Flags().StringVar(&url, "url", "", "")
|
||||
_ = command.MarkFlagRequired("url")
|
||||
|
||||
command.RunE = func(cmd *coral.Command, args []string) error {
|
||||
_, err := sql.Open("postgres", url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reportProblem := func(ev pq.ListenerEventType, err error) {
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
minReconn := 10 * time.Second
|
||||
maxReconn := time.Minute
|
||||
listener := pq.NewListener(url, minReconn, maxReconn, reportProblem)
|
||||
err = listener.Listen("ionscale_events")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("listening for events ...")
|
||||
fmt.Println("")
|
||||
for {
|
||||
select {
|
||||
case n, _ := <-listener.Notify:
|
||||
fmt.Println(n.Extra)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
@@ -1,111 +1,171 @@
|
||||
module github.com/jsiebens/ionscale
|
||||
|
||||
go 1.19
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/apparentlymart/go-cidr v1.1.0
|
||||
github.com/bufbuild/connect-go v0.4.0
|
||||
github.com/bufbuild/connect-go v1.5.2
|
||||
github.com/caarlos0/env/v6 v6.10.1
|
||||
github.com/caddyserver/certmagic v0.17.1
|
||||
github.com/coreos/go-oidc/v3 v3.3.0
|
||||
github.com/glebarez/sqlite v1.4.6
|
||||
github.com/caddyserver/certmagic v0.17.2
|
||||
github.com/coreos/go-oidc/v3 v3.5.0
|
||||
github.com/glebarez/sqlite v1.7.0
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.0.2
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0
|
||||
github.com/hashicorp/go-bexpr v0.1.11
|
||||
github.com/hashicorp/go-hclog v1.3.0
|
||||
github.com/hashicorp/go-hclog v1.4.0
|
||||
github.com/hashicorp/go-multierror v1.1.1
|
||||
github.com/imdario/mergo v0.3.12
|
||||
github.com/klauspost/compress v1.15.9
|
||||
github.com/labstack/echo-contrib v0.13.0
|
||||
github.com/labstack/echo/v4 v4.9.0
|
||||
github.com/lib/pq v1.10.6
|
||||
github.com/imdario/mergo v0.3.13
|
||||
github.com/jsiebens/go-edit v0.1.0
|
||||
github.com/klauspost/compress v1.16.0
|
||||
github.com/labstack/echo-contrib v0.14.1
|
||||
github.com/labstack/echo/v4 v4.10.2
|
||||
github.com/libdns/azure v0.2.0
|
||||
github.com/libdns/cloudflare v0.1.0
|
||||
github.com/libdns/digitalocean v0.0.0-20220518195853-a541bc8aa80f
|
||||
github.com/libdns/googleclouddns v1.1.0
|
||||
github.com/libdns/libdns v0.2.1
|
||||
github.com/libdns/route53 v1.3.1
|
||||
github.com/mitchellh/go-homedir v1.1.0
|
||||
github.com/mitchellh/pointerstructure v1.2.1
|
||||
github.com/mr-tron/base58 v1.2.0
|
||||
github.com/muesli/coral v1.0.0
|
||||
github.com/nleeper/goment v1.4.4
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/prometheus/client_golang v1.13.0
|
||||
github.com/rodaine/table v1.0.1
|
||||
github.com/ory/dockertest/v3 v3.9.1
|
||||
github.com/prometheus/client_golang v1.14.0
|
||||
github.com/rodaine/table v1.1.0
|
||||
github.com/sony/sonyflake v1.1.0
|
||||
github.com/stretchr/testify v1.8.0
|
||||
github.com/xhit/go-str2duration/v2 v2.0.0
|
||||
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
|
||||
golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b
|
||||
golang.org/x/oauth2 v0.0.0-20220822191816-0ebed06d0094
|
||||
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde
|
||||
google.golang.org/protobuf v1.28.1
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/stretchr/testify v1.8.1
|
||||
github.com/xhit/go-str2duration/v2 v2.1.0
|
||||
golang.org/x/crypto v0.7.0
|
||||
golang.org/x/net v0.8.0
|
||||
golang.org/x/oauth2 v0.6.0
|
||||
golang.org/x/sync v0.1.0
|
||||
google.golang.org/protobuf v1.29.0
|
||||
gopkg.in/square/go-jose.v2 v2.6.0
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/driver/postgres v1.3.9
|
||||
gorm.io/gorm v1.23.8
|
||||
gorm.io/driver/postgres v1.4.8
|
||||
gorm.io/gorm v1.24.6
|
||||
gorm.io/plugin/prometheus v0.0.0-20230109022219-ee24990c7392
|
||||
inet.af/netaddr v0.0.0-20220811202034-502d2d690317
|
||||
tailscale.com v1.30.0
|
||||
tailscale.com v1.36.2
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute v1.18.0 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.2.3 // indirect
|
||||
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible // indirect
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect
|
||||
github.com/Azure/go-autorest v14.2.0+incompatible // indirect
|
||||
github.com/Azure/go-autorest/autorest v0.11.28 // indirect
|
||||
github.com/Azure/go-autorest/autorest/adal v0.9.22 // indirect
|
||||
github.com/Azure/go-autorest/autorest/azure/auth v0.5.12 // indirect
|
||||
github.com/Azure/go-autorest/autorest/azure/cli v0.4.6 // indirect
|
||||
github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect
|
||||
github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect
|
||||
github.com/Azure/go-autorest/logger v0.2.1 // indirect
|
||||
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.0 // indirect
|
||||
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.17.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.18.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.13.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.31 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/route53 v1.27.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.12.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.18.6 // indirect
|
||||
github.com/aws/smithy-go v1.13.5 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.2.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/containerd/continuity v0.3.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/fatih/color v1.13.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.18.1 // indirect
|
||||
github.com/digitalocean/godo v1.98.0 // indirect
|
||||
github.com/dimchansky/utfbom v1.1.1 // indirect
|
||||
github.com/docker/cli v23.0.1+incompatible // indirect
|
||||
github.com/docker/docker v23.0.1+incompatible // indirect
|
||||
github.com/docker/go-connections v0.4.0 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fatih/color v1.14.1 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.0 // indirect
|
||||
github.com/go-jose/go-jose/v3 v3.0.0 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/google/go-cmp v0.5.8 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.7.1 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.13.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.3.1 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.12.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.17.2 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.3.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/josharian/native v1.0.0 // indirect
|
||||
github.com/jsimonetti/rtnetlink v1.2.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.1.1 // indirect
|
||||
github.com/labstack/gommon v0.3.1 // indirect
|
||||
github.com/libdns/libdns v0.2.1 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/josharian/native v1.1.0 // indirect
|
||||
github.com/jsimonetti/rtnetlink v1.3.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/labstack/gommon v0.4.0 // indirect
|
||||
github.com/lib/pq v1.10.6 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/mdlayher/netlink v1.6.0 // indirect
|
||||
github.com/mdlayher/socket v0.2.3 // indirect
|
||||
github.com/mholt/acmez v1.0.4 // indirect
|
||||
github.com/miekg/dns v1.1.50 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/mdlayher/netlink v1.7.1 // indirect
|
||||
github.com/mdlayher/socket v0.4.0 // indirect
|
||||
github.com/mholt/acmez v1.1.0 // indirect
|
||||
github.com/miekg/dns v1.1.51 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.0-rc2 // indirect
|
||||
github.com/opencontainers/runc v1.1.4 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_model v0.2.0 // indirect
|
||||
github.com/prometheus/common v0.37.0 // indirect
|
||||
github.com/prometheus/procfs v0.8.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
|
||||
github.com/prometheus/client_model v0.3.0 // indirect
|
||||
github.com/prometheus/common v0.42.0 // indirect
|
||||
github.com/prometheus/procfs v0.9.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/sirupsen/logrus v1.9.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/tkuchiki/go-timezone v0.2.2 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.1 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
go.uber.org/atomic v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.8.0 // indirect
|
||||
go.uber.org/zap v1.23.0 // indirect
|
||||
go4.org/intern v0.0.0-20220617035311-6925f38cc365 // indirect
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
go.uber.org/zap v1.24.0 // indirect
|
||||
go4.org/intern v0.0.0-20230205224052-192e9f60865c // indirect
|
||||
go4.org/mem v0.0.0-20220726221520-4f986261bf13 // indirect
|
||||
go4.org/unsafe/assume-no-moving-gc v0.0.0-20220617031537-928513b29760 // indirect
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
|
||||
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 // indirect
|
||||
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 // indirect
|
||||
golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect
|
||||
golang.org/x/tools v0.1.12 // indirect
|
||||
golang.zx2c4.com/wireguard/windows v0.4.10 // indirect
|
||||
go4.org/unsafe/assume-no-moving-gc v0.0.0-20230221090011-e4bae7ad2296 // indirect
|
||||
golang.org/x/exp v0.0.0-20230310171629-522b1b587ee0 // indirect
|
||||
golang.org/x/mod v0.9.0 // indirect
|
||||
golang.org/x/sys v0.6.0 // indirect
|
||||
golang.org/x/text v0.8.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
golang.org/x/tools v0.7.0 // indirect
|
||||
golang.zx2c4.com/wireguard/windows v0.5.3 // indirect
|
||||
google.golang.org/api v0.112.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
|
||||
modernc.org/libc v1.18.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 // indirect
|
||||
google.golang.org/grpc v1.53.0 // indirect
|
||||
modernc.org/libc v1.22.3 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.3.0 // indirect
|
||||
modernc.org/sqlite v1.18.1 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/sqlite v1.21.0 // indirect
|
||||
nhooyr.io/websocket v1.8.7 // indirect
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -1,6 +1,6 @@
|
||||
package provider
|
||||
package auth
|
||||
|
||||
type AuthProvider interface {
|
||||
type Provider interface {
|
||||
GetLoginURL(redirectURI, state string) string
|
||||
Exchange(redirectURI, code string) (*User, error)
|
||||
}
|
||||
+22
-12
@@ -8,6 +8,8 @@ import (
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"github.com/labstack/echo/v4"
|
||||
"io/ioutil"
|
||||
"sync"
|
||||
"tailscale.com/smallzstd"
|
||||
"tailscale.com/types/key"
|
||||
)
|
||||
|
||||
@@ -77,12 +79,7 @@ func (d *defaultBinder) Marshal(compress string, v interface{}) ([]byte, error)
|
||||
}
|
||||
|
||||
if compress == "zstd" {
|
||||
encoder, err := zstd.NewWriter(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payload = encoder.EncodeAll(marshalled, nil)
|
||||
payload = zstdEncode(marshalled)
|
||||
} else {
|
||||
payload = marshalled
|
||||
}
|
||||
@@ -140,12 +137,7 @@ func (b *boxBinder) Marshal(compress string, v interface{}) ([]byte, error) {
|
||||
}
|
||||
|
||||
if compress == "zstd" {
|
||||
encoder, err := zstd.NewWriter(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
encoded := encoder.EncodeAll(marshalled, nil)
|
||||
encoded := zstdEncode(marshalled)
|
||||
payload = b.controlKey.SealTo(b.machineKey, encoded)
|
||||
} else {
|
||||
payload = b.controlKey.SealTo(b.machineKey, marshalled)
|
||||
@@ -161,3 +153,21 @@ func (b *boxBinder) Marshal(compress string, v interface{}) ([]byte, error) {
|
||||
func (b *boxBinder) Peer() key.MachinePublic {
|
||||
return b.machineKey
|
||||
}
|
||||
|
||||
func zstdEncode(in []byte) []byte {
|
||||
encoder := zstdEncoderPool.Get().(*zstd.Encoder)
|
||||
out := encoder.EncodeAll(in, nil)
|
||||
encoder.Close()
|
||||
zstdEncoderPool.Put(encoder)
|
||||
return out
|
||||
}
|
||||
|
||||
var zstdEncoderPool = &sync.Pool{
|
||||
New: func() any {
|
||||
encoder, err := smallzstd.NewEncoder(nil, zstd.WithEncoderLevel(zstd.SpeedFastest))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return encoder
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
package broker
|
||||
@@ -1,16 +0,0 @@
|
||||
package broker
|
||||
|
||||
type Signal struct {
|
||||
PeerUpdated *uint64
|
||||
PeersRemoved []uint64
|
||||
ACLUpdated bool
|
||||
DNSUpdated bool
|
||||
}
|
||||
|
||||
type Listener chan *Signal
|
||||
|
||||
type Pubsub interface {
|
||||
Subscribe(tailnet uint64, listener Listener) (cancel func(), err error)
|
||||
Publish(tailnet uint64, message *Signal) error
|
||||
Close() error
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type memoryPubsub struct {
|
||||
mut sync.RWMutex
|
||||
listeners map[uint64]map[uuid.UUID]Listener
|
||||
}
|
||||
|
||||
func (m *memoryPubsub) Subscribe(tailnet uint64, listener Listener) (cancel func(), err error) {
|
||||
m.mut.Lock()
|
||||
defer m.mut.Unlock()
|
||||
|
||||
var listeners map[uuid.UUID]Listener
|
||||
var ok bool
|
||||
if listeners, ok = m.listeners[tailnet]; !ok {
|
||||
listeners = map[uuid.UUID]Listener{}
|
||||
m.listeners[tailnet] = listeners
|
||||
}
|
||||
var id uuid.UUID
|
||||
for {
|
||||
id = uuid.New()
|
||||
if _, ok = listeners[id]; !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
listeners[id] = listener
|
||||
return func() {
|
||||
m.mut.Lock()
|
||||
defer m.mut.Unlock()
|
||||
listeners := m.listeners[tailnet]
|
||||
delete(listeners, id)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *memoryPubsub) Publish(tailnet uint64, message *Signal) error {
|
||||
m.mut.RLock()
|
||||
defer m.mut.RUnlock()
|
||||
listeners, ok := m.listeners[tailnet]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, listener := range listeners {
|
||||
listener <- message
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*memoryPubsub) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewPubsubInMemory() Pubsub {
|
||||
return &memoryPubsub{
|
||||
listeners: make(map[uint64]map[uuid.UUID]Listener),
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/lib/pq"
|
||||
"time"
|
||||
)
|
||||
|
||||
type pgPubsub struct {
|
||||
pgListener *pq.Listener
|
||||
db *sql.DB
|
||||
target Pubsub
|
||||
}
|
||||
|
||||
func NewPubsub(ctx context.Context, database *sql.DB, connectURL string) (Pubsub, error) {
|
||||
errCh := make(chan error)
|
||||
listener := pq.NewListener(connectURL, time.Second, time.Minute, func(event pq.ListenerEventType, err error) {
|
||||
select {
|
||||
case <-errCh:
|
||||
return
|
||||
default:
|
||||
errCh <- err
|
||||
close(errCh)
|
||||
}
|
||||
})
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pq listener: %w", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
if err := listener.Listen("ionscale_events"); err != nil {
|
||||
return nil, fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
|
||||
pubsub := &pgPubsub{
|
||||
db: database,
|
||||
pgListener: listener,
|
||||
target: NewPubsubInMemory(),
|
||||
}
|
||||
go pubsub.listen(ctx)
|
||||
|
||||
return pubsub, nil
|
||||
}
|
||||
|
||||
func (p *pgPubsub) Close() error {
|
||||
return p.pgListener.Close()
|
||||
}
|
||||
|
||||
func (p *pgPubsub) Subscribe(tailnet uint64, listener Listener) (cancel func(), err error) {
|
||||
return p.target.Subscribe(tailnet, listener)
|
||||
}
|
||||
|
||||
func (p *pgPubsub) Publish(tailnet uint64, message *Signal) error {
|
||||
event := &pgEvent{
|
||||
TailnetID: tailnet,
|
||||
Signal: message,
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = p.db.ExecContext(context.Background(), `select pg_notify(`+pq.QuoteLiteral("ionscale_events")+`, $1)`, payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("exec pg_notify: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *pgPubsub) listen(ctx context.Context) {
|
||||
var (
|
||||
notif *pq.Notification
|
||||
ok bool
|
||||
)
|
||||
defer p.pgListener.Close()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case notif, ok = <-p.pgListener.Notify:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
// A nil notification can be dispatched on reconnect.
|
||||
if notif == nil {
|
||||
continue
|
||||
}
|
||||
p.listenReceive(notif)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *pgPubsub) listenReceive(notif *pq.Notification) {
|
||||
extra := []byte(notif.Extra)
|
||||
event := &pgEvent{}
|
||||
|
||||
if err := json.Unmarshal(extra, event); err == nil {
|
||||
p.target.Publish(event.TailnetID, event.Signal)
|
||||
} else {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
type pgEvent struct {
|
||||
TailnetID uint64
|
||||
Signal *Signal
|
||||
}
|
||||
+74
-9
@@ -1,23 +1,25 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/go-edit/editor"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
)
|
||||
|
||||
func getACLConfigCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func getACLConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get-acl-policy",
|
||||
Short: "Get the ACL policy",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var asJson bool
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
@@ -25,10 +27,9 @@ func getACLConfigCommand() *coral.Command {
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
command.Flags().BoolVar(&asJson, "json", false, "When enabled, render output as json otherwise yaml")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(cmd *coral.Command, args []string) error {
|
||||
command.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -57,8 +58,72 @@ func getACLConfigCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func setACLConfigCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func editACLConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "edit-acl-policy",
|
||||
Short: "Edit the ACL policy",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
edit := editor.NewDefaultEditor([]string{"IONSCALE_EDITOR", "EDITOR"})
|
||||
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.GetACLPolicy(context.Background(), connect.NewRequest(&api.GetACLPolicyRequest{TailnetId: tailnet.Id}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
previous, err := json.MarshalIndent(resp.Msg.Policy, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
next, s, err := edit.LaunchTempFile("ionscale", ".json", bytes.NewReader(previous))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer os.Remove(s)
|
||||
|
||||
var policy = &api.ACLPolicy{}
|
||||
if err := json.Unmarshal(next, policy); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.SetACLPolicy(context.Background(), connect.NewRequest(&api.SetACLPolicyRequest{TailnetId: tailnet.Id, Policy: policy}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("ACL policy updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func setACLConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "set-acl-policy",
|
||||
Short: "Set ACL policy",
|
||||
SilenceUsage: true,
|
||||
@@ -75,7 +140,7 @@ func setACLConfigCommand() *coral.Command {
|
||||
command.Flags().StringVar(&file, "file", "", "Path to json file with the acl configuration")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(cmd *coral.Command, args []string) error {
|
||||
command.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
rawJson, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/pkg/client/ionscale"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func authCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func authCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "auth",
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ func authCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func authLoginCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func authLoginCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "login",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
@@ -29,14 +29,14 @@ func authLoginCommand() *coral.Command {
|
||||
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := &api.AuthenticationRequest{}
|
||||
req := &api.AuthenticateRequest{}
|
||||
stream, err := client.Authenticate(context.Background(), connect.NewRequest(req))
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+22
-18
@@ -5,18 +5,19 @@ import (
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/rodaine/table"
|
||||
"github.com/spf13/cobra"
|
||||
str2dur "github.com/xhit/go-str2duration/v2"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func authkeysCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
Use: "auth-keys",
|
||||
Short: "Manage ionscale auth keys",
|
||||
func authkeysCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "auth-keys",
|
||||
Aliases: []string{"auth-key"},
|
||||
Short: "Manage ionscale auth keys",
|
||||
}
|
||||
|
||||
command.AddCommand(createAuthkeysCommand())
|
||||
@@ -26,8 +27,8 @@ func authkeysCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func createAuthkeysCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func createAuthkeysCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "Creates a new auth key in the specified tailnet",
|
||||
SilenceUsage: true,
|
||||
@@ -36,6 +37,7 @@ func createAuthkeysCommand() *coral.Command {
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var ephemeral bool
|
||||
var preAuthorized bool
|
||||
var tags []string
|
||||
var expiry string
|
||||
var target = Target{}
|
||||
@@ -46,9 +48,10 @@ func createAuthkeysCommand() *coral.Command {
|
||||
command.Flags().BoolVar(&ephemeral, "ephemeral", false, "When enabled, machines authenticated by this key will be automatically removed after going offline.")
|
||||
command.Flags().StringSliceVar(&tags, "tag", []string{}, "Machines authenticated by this key will be automatically tagged with these tags")
|
||||
command.Flags().StringVar(&expiry, "expiry", "180d", "Human-readable expiration of the key")
|
||||
command.Flags().BoolVar(&preAuthorized, "pre-authorized", false, "Generate an auth key which is pre-authorized.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -70,10 +73,11 @@ func createAuthkeysCommand() *coral.Command {
|
||||
}
|
||||
|
||||
req := &api.CreateAuthKeyRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
Ephemeral: ephemeral,
|
||||
Tags: tags,
|
||||
Expiry: expiryDur,
|
||||
TailnetId: tailnet.Id,
|
||||
Ephemeral: ephemeral,
|
||||
PreAuthorized: preAuthorized,
|
||||
Tags: tags,
|
||||
Expiry: expiryDur,
|
||||
}
|
||||
resp, err := client.CreateAuthKey(context.Background(), connect.NewRequest(req))
|
||||
|
||||
@@ -94,8 +98,8 @@ func createAuthkeysCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func deleteAuthKeyCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func deleteAuthKeyCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "delete",
|
||||
Short: "Delete a specified auth key",
|
||||
SilenceUsage: true,
|
||||
@@ -106,7 +110,7 @@ func deleteAuthKeyCommand() *coral.Command {
|
||||
target.prepareCommand(command)
|
||||
command.Flags().Uint64Var(&authKeyId, "id", 0, "Auth Key ID")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
grpcClient, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -125,8 +129,8 @@ func deleteAuthKeyCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func listAuthkeysCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func listAuthkeysCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List all auth keys for a given tailnet",
|
||||
SilenceUsage: true,
|
||||
@@ -141,7 +145,7 @@ func listAuthkeysCommand() *coral.Command {
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"fmt"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/key"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
"gopkg.in/yaml.v2"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func configureCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func configureCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "configure",
|
||||
Short: "Generate a simple config file to get started.",
|
||||
SilenceUsage: true,
|
||||
@@ -33,7 +33,7 @@ func configureCommand() *coral.Command {
|
||||
|
||||
command.MarkFlagRequired("domain")
|
||||
|
||||
command.PreRunE = func(cmd *coral.Command, args []string) error {
|
||||
command.PreRunE = func(cmd *cobra.Command, args []string) error {
|
||||
if domain == "" {
|
||||
return errors.New("required flag 'domain' is missing")
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func configureCommand() *coral.Command {
|
||||
return nil
|
||||
}
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
c := &config.Config{}
|
||||
|
||||
c.HttpListenAddr = "0.0.0.0:80"
|
||||
|
||||
+48
-22
@@ -6,27 +6,28 @@ import (
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
"gopkg.in/yaml.v2"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
func derpMapCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
Use: "derp-map",
|
||||
Short: "Manage DERP Map configuration",
|
||||
func systemCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "system",
|
||||
Short: "Manage global system configurations",
|
||||
}
|
||||
|
||||
command.AddCommand(getDERPMap())
|
||||
command.AddCommand(setDERPMap())
|
||||
command.AddCommand(getDefaultDERPMap())
|
||||
command.AddCommand(setDefaultDERPMap())
|
||||
command.AddCommand(resetDefaultDERPMap())
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func getDERPMap() *coral.Command {
|
||||
command := &coral.Command{
|
||||
Use: "get",
|
||||
func getDefaultDERPMap() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get-derp-map",
|
||||
Short: "Get the DERP Map configuration",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
@@ -37,13 +38,13 @@ func getDERPMap() *coral.Command {
|
||||
target.prepareCommand(command)
|
||||
command.Flags().BoolVar(&asJson, "json", false, "When enabled, render output as json otherwise yaml")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.GetDERPMap(context.Background(), connect.NewRequest(&api.GetDERPMapRequest{}))
|
||||
resp, err := client.GetDefaultDERPMap(context.Background(), connect.NewRequest(&api.GetDefaultDERPMapRequest{}))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -63,7 +64,6 @@ func getDERPMap() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println(string(marshal))
|
||||
} else {
|
||||
marshal, err := yaml.Marshal(derpMap)
|
||||
@@ -71,7 +71,6 @@ func getDERPMap() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println(string(marshal))
|
||||
}
|
||||
|
||||
@@ -81,9 +80,9 @@ func getDERPMap() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func setDERPMap() *coral.Command {
|
||||
command := &coral.Command{
|
||||
Use: "set",
|
||||
func setDefaultDERPMap() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "set-derp-map",
|
||||
Short: "Set the DERP Map configuration",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
@@ -93,18 +92,18 @@ func setDERPMap() *coral.Command {
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&file, "file", "", "Path to json file with the DERP Map configuration")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
grpcClient, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rawJson, err := ioutil.ReadFile(file)
|
||||
rawJson, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := grpcClient.SetDERPMap(context.Background(), connect.NewRequest(&api.SetDERPMapRequest{Value: rawJson}))
|
||||
resp, err := grpcClient.SetDefaultDERPMap(context.Background(), connect.NewRequest(&api.SetDefaultDERPMapRequest{Value: rawJson}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -114,7 +113,34 @@ func setDERPMap() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("DERP Map updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func resetDefaultDERPMap() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "reset-derp-map",
|
||||
Short: "Reset the DERP Map to the default configuration",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
grpcClient, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := grpcClient.ResetDefaultDERPMap(context.Background(), connect.NewRequest(&api.ResetDefaultDERPMapRequest{})); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("DERP Map updated successfully")
|
||||
|
||||
return nil
|
||||
|
||||
+11
-16
@@ -5,14 +5,14 @@ import (
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
)
|
||||
|
||||
func getDNSConfigCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func getDNSConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get-dns",
|
||||
Short: "Get DNS configuration",
|
||||
SilenceUsage: true,
|
||||
@@ -27,7 +27,7 @@ func getDNSConfigCommand() *coral.Command {
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -46,18 +46,12 @@ func getDNSConfigCommand() *coral.Command {
|
||||
}
|
||||
config := resp.Msg.Config
|
||||
|
||||
var allNameservers = config.Nameservers
|
||||
|
||||
for i, j := range config.Routes {
|
||||
for _, n := range j.Routes {
|
||||
allNameservers = append(allNameservers, fmt.Sprintf("%s:%s", i, n))
|
||||
}
|
||||
}
|
||||
|
||||
w := new(tabwriter.Writer)
|
||||
w.Init(os.Stdout, 8, 8, 0, '\t', 0)
|
||||
w.Init(os.Stdout, 8, 8, 1, '\t', 0)
|
||||
defer w.Flush()
|
||||
|
||||
fmt.Fprintf(w, "%s\t\t%v\n", "MagicDNS", config.MagicDns)
|
||||
fmt.Fprintf(w, "%s\t\t%v\n", "HTTPS Certs", config.HttpsCerts)
|
||||
fmt.Fprintf(w, "%s\t\t%v\n", "Override Local DNS", config.OverrideLocalDns)
|
||||
|
||||
if config.MagicDns {
|
||||
@@ -88,8 +82,8 @@ func getDNSConfigCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func setDNSConfigCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func setDNSConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "set-dns",
|
||||
Short: "Set DNS config",
|
||||
SilenceUsage: true,
|
||||
@@ -107,10 +101,11 @@ func setDNSConfigCommand() *coral.Command {
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
command.Flags().StringSliceVarP(&nameservers, "nameserver", "", []string{}, "Machines on your network will use these nameservers to resolve DNS queries.")
|
||||
command.Flags().BoolVarP(&magicDNS, "magic-dns", "", false, "Enable MagicDNS for the specified Tailnet")
|
||||
command.Flags().BoolVarP(&magicDNS, "https-certs", "", false, "Enable HTTPS Certificates for the specified Tailnet")
|
||||
command.Flags().BoolVarP(&overrideLocalDNS, "override-local-dns", "", false, "When enabled, connected clients ignore local DNS settings and always use the nameservers specified for this Tailnet")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -7,10 +7,10 @@ import (
|
||||
"github.com/jsiebens/ionscale/pkg/client/ionscale"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
apiconnect "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1/ionscalev1connect"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func checkRequiredTailnetAndTailnetIdFlags(cmd *coral.Command, args []string) error {
|
||||
func checkRequiredTailnetAndTailnetIdFlags(cmd *cobra.Command, args []string) error {
|
||||
savedTailnetID, err := ionscale.TailnetFromFile()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -37,7 +37,7 @@ func findTailnet(client apiconnect.IonscaleServiceClient, tailnet string, tailne
|
||||
return nil, fmt.Errorf("requested tailnet not found or you are not authorized for this tailnet")
|
||||
}
|
||||
|
||||
tailnets, err := client.ListTailnets(context.Background(), connect.NewRequest(&api.ListTailnetRequest{}))
|
||||
tailnets, err := client.ListTailnets(context.Background(), connect.NewRequest(&api.ListTailnetsRequest{}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+74
-7
@@ -1,17 +1,20 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/go-edit/editor"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
)
|
||||
|
||||
func getIAMPolicyCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func getIAMPolicyCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get-iam-policy",
|
||||
Short: "Get the IAM policy",
|
||||
SilenceUsage: true,
|
||||
@@ -26,7 +29,7 @@ func getIAMPolicyCommand() *coral.Command {
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(cmd *coral.Command, args []string) error {
|
||||
command.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -55,8 +58,72 @@ func getIAMPolicyCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func setIAMPolicyCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func editIAMPolicyCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "edit-iam-policy",
|
||||
Short: "Edit the IAM policy",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
edit := editor.NewDefaultEditor([]string{"IONSCALE_EDITOR", "EDITOR"})
|
||||
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.GetIAMPolicy(context.Background(), connect.NewRequest(&api.GetIAMPolicyRequest{TailnetId: tailnet.Id}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
previous, err := json.MarshalIndent(resp.Msg.Policy, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
next, s, err := edit.LaunchTempFile("ionscale", ".json", bytes.NewReader(previous))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer os.Remove(s)
|
||||
|
||||
var policy = &api.IAMPolicy{}
|
||||
if err := json.Unmarshal(next, policy); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.SetIAMPolicy(context.Background(), connect.NewRequest(&api.SetIAMPolicyRequest{TailnetId: tailnet.Id, Policy: policy}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("IAM policy updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func setIAMPolicyCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "set-iam-policy",
|
||||
Short: "Set IAM policy",
|
||||
SilenceUsage: true,
|
||||
@@ -73,7 +140,7 @@ func setIAMPolicyCommand() *coral.Command {
|
||||
command.Flags().StringVar(&file, "file", "", "Path to json file with the acl configuration")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(cmd *coral.Command, args []string) error {
|
||||
command.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
rawJson, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+4
-4
@@ -3,11 +3,11 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/jsiebens/ionscale/internal/key"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func keyCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func keyCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "genkey",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
@@ -16,7 +16,7 @@ func keyCommand() *coral.Command {
|
||||
|
||||
command.Flags().BoolVarP(&disableNewLine, "no-newline", "n", false, "do not output a trailing newline")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
serverKey := key.NewServerKey()
|
||||
if disableNewLine {
|
||||
fmt.Print(serverKey.String())
|
||||
|
||||
+83
-44
@@ -5,18 +5,19 @@ import (
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/nleeper/goment"
|
||||
"github.com/rodaine/table"
|
||||
"github.com/spf13/cobra"
|
||||
"inet.af/netaddr"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
)
|
||||
|
||||
func machineCommands() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func machineCommands() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "machines",
|
||||
Aliases: []string{"machine"},
|
||||
Short: "Manage ionscale machines",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
@@ -32,12 +33,13 @@ func machineCommands() *coral.Command {
|
||||
command.AddCommand(enableExitNodeCommand())
|
||||
command.AddCommand(disableExitNodeCommand())
|
||||
command.AddCommand(disableMachineKeyExpiryCommand())
|
||||
command.AddCommand(authorizeMachineCommand())
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func getMachineCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func getMachineCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get",
|
||||
Short: "Retrieve detailed information for a machine",
|
||||
SilenceUsage: true,
|
||||
@@ -50,7 +52,7 @@ func getMachineCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -94,6 +96,10 @@ func getMachineCommand() *coral.Command {
|
||||
fmt.Fprintf(w, "%s\t%s\n", "Tailscale IPv4", m.Ipv4)
|
||||
fmt.Fprintf(w, "%s\t%s\n", "Tailscale IPv6", m.Ipv6)
|
||||
fmt.Fprintf(w, "%s\t%s\n", "Last seen", lastSeen)
|
||||
fmt.Fprintf(w, "%s\t%v\n", "Ephemeral", m.Ephemeral)
|
||||
if !m.Authorized {
|
||||
fmt.Fprintf(w, "%s\t%v\n", "Authorized", m.Authorized)
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\n", "Key expiry", expiresAt)
|
||||
|
||||
for i, t := range m.Tags {
|
||||
@@ -144,8 +150,8 @@ func getMachineCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func deleteMachineCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func deleteMachineCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "delete",
|
||||
Short: "Deletes a machine",
|
||||
SilenceUsage: true,
|
||||
@@ -158,7 +164,7 @@ func deleteMachineCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -177,8 +183,8 @@ func deleteMachineCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func expireMachineCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func expireMachineCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "expire",
|
||||
Short: "Expires a machine",
|
||||
SilenceUsage: true,
|
||||
@@ -191,7 +197,7 @@ func expireMachineCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -210,8 +216,41 @@ func expireMachineCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func listMachinesCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func authorizeMachineCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "authorize",
|
||||
Short: "Authorizes a machine",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var machineID uint64
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
command.Flags().Uint64Var(&machineID, "machine-id", 0, "Machine ID.")
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.AuthorizeMachineRequest{MachineId: machineID}
|
||||
if _, err := client.AuthorizeMachine(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Machine authorized.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func listMachinesCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List machines",
|
||||
SilenceUsage: true,
|
||||
@@ -226,7 +265,7 @@ func listMachinesCommand() *coral.Command {
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -244,7 +283,7 @@ func listMachinesCommand() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
tbl := table.New("ID", "TAILNET", "NAME", "IPv4", "IPv6", "EPHEMERAL", "LAST_SEEN", "TAGS")
|
||||
tbl := table.New("ID", "TAILNET", "NAME", "IPv4", "IPv6", "AUTHORIZED", "EPHEMERAL", "LAST_SEEN", "TAGS")
|
||||
for _, m := range resp.Msg.Machines {
|
||||
var lastSeen = "N/A"
|
||||
if m.Connected {
|
||||
@@ -255,7 +294,7 @@ func listMachinesCommand() *coral.Command {
|
||||
lastSeen = mom.FromNow()
|
||||
}
|
||||
}
|
||||
tbl.AddRow(m.Id, m.Tailnet.Name, m.Name, m.Ipv4, m.Ipv6, m.Ephemeral, lastSeen, strings.Join(m.Tags, ","))
|
||||
tbl.AddRow(m.Id, m.Tailnet.Name, m.Name, m.Ipv4, m.Ipv6, m.Authorized, m.Ephemeral, lastSeen, strings.Join(m.Tags, ","))
|
||||
}
|
||||
tbl.Print()
|
||||
|
||||
@@ -265,8 +304,8 @@ func listMachinesCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func getMachineRoutesCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func getMachineRoutesCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get-routes",
|
||||
Short: "Show routes advertised and enabled by a given machine",
|
||||
SilenceUsage: true,
|
||||
@@ -279,7 +318,7 @@ func getMachineRoutesCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
grpcClient, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -291,7 +330,7 @@ func getMachineRoutesCommand() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
printMachinesRoutesResponse(resp.Msg)
|
||||
printMachinesRoutesResponse(resp.Msg.Routes)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -299,8 +338,8 @@ func getMachineRoutesCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func enableMachineRoutesCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func enableMachineRoutesCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-routes",
|
||||
Short: "Enable routes for a given machine",
|
||||
SilenceUsage: true,
|
||||
@@ -317,7 +356,7 @@ func enableMachineRoutesCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -335,7 +374,7 @@ func enableMachineRoutesCommand() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
printMachinesRoutesResponse(resp.Msg)
|
||||
printMachinesRoutesResponse(resp.Msg.Routes)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -343,8 +382,8 @@ func enableMachineRoutesCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func disableMachineRoutesCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func disableMachineRoutesCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-routes",
|
||||
Short: "Disable routes for a given machine",
|
||||
SilenceUsage: true,
|
||||
@@ -359,7 +398,7 @@ func disableMachineRoutesCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -377,7 +416,7 @@ func disableMachineRoutesCommand() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
printMachinesRoutesResponse(resp.Msg)
|
||||
printMachinesRoutesResponse(resp.Msg.Routes)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -385,8 +424,8 @@ func disableMachineRoutesCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func enableExitNodeCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func enableExitNodeCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-exit-node",
|
||||
Short: "Enable given machine as an exit node",
|
||||
SilenceUsage: true,
|
||||
@@ -399,7 +438,7 @@ func enableExitNodeCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -411,7 +450,7 @@ func enableExitNodeCommand() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
printMachinesRoutesResponse(resp.Msg)
|
||||
printMachinesRoutesResponse(resp.Msg.Routes)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -419,8 +458,8 @@ func enableExitNodeCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func disableExitNodeCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func disableExitNodeCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-exit-node",
|
||||
Short: "Disable given machine as an exit node",
|
||||
SilenceUsage: true,
|
||||
@@ -433,7 +472,7 @@ func disableExitNodeCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -445,7 +484,7 @@ func disableExitNodeCommand() *coral.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
printMachinesRoutesResponse(resp.Msg)
|
||||
printMachinesRoutesResponse(resp.Msg.Routes)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -453,8 +492,8 @@ func disableExitNodeCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func enableMachineKeyExpiryCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func enableMachineKeyExpiryCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-key-expiry",
|
||||
Short: "Enable machine key expiry",
|
||||
SilenceUsage: true,
|
||||
@@ -463,8 +502,8 @@ func enableMachineKeyExpiryCommand() *coral.Command {
|
||||
return configureSetMachineKeyExpiryCommand(command, false)
|
||||
}
|
||||
|
||||
func disableMachineKeyExpiryCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func disableMachineKeyExpiryCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-key-expiry",
|
||||
Short: "Disable machine key expiry",
|
||||
SilenceUsage: true,
|
||||
@@ -473,7 +512,7 @@ func disableMachineKeyExpiryCommand() *coral.Command {
|
||||
return configureSetMachineKeyExpiryCommand(command, true)
|
||||
}
|
||||
|
||||
func configureSetMachineKeyExpiryCommand(command *coral.Command, v bool) *coral.Command {
|
||||
func configureSetMachineKeyExpiryCommand(command *cobra.Command, v bool) *cobra.Command {
|
||||
var machineID uint64
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
@@ -481,7 +520,7 @@ func configureSetMachineKeyExpiryCommand(command *coral.Command, v bool) *coral.
|
||||
|
||||
_ = command.MarkFlagRequired("machine-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -499,7 +538,7 @@ func configureSetMachineKeyExpiryCommand(command *coral.Command, v bool) *coral.
|
||||
return command
|
||||
}
|
||||
|
||||
func printMachinesRoutesResponse(msg *api.GetMachineRoutesResponse) {
|
||||
func printMachinesRoutesResponse(msg *api.MachineRoutes) {
|
||||
w := new(tabwriter.Writer)
|
||||
w.Init(os.Stdout, 8, 8, 0, '\t', 0)
|
||||
defer w.Flush()
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func Command() *coral.Command {
|
||||
func Command() *cobra.Command {
|
||||
rootCmd := rootCommand()
|
||||
rootCmd.AddCommand(configureCommand())
|
||||
rootCmd.AddCommand(keyCommand())
|
||||
rootCmd.AddCommand(authCommand())
|
||||
rootCmd.AddCommand(derpMapCommand())
|
||||
rootCmd.AddCommand(serverCommand())
|
||||
rootCmd.AddCommand(versionCommand())
|
||||
rootCmd.AddCommand(tailnetCommand())
|
||||
rootCmd.AddCommand(authkeysCommand())
|
||||
rootCmd.AddCommand(machineCommands())
|
||||
rootCmd.AddCommand(userCommands())
|
||||
rootCmd.AddCommand(systemCommand())
|
||||
|
||||
return rootCmd
|
||||
}
|
||||
@@ -24,8 +24,8 @@ func Execute() error {
|
||||
return Command().Execute()
|
||||
}
|
||||
|
||||
func rootCommand() *coral.Command {
|
||||
return &coral.Command{
|
||||
func rootCommand() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "ionscale",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ package cmd
|
||||
import (
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/server"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func serverCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func serverCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "server",
|
||||
Short: "Start an ionscale server",
|
||||
SilenceUsage: true,
|
||||
@@ -17,7 +17,7 @@ func serverCommand() *coral.Command {
|
||||
|
||||
command.Flags().StringVarP(&configFile, "config", "c", "", "Path to the configuration file.")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
|
||||
c, err := config.LoadConfig(configFile)
|
||||
if err != nil {
|
||||
|
||||
+533
-30
@@ -2,19 +2,25 @@ package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
idomain "github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/pkg/defaults"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/rodaine/table"
|
||||
"github.com/spf13/cobra"
|
||||
"gopkg.in/yaml.v3"
|
||||
"os"
|
||||
"strings"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
func tailnetCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
Use: "tailnets",
|
||||
Short: "Manage ionscale tailnets",
|
||||
func tailnetCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "tailnets",
|
||||
Aliases: []string{"tailnet"},
|
||||
Short: "Manage ionscale tailnets",
|
||||
}
|
||||
|
||||
command.AddCommand(listTailnetsCommand())
|
||||
@@ -24,14 +30,27 @@ func tailnetCommand() *coral.Command {
|
||||
command.AddCommand(setDNSConfigCommand())
|
||||
command.AddCommand(getACLConfigCommand())
|
||||
command.AddCommand(setACLConfigCommand())
|
||||
command.AddCommand(editACLConfigCommand())
|
||||
command.AddCommand(getIAMPolicyCommand())
|
||||
command.AddCommand(setIAMPolicyCommand())
|
||||
command.AddCommand(editIAMPolicyCommand())
|
||||
command.AddCommand(enableServiceCollectionCommand())
|
||||
command.AddCommand(disableServiceCollectionCommand())
|
||||
command.AddCommand(enableFileSharingCommand())
|
||||
command.AddCommand(disableFileSharingCommand())
|
||||
command.AddCommand(enableSSHCommand())
|
||||
command.AddCommand(disableSSHCommand())
|
||||
command.AddCommand(enableMachineAuthorizationCommand())
|
||||
command.AddCommand(disableMachineAuthorizationCommand())
|
||||
command.AddCommand(getDERPMap())
|
||||
command.AddCommand(setDERPMap())
|
||||
command.AddCommand(resetDERPMap())
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func listTailnetsCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func listTailnetsCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List available Tailnets",
|
||||
SilenceUsage: true,
|
||||
@@ -40,14 +59,14 @@ func listTailnetsCommand() *coral.Command {
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.ListTailnets(context.Background(), connect.NewRequest(&api.ListTailnetRequest{}))
|
||||
resp, err := client.ListTailnets(context.Background(), connect.NewRequest(&api.ListTailnetsRequest{}))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -65,8 +84,8 @@ func listTailnetsCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func createTailnetsCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func createTailnetsCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "Create a new Tailnet",
|
||||
SilenceUsage: true,
|
||||
@@ -82,9 +101,9 @@ func createTailnetsCommand() *coral.Command {
|
||||
command.Flags().StringVar(&domain, "domain", "", "")
|
||||
command.Flags().StringVar(&email, "email", "", "")
|
||||
|
||||
command.PreRunE = func(cmd *coral.Command, args []string) error {
|
||||
if name == "" && email == "" && domain == "" {
|
||||
return fmt.Errorf("at least flag --name, --email or --domain is required")
|
||||
command.PreRunE = func(cmd *cobra.Command, args []string) error {
|
||||
if name == "" {
|
||||
return fmt.Errorf("flag --name is required")
|
||||
}
|
||||
if domain != "" && email != "" {
|
||||
return fmt.Errorf("flags --email and --domain are mutually exclusive")
|
||||
@@ -92,23 +111,22 @@ func createTailnetsCommand() *coral.Command {
|
||||
return nil
|
||||
}
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
|
||||
var tailnetName = ""
|
||||
var iamPolicy = api.IAMPolicy{}
|
||||
dnsConfig := defaults.DefaultDNSConfig()
|
||||
aclPolicy := defaults.DefaultACLPolicy()
|
||||
iamPolicy := &api.IAMPolicy{}
|
||||
|
||||
if len(domain) != 0 {
|
||||
domainToLower := strings.ToLower(domain)
|
||||
tailnetName = domainToLower
|
||||
iamPolicy = api.IAMPolicy{
|
||||
iamPolicy = &api.IAMPolicy{
|
||||
Filters: []string{fmt.Sprintf("domain == %s", domainToLower)},
|
||||
}
|
||||
}
|
||||
|
||||
if len(email) != 0 {
|
||||
emailToLower := strings.ToLower(email)
|
||||
tailnetName = emailToLower
|
||||
iamPolicy = api.IAMPolicy{
|
||||
iamPolicy = &api.IAMPolicy{
|
||||
Emails: []string{emailToLower},
|
||||
Roles: map[string]string{
|
||||
emailToLower: string(idomain.UserRoleAdmin),
|
||||
@@ -116,18 +134,16 @@ func createTailnetsCommand() *coral.Command {
|
||||
}
|
||||
}
|
||||
|
||||
if len(name) != 0 {
|
||||
tailnetName = name
|
||||
}
|
||||
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.CreateTailnet(context.Background(), connect.NewRequest(&api.CreateTailnetRequest{
|
||||
Name: tailnetName,
|
||||
IamPolicy: &iamPolicy,
|
||||
Name: name,
|
||||
IamPolicy: iamPolicy,
|
||||
AclPolicy: aclPolicy,
|
||||
DnsConfig: dnsConfig,
|
||||
}))
|
||||
|
||||
if err != nil {
|
||||
@@ -144,8 +160,8 @@ func createTailnetsCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func deleteTailnetCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func deleteTailnetCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "delete",
|
||||
Short: "Delete a tailnet",
|
||||
SilenceUsage: true,
|
||||
@@ -162,7 +178,7 @@ func deleteTailnetCommand() *coral.Command {
|
||||
command.Flags().BoolVar(&force, "force", false, "When enabled, force delete the specified Tailnet even when machines are still available.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
@@ -187,3 +203,490 @@ func deleteTailnetCommand() *coral.Command {
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func getDERPMap() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "get-derp-map",
|
||||
Short: "Get the DERP Map configuration",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var asJson bool
|
||||
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
command.Flags().BoolVar(&asJson, "json", false, "When enabled, render output as json otherwise yaml")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.GetDERPMap(context.Background(), connect.NewRequest(&api.GetDERPMapRequest{TailnetId: tailnet.Id}))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var derpMap struct {
|
||||
Regions map[int]*tailcfg.DERPRegion
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(resp.Msg.Value, &derpMap); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if asJson {
|
||||
marshal, err := json.MarshalIndent(derpMap, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println(string(marshal))
|
||||
} else {
|
||||
marshal, err := yaml.Marshal(derpMap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println(string(marshal))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func setDERPMap() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "set-derp-map",
|
||||
Short: "Set the DERP Map configuration",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var file string
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
command.Flags().StringVar(&file, "file", "", "Path to json file with the DERP Map configuration")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rawJson, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.SetDERPMap(context.Background(), connect.NewRequest(&api.SetDERPMapRequest{TailnetId: tailnet.Id, Value: rawJson}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var derpMap tailcfg.DERPMap
|
||||
if err := json.Unmarshal(resp.Msg.Value, &derpMap); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("DERP Map updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func resetDERPMap() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "reset-derp-map",
|
||||
Short: "Reset the DERP Map to the default configuration",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := client.ResetDERPMap(context.Background(), connect.NewRequest(&api.ResetDERPMapRequest{TailnetId: tailnet.Id})); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("DERP Map updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func enableFileSharingCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-file-sharing",
|
||||
Aliases: []string{"enable-taildrop"},
|
||||
Short: "Enable Taildrop, the file sharing feature",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.EnableFileSharingRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.EnableFileSharing(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func disableFileSharingCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-file-sharing",
|
||||
Aliases: []string{"disable-taildrop"},
|
||||
Short: "Disable Taildrop, the file sharing feature",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.DisableFileSharingRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.DisableFileSharing(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func enableServiceCollectionCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-service-collection",
|
||||
Short: "Enable monitoring live services running on your network’s machines.",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.EnableServiceCollectionRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.EnableServiceCollection(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func disableServiceCollectionCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-service-collection",
|
||||
Short: "Disable monitoring live services running on your network’s machines.",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.DisableServiceCollectionRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.DisableServiceCollection(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func enableSSHCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-ssh",
|
||||
Short: "Enable ssh access using tailnet and ACLs.",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.EnableSSHRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.EnableSSH(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func disableSSHCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-ssh",
|
||||
Short: "Disable ssh access using tailnet and ACLs.",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.DisableSSHRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.DisableSSH(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func enableMachineAuthorizationCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "enable-machine-authorization",
|
||||
Short: "Enable machine authorization.",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.EnableMachineAuthorizationRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.EnableMachineAuthorization(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func disableMachineAuthorizationCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "disable-machine-authorization",
|
||||
Short: "Disable machine authorization.",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
var tailnetID uint64
|
||||
var tailnetName string
|
||||
var target = Target{}
|
||||
|
||||
target.prepareCommand(command)
|
||||
command.Flags().StringVar(&tailnetName, "tailnet", "", "Tailnet name. Mutually exclusive with --tailnet-id.")
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnet, err := findTailnet(client, tailnetName, tailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := api.DisableMachineAuthorizationRequest{
|
||||
TailnetId: tailnet.Id,
|
||||
}
|
||||
|
||||
if _, err := client.DisableMachineAuthorization(context.Background(), connect.NewRequest(&req)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/pkg/client/ionscale"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1/ionscalev1connect"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,7 +19,7 @@ type Target struct {
|
||||
systemAdminKey string
|
||||
}
|
||||
|
||||
func (t *Target) prepareCommand(cmd *coral.Command) {
|
||||
func (t *Target) prepareCommand(cmd *cobra.Command) {
|
||||
cmd.Flags().StringVar(&t.addr, "addr", "", "Addr of the ionscale server, as a complete URL")
|
||||
cmd.Flags().BoolVar(&t.insecureSkipVerify, "tls-skip-verify", false, "Disable verification of TLS certificates")
|
||||
cmd.Flags().StringVar(&t.systemAdminKey, "system-admin-key", "", "If specified, the given value will be used as the key to generate a Bearer token for the call. This can also be specified via the IONSCALE_ADMIN_KEY environment variable.")
|
||||
|
||||
+10
-9
@@ -5,13 +5,14 @@ import (
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/rodaine/table"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func userCommands() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func userCommands() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "users",
|
||||
Aliases: []string{"user"},
|
||||
Short: "Manage ionscale users",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
@@ -22,8 +23,8 @@ func userCommands() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func listUsersCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func listUsersCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List users",
|
||||
SilenceUsage: true,
|
||||
@@ -38,7 +39,7 @@ func listUsersCommand() *coral.Command {
|
||||
command.Flags().Uint64Var(&tailnetID, "tailnet-id", 0, "Tailnet ID. Mutually exclusive with --tailnet.")
|
||||
|
||||
command.PreRunE = checkRequiredTailnetAndTailnetIdFlags
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -68,8 +69,8 @@ func listUsersCommand() *coral.Command {
|
||||
return command
|
||||
}
|
||||
|
||||
func deleteUserCommand() *coral.Command {
|
||||
command := &coral.Command{
|
||||
func deleteUserCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "delete",
|
||||
Short: "Deletes a user",
|
||||
SilenceUsage: true,
|
||||
@@ -82,7 +83,7 @@ func deleteUserCommand() *coral.Command {
|
||||
|
||||
_ = command.MarkFlagRequired("user-id")
|
||||
|
||||
command.RunE = func(command *coral.Command, args []string) error {
|
||||
command.RunE = func(command *cobra.Command, args []string) error {
|
||||
client, err := target.createGRPCClient()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/version"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"github.com/muesli/coral"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func versionCommand() *coral.Command {
|
||||
var command = &coral.Command{
|
||||
func versionCommand() *cobra.Command {
|
||||
var command = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Display version information",
|
||||
SilenceUsage: true,
|
||||
@@ -19,7 +19,7 @@ func versionCommand() *coral.Command {
|
||||
var target = Target{}
|
||||
target.prepareCommand(command)
|
||||
|
||||
command.Run = func(cmd *coral.Command, args []string) {
|
||||
command.Run = func(cmd *cobra.Command, args []string) {
|
||||
clientVersion, clientRevision := version.GetReleaseInfo()
|
||||
fmt.Printf(`
|
||||
Client:
|
||||
|
||||
+66
-26
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"github.com/caarlos0/env/v6"
|
||||
"github.com/caddyserver/certmagic"
|
||||
@@ -23,8 +24,9 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
keepAliveInterval = defaultKeepAliveInterval
|
||||
magicDNSSuffix = defaultMagicDNSSuffix
|
||||
keepAliveInterval = defaultKeepAliveInterval
|
||||
magicDNSSuffix = defaultMagicDNSSuffix
|
||||
dnsProviderConfigured = false
|
||||
)
|
||||
|
||||
func KeepAliveInterval() time.Duration {
|
||||
@@ -35,6 +37,10 @@ func MagicDNSSuffix() string {
|
||||
return magicDNSSuffix
|
||||
}
|
||||
|
||||
func DNSProviderConfigured() bool {
|
||||
return dnsProviderConfigured
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (*Config, error) {
|
||||
cfg := defaultConfig()
|
||||
|
||||
@@ -59,6 +65,19 @@ func LoadConfig(path string) (*Config, error) {
|
||||
}
|
||||
}
|
||||
|
||||
envCfgB64 := os.Getenv("IONSCALE_CONFIG_BASE64")
|
||||
if len(envCfgB64) != 0 {
|
||||
b, err := base64.StdEncoding.DecodeString(envCfgB64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// merge env configuration on top of the default/file configuration
|
||||
if err := yaml.Unmarshal(b, cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
envCfg := &Config{}
|
||||
if err := env.Parse(envCfg, env.Options{Prefix: "IONSCALE_"}); err != nil {
|
||||
return nil, err
|
||||
@@ -72,6 +91,10 @@ func LoadConfig(path string) (*Config, error) {
|
||||
keepAliveInterval = cfg.PollNet.KeepAliveInterval
|
||||
magicDNSSuffix = cfg.DNS.MagicDNSSuffix
|
||||
|
||||
if cfg.DNS.Provider.Zone != "" {
|
||||
dnsProviderConfigured = true
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -82,8 +105,10 @@ func defaultConfig() *Config {
|
||||
MetricsListenAddr: ":9091",
|
||||
ServerUrl: "https://localhost:8843",
|
||||
Database: Database{
|
||||
Type: "sqlite",
|
||||
Url: "./ionscale.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)",
|
||||
Type: "sqlite",
|
||||
Url: "./ionscale.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)",
|
||||
MaxOpenConns: 0,
|
||||
MaxIdleConns: 2,
|
||||
},
|
||||
Tls: Tls{
|
||||
Disable: false,
|
||||
@@ -111,17 +136,17 @@ type ServerKeys struct {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
HttpListenAddr string `yaml:"http_listen_addr,omitempty" env:"HTTP_LISTEN_ADDR"`
|
||||
HttpsListenAddr string `yaml:"https_listen_addr,omitempty" env:"HTTPS_LISTEN_ADDR"`
|
||||
MetricsListenAddr string `yaml:"metrics_listen_addr,omitempty" env:"METRICS_LISTEN_ADDR"`
|
||||
ServerUrl string `yaml:"server_url,omitempty" env:"SERVER_URL"`
|
||||
Tls Tls `yaml:"tls,omitempty" envPrefix:"TLS_"`
|
||||
PollNet PollNet `yaml:"poll_net,omitempty" envPrefix:"POLL_NET_"`
|
||||
Keys Keys `yaml:"keys,omitempty" envPrefix:"KEYS_"`
|
||||
Database Database `yaml:"database,omitempty" envPrefix:"DB_"`
|
||||
AuthProvider AuthProvider `yaml:"auth_provider,omitempty"`
|
||||
DNS DNS `yaml:"dns,omitempty"`
|
||||
Logging Logging `yaml:"logging,omitempty" envPrefix:"LOGGING_"`
|
||||
HttpListenAddr string `yaml:"http_listen_addr,omitempty" env:"HTTP_LISTEN_ADDR"`
|
||||
HttpsListenAddr string `yaml:"https_listen_addr,omitempty" env:"HTTPS_LISTEN_ADDR"`
|
||||
MetricsListenAddr string `yaml:"metrics_listen_addr,omitempty" env:"METRICS_LISTEN_ADDR"`
|
||||
ServerUrl string `yaml:"server_url,omitempty" env:"SERVER_URL"`
|
||||
Tls Tls `yaml:"tls,omitempty" envPrefix:"TLS_"`
|
||||
PollNet PollNet `yaml:"poll_net,omitempty" envPrefix:"POLL_NET_"`
|
||||
Keys Keys `yaml:"keys,omitempty" envPrefix:"KEYS_"`
|
||||
Database Database `yaml:"database,omitempty" envPrefix:"DB_"`
|
||||
Auth Auth `yaml:"auth,omitempty" envPrefix:"AUTH_"`
|
||||
DNS DNS `yaml:"dns,omitempty"`
|
||||
Logging Logging `yaml:"logging,omitempty" envPrefix:"LOGGING_"`
|
||||
}
|
||||
|
||||
type Tls struct {
|
||||
@@ -146,8 +171,12 @@ type Logging struct {
|
||||
}
|
||||
|
||||
type Database struct {
|
||||
Type string `yaml:"type,omitempty" env:"TYPE"`
|
||||
Url string `yaml:"url,omitempty" env:"URL"`
|
||||
Type string `yaml:"type,omitempty" env:"TYPE"`
|
||||
Url string `yaml:"url,omitempty" env:"URL"`
|
||||
MaxOpenConns int `yaml:"max_open_conns,omitempty" env:"MAX_OPEN_CONNS"`
|
||||
MaxIdleConns int `yaml:"max_idle_conns,omitempty" env:"MAX_IDLE_CONNS"`
|
||||
ConnMaxLifetime time.Duration `yaml:"conn_max_life_time,omitempty" env:"CONN_MAX_LIFE_TIME"`
|
||||
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time,omitempty" env:"CONN_MAX_IDLE_TIME"`
|
||||
}
|
||||
|
||||
type Keys struct {
|
||||
@@ -156,22 +185,33 @@ type Keys struct {
|
||||
SystemAdminKey string `yaml:"system_admin_key,omitempty" env:"SYSTEM_ADMIN_KEY"`
|
||||
}
|
||||
|
||||
type AuthProvider struct {
|
||||
Issuer string `yaml:"issuer"`
|
||||
ClientID string `yaml:"client_id"`
|
||||
ClientSecret string `yaml:"client_secret"`
|
||||
Scopes []string `yaml:"additional_scopes"`
|
||||
type Auth struct {
|
||||
Provider AuthProvider `yaml:"provider,omitempty" envPrefix:"PROVIDER_"`
|
||||
SystemAdminPolicy SystemAdminPolicy `yaml:"system_admins"`
|
||||
}
|
||||
|
||||
type AuthProvider struct {
|
||||
Issuer string `yaml:"issuer" env:"ISSUER"`
|
||||
ClientID string `yaml:"client_id" env:"CLIENT_ID"`
|
||||
ClientSecret string `yaml:"client_secret" env:"CLIENT_SECRET"`
|
||||
Scopes []string `yaml:"additional_scopes" env:"SCOPES"`
|
||||
}
|
||||
|
||||
type DNS struct {
|
||||
MagicDNSSuffix string `yaml:"magic_dns_suffix"`
|
||||
MagicDNSSuffix string `yaml:"magic_dns_suffix"`
|
||||
Provider DNSProvider `yaml:"provider,omitempty"`
|
||||
}
|
||||
|
||||
type DNSProvider struct {
|
||||
Name string `yaml:"name"`
|
||||
Zone string `yaml:"zone"`
|
||||
Configuration map[string]string `yaml:"config"`
|
||||
}
|
||||
|
||||
type SystemAdminPolicy struct {
|
||||
Subs []string `json:"subs,omitempty"`
|
||||
Emails []string `json:"emails,omitempty"`
|
||||
Filters []string `json:"filters,omitempty"`
|
||||
Subs []string `yaml:"subs,omitempty"`
|
||||
Emails []string `yaml:"emails,omitempty"`
|
||||
Filters []string `yaml:"filters,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Config) CreateUrl(format string, a ...interface{}) string {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package handlers
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"time"
|
||||
)
|
||||
@@ -12,26 +11,28 @@ const (
|
||||
inactivityTimeout = 30 * time.Minute
|
||||
)
|
||||
|
||||
func NewReaper(brokers broker.Pubsub, repository domain.Repository) *Reaper {
|
||||
return &Reaper{
|
||||
pubsub: brokers,
|
||||
repository: repository,
|
||||
func StartReaper(repository domain.Repository, sessionManager PollMapSessionManager) {
|
||||
r := &reaper{
|
||||
sessionManager: sessionManager,
|
||||
repository: repository,
|
||||
}
|
||||
|
||||
go r.start()
|
||||
}
|
||||
|
||||
type Reaper struct {
|
||||
pubsub broker.Pubsub
|
||||
repository domain.Repository
|
||||
type reaper struct {
|
||||
sessionManager PollMapSessionManager
|
||||
repository domain.Repository
|
||||
}
|
||||
|
||||
func (r *Reaper) Start() {
|
||||
func (r *reaper) start() {
|
||||
t := time.NewTicker(ticker)
|
||||
for range t.C {
|
||||
r.reapInactiveEphemeralNodes()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reaper) reapInactiveEphemeralNodes() {
|
||||
func (r *reaper) reapInactiveEphemeralNodes() {
|
||||
ctx := context.Background()
|
||||
|
||||
now := time.Now().UTC()
|
||||
@@ -54,8 +55,8 @@ func (r *Reaper) reapInactiveEphemeralNodes() {
|
||||
}
|
||||
|
||||
if len(removedNodes) != 0 {
|
||||
for i, p := range removedNodes {
|
||||
r.pubsub.Publish(i, &broker.Signal{PeersRemoved: p})
|
||||
for i, _ := range removedNodes {
|
||||
r.sessionManager.NotifyAll(i)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Ping struct{}
|
||||
|
||||
type PollMapSessionManager interface {
|
||||
Register(tailnetID uint64, machineID uint64, ch chan *Ping)
|
||||
Deregister(tailnetID uint64, machineID uint64)
|
||||
HasSession(tailnetID uint64, machineID uint64) bool
|
||||
NotifyAll(tailnetID uint64)
|
||||
}
|
||||
|
||||
func NewPollMapSessionManager() PollMapSessionManager {
|
||||
return &pollMapSessionManager{
|
||||
data: map[uint64]map[uint64]chan *Ping{},
|
||||
timers: map[uint64]*time.Timer{},
|
||||
}
|
||||
}
|
||||
|
||||
type pollMapSessionManager struct {
|
||||
sync.RWMutex
|
||||
data map[uint64]map[uint64]chan *Ping
|
||||
timers map[uint64]*time.Timer
|
||||
}
|
||||
|
||||
func (n *pollMapSessionManager) Register(tailnetID uint64, machineID uint64, ch chan *Ping) {
|
||||
n.Lock()
|
||||
defer n.Unlock()
|
||||
|
||||
if ss := n.data[tailnetID]; ss == nil {
|
||||
n.data[tailnetID] = map[uint64]chan *Ping{machineID: ch}
|
||||
} else {
|
||||
ss[machineID] = ch
|
||||
}
|
||||
|
||||
t, ok := n.timers[machineID]
|
||||
if ok {
|
||||
t.Stop()
|
||||
delete(n.timers, machineID)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *pollMapSessionManager) Deregister(tailnetID uint64, machineID uint64) {
|
||||
n.Lock()
|
||||
defer n.Unlock()
|
||||
|
||||
if ss := n.data[tailnetID]; ss != nil {
|
||||
delete(ss, machineID)
|
||||
}
|
||||
|
||||
t, ok := n.timers[machineID]
|
||||
if ok {
|
||||
t.Stop()
|
||||
delete(n.timers, machineID)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(10 * time.Second)
|
||||
go func() {
|
||||
<-timer.C
|
||||
if !n.HasSession(tailnetID, machineID) {
|
||||
n.NotifyAll(tailnetID)
|
||||
}
|
||||
}()
|
||||
|
||||
n.timers[machineID] = timer
|
||||
}
|
||||
|
||||
func (n *pollMapSessionManager) HasSession(tailnetID uint64, machineID uint64) bool {
|
||||
n.RLock()
|
||||
defer n.RUnlock()
|
||||
|
||||
if ss := n.data[tailnetID]; ss != nil {
|
||||
if _, ok := ss[machineID]; ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (n *pollMapSessionManager) NotifyAll(tailnetID uint64) {
|
||||
n.RLock()
|
||||
defer n.RUnlock()
|
||||
|
||||
if ss := n.data[tailnetID]; ss != nil {
|
||||
for _, p := range ss {
|
||||
p <- &Ping{}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/database/migration"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
"go.uber.org/zap"
|
||||
"tailscale.com/types/key"
|
||||
"time"
|
||||
|
||||
@@ -15,57 +15,55 @@ import (
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
"gorm.io/plugin/prometheus"
|
||||
)
|
||||
|
||||
type db interface {
|
||||
DB() *gorm.DB
|
||||
type dbLock interface {
|
||||
Lock() error
|
||||
Unlock() error
|
||||
UnlockErr(error) error
|
||||
}
|
||||
|
||||
func OpenDB(config *config.Database, logger hclog.Logger) (domain.Repository, broker.Pubsub, error) {
|
||||
db, pubsub, err := createDB(config, logger)
|
||||
func OpenDB(config *config.Database, logger *zap.Logger) (domain.Repository, error) {
|
||||
db, lock, err := createDB(config, logger)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
repository := domain.NewRepository(db.DB())
|
||||
_ = db.Use(prometheus.New(prometheus.Config{StartServer: false}))
|
||||
|
||||
if err := db.Lock(); err != nil {
|
||||
return nil, nil, err
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := db.UnlockErr(migrate(db.DB())); err != nil {
|
||||
return nil, nil, err
|
||||
sqlDB.SetMaxOpenConns(config.MaxOpenConns)
|
||||
sqlDB.SetMaxIdleConns(config.MaxIdleConns)
|
||||
sqlDB.SetConnMaxLifetime(config.ConnMaxLifetime)
|
||||
sqlDB.SetConnMaxIdleTime(config.ConnMaxIdleTime)
|
||||
|
||||
repository := domain.NewRepository(db)
|
||||
|
||||
if err := lock.Lock(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return repository, pubsub, nil
|
||||
if err := lock.UnlockErr(migrate(db)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return repository, nil
|
||||
}
|
||||
|
||||
func createDB(config *config.Database, logger hclog.Logger) (db, broker.Pubsub, error) {
|
||||
func createDB(config *config.Database, logger *zap.Logger) (*gorm.DB, dbLock, error) {
|
||||
gormConfig := &gorm.Config{
|
||||
Logger: &GormLoggerAdapter{logger: logger.Named("db")},
|
||||
Logger: &GormLoggerAdapter{logger: logger.Sugar()},
|
||||
}
|
||||
|
||||
switch config.Type {
|
||||
case "sqlite", "sqlite3":
|
||||
db, err := newSqliteDB(config, gormConfig)
|
||||
return db, broker.NewPubsubInMemory(), err
|
||||
return newSqliteDB(config, gormConfig)
|
||||
case "postgres", "postgresql":
|
||||
db, err := newPostgresDB(config, gormConfig)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
stdDB, err := db.DB().DB()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pubsub, err := broker.NewPubsub(context.TODO(), stdDB, config.Url)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return db, pubsub, err
|
||||
return newPostgresDB(config, gormConfig)
|
||||
}
|
||||
|
||||
return nil, nil, fmt.Errorf("invalid database type '%s'", config.Type)
|
||||
@@ -85,6 +83,10 @@ func migrate(db *gorm.DB) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := createJSONWebKeySet(ctx, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -108,8 +110,31 @@ func createServerKey(ctx context.Context, repository domain.Repository) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func createJSONWebKeySet(ctx context.Context, repository domain.Repository) error {
|
||||
jwks, err := repository.GetJSONWebKeySet(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if jwks != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
privateKey, id, err := util.NewPrivateKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jsonWebKey := domain.JSONWebKey{Id: id, PrivateKey: *privateKey}
|
||||
|
||||
if err := repository.SetJSONWebKeySet(ctx, &domain.JSONWebKeys{Key: jsonWebKey}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type GormLoggerAdapter struct {
|
||||
logger hclog.Logger
|
||||
logger *zap.SugaredLogger
|
||||
}
|
||||
|
||||
func (g *GormLoggerAdapter) LogMode(level logger.LogLevel) logger.Interface {
|
||||
@@ -117,11 +142,11 @@ func (g *GormLoggerAdapter) LogMode(level logger.LogLevel) logger.Interface {
|
||||
}
|
||||
|
||||
func (g *GormLoggerAdapter) Info(ctx context.Context, s string, i ...interface{}) {
|
||||
g.logger.Info(s, i)
|
||||
g.logger.Infow(s, i)
|
||||
}
|
||||
|
||||
func (g *GormLoggerAdapter) Warn(ctx context.Context, s string, i ...interface{}) {
|
||||
g.logger.Warn(s, i)
|
||||
g.logger.Warnw(s, i)
|
||||
}
|
||||
|
||||
func (g *GormLoggerAdapter) Error(ctx context.Context, s string, i ...interface{}) {
|
||||
@@ -129,21 +154,23 @@ func (g *GormLoggerAdapter) Error(ctx context.Context, s string, i ...interface{
|
||||
}
|
||||
|
||||
func (g *GormLoggerAdapter) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
|
||||
elapsed := time.Since(begin)
|
||||
switch {
|
||||
case err != nil && !errors.Is(err, gorm.ErrRecordNotFound):
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
g.logger.Error("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "err", err)
|
||||
} else {
|
||||
g.logger.Error("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows, "err", err)
|
||||
}
|
||||
case g.logger.IsTrace():
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
g.logger.Trace("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed)
|
||||
} else {
|
||||
g.logger.Trace("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows)
|
||||
if g.logger.Level().Enabled(zap.DebugLevel) {
|
||||
elapsed := time.Since(begin)
|
||||
switch {
|
||||
case err != nil && !errors.Is(err, gorm.ErrRecordNotFound):
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
g.logger.Debugw("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "err", err)
|
||||
} else {
|
||||
g.logger.Debugw("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows, "err", err)
|
||||
}
|
||||
default:
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
g.logger.Debugw("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed)
|
||||
} else {
|
||||
g.logger.Debugw("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,26 +14,26 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
// it's a good practice to copy the struct inside the function,
|
||||
// so side effects are prevented if the original struct changes during the time
|
||||
type ServerConfig struct {
|
||||
Key string `gorm:"primary_key"`
|
||||
Key string `gorm:"primaryKey"`
|
||||
Value []byte
|
||||
}
|
||||
|
||||
type Tailnet struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
Name string `gorm:"type:varchar(64);unique_index"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
Name string `gorm:"type:varchar(64);uniqueIndex"`
|
||||
DNSConfig domain.DNSConfig
|
||||
IAMPolicy domain.IAMPolicy
|
||||
ACLPolicy domain.ACLPolicy
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
ExternalID string
|
||||
LoginName string
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
Name string
|
||||
UserType domain.UserType
|
||||
TailnetID uint64
|
||||
@@ -43,8 +43,8 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
}
|
||||
|
||||
type SystemApiKey struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);unique_index"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);uniqueIndex"`
|
||||
Hash string
|
||||
|
||||
CreatedAt time.Time
|
||||
@@ -55,8 +55,8 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
}
|
||||
|
||||
type ApiKey struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);unique_index"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);uniqueIndex"`
|
||||
Hash string
|
||||
|
||||
CreatedAt time.Time
|
||||
@@ -70,8 +70,8 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
}
|
||||
|
||||
type AuthKey struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);unique_index"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);uniqueIndex"`
|
||||
Hash string
|
||||
Ephemeral bool
|
||||
Tags domain.Tags
|
||||
@@ -87,7 +87,7 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
}
|
||||
|
||||
type Machine struct {
|
||||
ID uint64 `gorm:"primary_key;autoIncrement:false"`
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false"`
|
||||
Name string
|
||||
NameIdx uint64
|
||||
MachineKey string
|
||||
@@ -117,8 +117,8 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
}
|
||||
|
||||
type RegistrationRequest struct {
|
||||
MachineKey string `gorm:"primary_key;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);unique_index"`
|
||||
MachineKey string `gorm:"primaryKey;autoIncrement:false"`
|
||||
Key string `gorm:"type:varchar(64);uniqueIndex"`
|
||||
Data domain.RegistrationRequestData
|
||||
CreatedAt time.Time
|
||||
Authenticated bool
|
||||
@@ -126,7 +126,7 @@ func m202209070900_initial_schema() *gormigrate.Migration {
|
||||
}
|
||||
|
||||
type AuthenticationRequest struct {
|
||||
Key string `gorm:"primary_key;autoIncrement:false"`
|
||||
Key string `gorm:"primaryKey;autoIncrement:false"`
|
||||
Token string
|
||||
TailnetID *uint64
|
||||
Error string
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func m202209251532_add_alias_column() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202209251532a",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Tailnet struct {
|
||||
Alias *string `gorm:"type:varchar(64)"`
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Tailnet{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func m202229251530_add_alias_column_constraint() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202209251532b",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Tailnet struct {
|
||||
Name string `gorm:"uniqueIndex"`
|
||||
Alias *string `gorm:"uniqueIndex"`
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Tailnet{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func m202210040828_add_derpmap_colum() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202210040828",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Tailnet struct {
|
||||
Name string `gorm:"uniqueIndex"`
|
||||
Alias *string `gorm:"uniqueIndex"`
|
||||
DERPMap domain.DERPMap
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Tailnet{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func m202210070814_add_filesharing_and_servicecollection_columns() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202210070814",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Tailnet struct {
|
||||
Name string `gorm:"uniqueIndex"`
|
||||
Alias *string `gorm:"uniqueIndex"`
|
||||
ServiceCollectionEnabled bool
|
||||
FileSharingEnabled bool
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Tailnet{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func m202210080700_ssh_action_request() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202210080700",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Tailnet struct {
|
||||
Name string `gorm:"uniqueIndex"`
|
||||
Alias *string `gorm:"uniqueIndex"`
|
||||
SSHEnabled bool
|
||||
}
|
||||
|
||||
type SSHActionRequest struct {
|
||||
Key string `gorm:"primary_key"`
|
||||
Action string
|
||||
SrcMachineID uint64
|
||||
DstMachineID uint64
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Tailnet{},
|
||||
&SSHActionRequest{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func m202211031100_add_authorized_column() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202211031100",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Tailnet struct {
|
||||
Name string `gorm:"uniqueIndex"`
|
||||
MachineAuthorizationEnabled bool
|
||||
}
|
||||
|
||||
type AuthKey struct {
|
||||
PreAuthorized bool
|
||||
}
|
||||
|
||||
type Machine struct {
|
||||
Authorized bool `gorm:"default:true"`
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Tailnet{},
|
||||
&AuthKey{},
|
||||
&Machine{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func m202212201300_add_user_id_column() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202212201300",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type RegistrationRequest struct {
|
||||
Key string `gorm:"type:varchar(64);uniqueIndex"`
|
||||
UserID uint64
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&RegistrationRequest{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func m202212270800_machine_indeces() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202212270800",
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
type Machine struct {
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement:false;index:idx_tailnet_id_id,priority:2"`
|
||||
MachineKey string `gorm:"index:idx_machine_keys"`
|
||||
NodeKey string `gorm:"index:idx_machine_keys"`
|
||||
|
||||
Name string `gorm:"index:idx_tailnet_id_name,priority:2"`
|
||||
NameIdx uint64 `gorm:"index:idx_tailnet_id_name,sort:desc,priority:3"`
|
||||
|
||||
TailnetID uint64 `gorm:"index:idx_tailnet_id_id,priority:1;index:idx_tailnet_id_name,priority:1"`
|
||||
|
||||
IPv4 domain.IP `gorm:"index:idx_ipv4"`
|
||||
}
|
||||
|
||||
return db.AutoMigrate(
|
||||
&Machine{},
|
||||
)
|
||||
},
|
||||
Rollback: nil,
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,14 @@ func Migrations() []*gormigrate.Migration {
|
||||
var migrations = []*gormigrate.Migration{
|
||||
m202209070900_initial_schema(),
|
||||
m202209251530_add_autoallowips_column(),
|
||||
m202209251532_add_alias_column(),
|
||||
m202229251530_add_alias_column_constraint(),
|
||||
m202210040828_add_derpmap_colum(),
|
||||
m202210070814_add_filesharing_and_servicecollection_columns(),
|
||||
m202210080700_ssh_action_request(),
|
||||
m202211031100_add_authorized_column(),
|
||||
m202212201300_add_user_id_column(),
|
||||
m202212270800_machine_indeces(),
|
||||
}
|
||||
return migrations
|
||||
}
|
||||
|
||||
@@ -11,26 +11,20 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newPostgresDB(config *config.Database, g *gorm.Config) (db, error) {
|
||||
func newPostgresDB(config *config.Database, g *gorm.Config) (*gorm.DB, dbLock, error) {
|
||||
db, err := gorm.Open(postgres.Open(config.Url), g)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return &Postgres{
|
||||
db: db,
|
||||
}, nil
|
||||
return db, &pgLock{db: db}, nil
|
||||
}
|
||||
|
||||
type Postgres struct {
|
||||
type pgLock struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (s *Postgres) DB() *gorm.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
func (s *Postgres) Lock() error {
|
||||
func (s *pgLock) Lock() error {
|
||||
d, _ := s.db.DB()
|
||||
|
||||
query := `SELECT pg_advisory_lock($1)`
|
||||
@@ -42,7 +36,14 @@ func (s *Postgres) Lock() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Postgres) Unlock() error {
|
||||
func (s *pgLock) UnlockErr(prevErr error) error {
|
||||
if err := s.unlock(); err != nil {
|
||||
return multierror.Append(prevErr, err)
|
||||
}
|
||||
return prevErr
|
||||
}
|
||||
|
||||
func (s *pgLock) unlock() error {
|
||||
d, _ := s.db.DB()
|
||||
|
||||
query := `SELECT pg_advisory_unlock($1)`
|
||||
@@ -53,16 +54,9 @@ func (s *Postgres) Unlock() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Postgres) UnlockErr(prevErr error) error {
|
||||
if err := s.Unlock(); err != nil {
|
||||
return multierror.Append(prevErr, err)
|
||||
}
|
||||
return prevErr
|
||||
}
|
||||
|
||||
const advisoryLockIDSalt uint = 1486364155
|
||||
|
||||
func (s *Postgres) generateAdvisoryLockId() string {
|
||||
func (s *pgLock) generateAdvisoryLockId() string {
|
||||
sum := crc32.ChecksumIEEE([]byte("ionscale_migration"))
|
||||
sum = sum * uint32(advisoryLockIDSalt)
|
||||
return fmt.Sprint(sum)
|
||||
|
||||
@@ -6,33 +6,21 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newSqliteDB(config *config.Database, g *gorm.Config) (db, error) {
|
||||
func newSqliteDB(config *config.Database, g *gorm.Config) (*gorm.DB, dbLock, error) {
|
||||
db, err := gorm.Open(sqlite.Open(config.Url), g)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return &Sqlite{
|
||||
db: db,
|
||||
}, nil
|
||||
return db, &sqliteLock{}, nil
|
||||
}
|
||||
|
||||
type Sqlite struct {
|
||||
db *gorm.DB
|
||||
type sqliteLock struct {
|
||||
}
|
||||
|
||||
func (s *Sqlite) DB() *gorm.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
func (s *Sqlite) Lock() error {
|
||||
func (s *sqliteLock) Lock() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Sqlite) Unlock() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Sqlite) UnlockErr(prevErr error) error {
|
||||
func (s *sqliteLock) UnlockErr(prevErr error) error {
|
||||
return prevErr
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/imdario/mergo"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/mapping"
|
||||
"github.com/libdns/azure"
|
||||
"github.com/libdns/cloudflare"
|
||||
"github.com/libdns/digitalocean"
|
||||
"github.com/libdns/googleclouddns"
|
||||
"github.com/libdns/libdns"
|
||||
"github.com/libdns/route53"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Provider interface {
|
||||
SetRecord(ctx context.Context, recordType, recordName, value string) error
|
||||
}
|
||||
|
||||
func NewProvider(config config.DNS) (Provider, error) {
|
||||
p := config.Provider
|
||||
if len(p.Zone) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(config.MagicDNSSuffix, p.Zone) {
|
||||
return nil, fmt.Errorf("invalid MagicDNS suffix [%s], not part of zone [%s]", config.MagicDNSSuffix, p.Zone)
|
||||
}
|
||||
|
||||
switch p.Name {
|
||||
case "azure":
|
||||
return configureAzureProvider(p.Zone, p.Configuration)
|
||||
case "cloudflare":
|
||||
return configureCloudflareProvider(p.Zone, p.Configuration)
|
||||
case "digitalocean":
|
||||
return configureDigitalOceanProvider(p.Zone, p.Configuration)
|
||||
case "googleclouddns":
|
||||
return configureGoogleCloudDNSProvider(p.Zone, p.Configuration)
|
||||
case "route53":
|
||||
return configureRoute53Provider(p.Zone, p.Configuration)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown dns provider: %s", p.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func configureAzureProvider(zone string, values map[string]string) (Provider, error) {
|
||||
p := &azure.Provider{}
|
||||
if err := mapping.CopyViaJson(values, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e := &azure.Provider{
|
||||
TenantId: config.GetString("IONSCALE_DNS_AZURE_TENANT_ID", ""),
|
||||
ClientId: config.GetString("IONSCALE_DNS_AZURE_CLIENT_ID", ""),
|
||||
ClientSecret: config.GetString("IONSCALE_DNS_AZURE_CLIENT_SECRET", ""),
|
||||
SubscriptionId: config.GetString("IONSCALE_DNS_AZURE_SUBSCRIPTION_ID", ""),
|
||||
ResourceGroupName: config.GetString("IONSCALE_DNS_AZURE_RESOURCE_GROUP_NAME", ""),
|
||||
}
|
||||
|
||||
// merge env configuration on top of the default/file configuration
|
||||
if err := mergo.Merge(p, e, mergo.WithOverride); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &externalProvider{zone: zone, setter: p}, nil
|
||||
}
|
||||
|
||||
func configureCloudflareProvider(zone string, values map[string]string) (Provider, error) {
|
||||
p := &cloudflare.Provider{}
|
||||
if err := mapping.CopyViaJson(values, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e := &cloudflare.Provider{
|
||||
APIToken: config.GetString("IONSCALE_DNS_CLOUDFLARE_API_TOKEN", ""),
|
||||
}
|
||||
|
||||
// merge env configuration on top of the default/file configuration
|
||||
if err := mergo.Merge(p, e, mergo.WithOverride); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &externalProvider{zone: zone, setter: p}, nil
|
||||
}
|
||||
|
||||
func configureDigitalOceanProvider(zone string, values map[string]string) (Provider, error) {
|
||||
p := &digitalocean.Provider{}
|
||||
if err := mapping.CopyViaJson(values, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e := &digitalocean.Provider{
|
||||
APIToken: config.GetString("IONSCALE_DNS_DIGITALOCEAN_API_TOKEN", ""),
|
||||
}
|
||||
|
||||
// merge env configuration on top of the default/file configuration
|
||||
if err := mergo.Merge(p, e, mergo.WithOverride); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &externalProvider{zone: zone, setter: p}, nil
|
||||
}
|
||||
|
||||
func configureGoogleCloudDNSProvider(zone string, values map[string]string) (Provider, error) {
|
||||
p := &googleclouddns.Provider{}
|
||||
if err := mapping.CopyViaJson(values, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e := &googleclouddns.Provider{
|
||||
Project: config.GetString("IONSCALE_DNS_GOOGLECLOUDDNS_PROJECT", ""),
|
||||
ServiceAccountJSON: config.GetString("IONSCALE_DNS_GOOGLECLOUDDNS_SERVICE_ACCOUNT_JSON", ""),
|
||||
}
|
||||
|
||||
// merge env configuration on top of the default/file configuration
|
||||
if err := mergo.Merge(p, e, mergo.WithOverride); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &externalProvider{zone: zone, setter: p}, nil
|
||||
}
|
||||
|
||||
func configureRoute53Provider(zone string, values map[string]string) (Provider, error) {
|
||||
p := &route53.Provider{}
|
||||
if err := mapping.CopyViaJson(values, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e := &route53.Provider{
|
||||
MaxRetries: 0,
|
||||
MaxWaitDur: 0,
|
||||
WaitForPropagation: false,
|
||||
Region: config.GetString("IONSCALE_DNS_ROUTE53_REGION", ""),
|
||||
AWSProfile: config.GetString("IONSCALE_DNS_ROUTE53_AWS_PROFILE", ""),
|
||||
AccessKeyId: config.GetString("IONSCALE_DNS_ROUTE53_ACCESS_KEY_ID", ""),
|
||||
SecretAccessKey: config.GetString("IONSCALE_DNS_ROUTE53_SECRET_ACCESS_KEY", ""),
|
||||
Token: config.GetString("IONSCALE_DNS_ROUTE53_TOKEN", ""),
|
||||
}
|
||||
|
||||
// merge env configuration on top of the default/file configuration
|
||||
if err := mergo.Merge(p, e, mergo.WithOverride); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &externalProvider{zone: zone, setter: p}, nil
|
||||
}
|
||||
|
||||
type externalProvider struct {
|
||||
zone string
|
||||
setter libdns.RecordSetter
|
||||
}
|
||||
|
||||
func (p *externalProvider) SetRecord(ctx context.Context, recordType, recordName, value string) error {
|
||||
_, err := p.setter.SetRecords(ctx, fmt.Sprintf("%s.", p.zone), []libdns.Record{{
|
||||
Type: recordType,
|
||||
Name: strings.TrimSuffix(recordName, p.zone),
|
||||
Value: value,
|
||||
TTL: 1 * time.Minute,
|
||||
}})
|
||||
return err
|
||||
}
|
||||
+45
-9
@@ -21,16 +21,17 @@ const (
|
||||
)
|
||||
|
||||
type AutoApprovers struct {
|
||||
Routes map[string][]string `json:"routes"`
|
||||
ExitNode []string `json:"exitNode"`
|
||||
Routes map[string][]string `json:"routes,omitempty"`
|
||||
ExitNode []string `json:"exitNode,omitempty"`
|
||||
}
|
||||
|
||||
type ACLPolicy struct {
|
||||
Groups map[string][]string `json:"groups,omitempty"`
|
||||
Hosts map[string]string `json:"hosts,omitempty"`
|
||||
ACLs []ACL `json:"acls"`
|
||||
TagOwners map[string][]string `json:"tagowners"`
|
||||
AutoApprovers AutoApprovers `json:"autoApprovers"`
|
||||
ACLs []ACL `json:"acls,omitempty"`
|
||||
TagOwners map[string][]string `json:"tagowners,omitempty"`
|
||||
AutoApprovers *AutoApprovers `json:"autoApprovers,omitempty"`
|
||||
SSHRules []SSHRule `json:"ssh,omitempty"`
|
||||
}
|
||||
|
||||
type ACL struct {
|
||||
@@ -39,7 +40,14 @@ type ACL struct {
|
||||
Dst []string `json:"dst"`
|
||||
}
|
||||
|
||||
func DefaultPolicy() ACLPolicy {
|
||||
type SSHRule struct {
|
||||
Action string `json:"action"`
|
||||
Src []string `json:"src"`
|
||||
Dst []string `json:"dst"`
|
||||
Users []string `json:"users"`
|
||||
}
|
||||
|
||||
func DefaultACLPolicy() ACLPolicy {
|
||||
return ACLPolicy{
|
||||
ACLs: []ACL{
|
||||
{
|
||||
@@ -52,7 +60,7 @@ func DefaultPolicy() ACLPolicy {
|
||||
}
|
||||
|
||||
func (a ACLPolicy) FindAutoApprovedIPs(routableIPs []netip.Prefix, tags []string, u *User) []netip.Prefix {
|
||||
if len(routableIPs) == 0 {
|
||||
if a.AutoApprovers == nil || len(routableIPs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -116,17 +124,26 @@ func (a ACLPolicy) FindAutoApprovedIPs(routableIPs []netip.Prefix, tags []string
|
||||
return result
|
||||
}
|
||||
|
||||
func (a ACLPolicy) IsTagOwner(tags []string, p *User) bool {
|
||||
for _, t := range tags {
|
||||
if a.isTagOwner(t, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a ACLPolicy) CheckTagOwners(tags []string, p *User) error {
|
||||
var result *multierror.Error
|
||||
for _, t := range tags {
|
||||
if ok := a.IsTagOwner(t, p); !ok {
|
||||
if ok := a.isTagOwner(t, p); !ok {
|
||||
result = multierror.Append(result, fmt.Errorf("tag [%s] is invalid or not permitted", t))
|
||||
}
|
||||
}
|
||||
return result.ErrorOrNil()
|
||||
}
|
||||
|
||||
func (a ACLPolicy) IsTagOwner(tag string, p *User) bool {
|
||||
func (a ACLPolicy) isTagOwner(tag string, p *User) bool {
|
||||
if p.UserType == UserTypeService {
|
||||
return true
|
||||
}
|
||||
@@ -387,6 +404,25 @@ func (a ACLPolicy) expandValuePortToPortRange(s string) ([]tailcfg.PortRange, er
|
||||
return ports, nil
|
||||
}
|
||||
|
||||
func (a ACLPolicy) isGroupMember(group string, m *Machine) bool {
|
||||
if m.HasTags() {
|
||||
return false
|
||||
}
|
||||
|
||||
users, ok := a.Groups[group]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
if m.HasUser(u) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *ACLPolicy) Scan(destination interface{}) error {
|
||||
switch value := destination.(type) {
|
||||
case []byte:
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
func (a ACLPolicy) BuildSSHPolicy(srcs []Machine, dst *Machine) *tailcfg.SSHPolicy {
|
||||
var rules []*tailcfg.SSHRule
|
||||
|
||||
expandSrcAliases := func(aliases []string, action string, u *User) []*tailcfg.SSHPrincipal {
|
||||
var allSrcIPsSet = &StringSet{}
|
||||
for _, alias := range aliases {
|
||||
if strings.HasPrefix(alias, "tag:") && action == "check" {
|
||||
continue
|
||||
}
|
||||
for _, src := range srcs {
|
||||
srcIPs := a.expandSSHSrcAlias(&src, alias, u)
|
||||
allSrcIPsSet.Add(srcIPs...)
|
||||
}
|
||||
}
|
||||
|
||||
var result = []*tailcfg.SSHPrincipal{}
|
||||
for _, i := range allSrcIPsSet.Items() {
|
||||
result = append(result, &tailcfg.SSHPrincipal{NodeIP: i})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
for _, rule := range a.SSHRules {
|
||||
if rule.Action != "accept" && rule.Action != "check" {
|
||||
continue
|
||||
}
|
||||
|
||||
var action = &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
}
|
||||
|
||||
if rule.Action == "check" {
|
||||
action = &tailcfg.SSHAction{
|
||||
HoldAndDelegate: "https://unused/machine/ssh/action/$SRC_NODE_ID/to/$DST_NODE_ID",
|
||||
}
|
||||
}
|
||||
|
||||
selfUsers, otherUsers := a.expandSSHDstToSSHUsers(dst, rule)
|
||||
|
||||
if len(selfUsers) != 0 {
|
||||
principals := expandSrcAliases(rule.Src, rule.Action, &dst.User)
|
||||
if len(principals) != 0 {
|
||||
rules = append(rules, &tailcfg.SSHRule{
|
||||
Principals: principals,
|
||||
SSHUsers: selfUsers,
|
||||
Action: action,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(otherUsers) != 0 {
|
||||
principals := expandSrcAliases(rule.Src, rule.Action, nil)
|
||||
if len(principals) != 0 {
|
||||
rules = append(rules, &tailcfg.SSHRule{
|
||||
Principals: principals,
|
||||
SSHUsers: otherUsers,
|
||||
Action: action,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &tailcfg.SSHPolicy{Rules: rules}
|
||||
}
|
||||
|
||||
func (a ACLPolicy) expandSSHSrcAlias(m *Machine, alias string, dstUser *User) []string {
|
||||
if dstUser != nil {
|
||||
if !m.HasUser(dstUser.Name) || m.HasTags() {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
if alias == AutoGroupMembers {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
if strings.Contains(alias, "@") && m.HasUser(alias) {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
if strings.HasPrefix(alias, "group:") && a.isGroupMember(alias, m) {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
return []string{}
|
||||
}
|
||||
|
||||
if alias == AutoGroupMembers && !m.HasTags() {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
if strings.Contains(alias, "@") && !m.HasTags() && m.HasUser(alias) {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
if strings.HasPrefix(alias, "group:") && !m.HasTags() && a.isGroupMember(alias, m) {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
if strings.HasPrefix(alias, "tag:") && m.HasTag(alias) {
|
||||
return m.IPs()
|
||||
}
|
||||
|
||||
return []string{}
|
||||
}
|
||||
|
||||
func (a ACLPolicy) expandSSHDstToSSHUsers(m *Machine, rule SSHRule) (map[string]string, map[string]string) {
|
||||
users := buildSSHUsers(rule.Users)
|
||||
|
||||
var selfUsers map[string]string
|
||||
var otherUsers map[string]string
|
||||
|
||||
for _, d := range rule.Dst {
|
||||
if strings.HasPrefix(d, "tag:") && m.HasTag(d) {
|
||||
otherUsers = users
|
||||
}
|
||||
|
||||
if m.HasUser(d) || d == AutoGroupSelf {
|
||||
selfUsers = users
|
||||
}
|
||||
}
|
||||
|
||||
return selfUsers, otherUsers
|
||||
}
|
||||
|
||||
func buildSSHUsers(users []string) map[string]string {
|
||||
var autogroupNonRoot = false
|
||||
m := make(map[string]string)
|
||||
for _, u := range users {
|
||||
if u == "autogroup:nonroot" {
|
||||
m["*"] = "="
|
||||
autogroupNonRoot = true
|
||||
} else {
|
||||
m[u] = u
|
||||
}
|
||||
}
|
||||
|
||||
// disable root when autogroup:nonroot is used and root is not explicitly enabled
|
||||
if _, exists := m["root"]; !exists && autogroupNonRoot {
|
||||
m["root"] = ""
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"tailscale.com/tailcfg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"autogroup:members"},
|
||||
Dst: []string{"autogroup:self"},
|
||||
Users: []string{"autogroup:nonroot"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: []*tailcfg.SSHPrincipal{
|
||||
{NodeIP: p1.IPv4.String()},
|
||||
{NodeIP: p1.IPv6.String()},
|
||||
},
|
||||
SSHUsers: map[string]string{
|
||||
"*": "=",
|
||||
"root": "",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithGroup(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
Groups: map[string][]string{
|
||||
"group:sre": {
|
||||
"john@example.com",
|
||||
},
|
||||
},
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"group:sre"},
|
||||
Dst: []string{"tag:web"},
|
||||
Users: []string{"autogroup:nonroot", "root"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com", "tag:web")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: []*tailcfg.SSHPrincipal{
|
||||
{NodeIP: p1.IPv4.String()},
|
||||
{NodeIP: p1.IPv6.String()},
|
||||
},
|
||||
SSHUsers: map[string]string{
|
||||
"*": "=",
|
||||
"root": "root",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithMatchingUsers(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"john@example.com"},
|
||||
Dst: []string{"john@example.com"},
|
||||
Users: []string{"autogroup:nonroot", "root"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: sshPrincipalsFromMachines(*p1),
|
||||
SSHUsers: map[string]string{
|
||||
"*": "=",
|
||||
"root": "root",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithMatchingUsersInGroup(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
Groups: map[string][]string{
|
||||
"group:sre": {"jane@example.com", "john@example.com"},
|
||||
},
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"group:sre"},
|
||||
Dst: []string{"john@example.com"},
|
||||
Users: []string{"autogroup:nonroot", "root"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: sshPrincipalsFromMachines(*p1),
|
||||
SSHUsers: map[string]string{
|
||||
"*": "=",
|
||||
"root": "root",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithNoMatchingUsers(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"jane@example.com"},
|
||||
Dst: []string{"john@example.com"},
|
||||
Users: []string{"autogroup:nonroot", "root"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
|
||||
assert.Nil(t, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithTags(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("nick@example.com")
|
||||
p3 := createMachine("nick@example.com", "tag:web")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"john@example.com", "tag:web"},
|
||||
Dst: []string{"tag:web"},
|
||||
Users: []string{"ubuntu"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com", "tag:web")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2, *p3}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: sshPrincipalsFromMachines(*p1, *p3),
|
||||
SSHUsers: map[string]string{
|
||||
"ubuntu": "ubuntu",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithTagsInDstAndAutogroupMemberInSrc(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("nick@example.com")
|
||||
p3 := createMachine("nick@example.com", "tag:web")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"autogroup:members"},
|
||||
Dst: []string{"tag:web"},
|
||||
Users: []string{"ubuntu"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com", "tag:web")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2, *p3}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: sshPrincipalsFromMachines(*p1, *p2),
|
||||
SSHUsers: map[string]string{
|
||||
"ubuntu": "ubuntu",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithUserInDstAndNonMatchingSrc(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"jane@example.com"},
|
||||
Dst: []string{"john@example.com"},
|
||||
Users: []string{"autogroup:nonroot"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
|
||||
assert.Nil(t, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithUserInDstAndAutogroupMembersSrc(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"autogroup:members"},
|
||||
Dst: []string{"john@example.com"},
|
||||
Users: []string{"autogroup:nonroot"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
expectedRules := []*tailcfg.SSHRule{
|
||||
{
|
||||
Principals: sshPrincipalsFromMachines(*p1),
|
||||
SSHUsers: map[string]string{
|
||||
"*": "=",
|
||||
"root": "",
|
||||
},
|
||||
Action: &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, expectedRules, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithAutogroupSelfAndTagSrc(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com", "tag:web")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "accept",
|
||||
Src: []string{"tag:web"},
|
||||
Dst: []string{"autogroup:self"},
|
||||
Users: []string{"autogroup:nonroot"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
|
||||
assert.Nil(t, actualRules.Rules)
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildSSHPolicy_WithTagsAndActionCheck(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com", "tag:web")
|
||||
|
||||
policy := ACLPolicy{
|
||||
SSHRules: []SSHRule{
|
||||
{
|
||||
Action: "check",
|
||||
Src: []string{"tag:web"},
|
||||
Dst: []string{"tag:web"},
|
||||
Users: []string{"autogroup:nonroot"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dst := createMachine("john@example.com", "tag:web")
|
||||
|
||||
actualRules := policy.BuildSSHPolicy([]Machine{*p1, *p2}, dst)
|
||||
|
||||
assert.Nil(t, actualRules.Rules)
|
||||
}
|
||||
|
||||
func printRules(rules []*tailcfg.SSHRule) {
|
||||
indent, err := json.MarshalIndent(rules, "", " ")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println(string(indent))
|
||||
}
|
||||
|
||||
func sshPrincipalsFromMachines(machines ...Machine) []*tailcfg.SSHPrincipal {
|
||||
x := StringSet{}
|
||||
for _, m := range machines {
|
||||
x.Add(m.IPv4.String(), m.IPv6.String())
|
||||
}
|
||||
|
||||
var result = []*tailcfg.SSHPrincipal{}
|
||||
|
||||
for _, i := range x.Items() {
|
||||
result = append(result, &tailcfg.SSHPrincipal{NodeIP: i})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
+10
-11
@@ -1,8 +1,6 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/jsiebens/ionscale/internal/addr"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"net/netip"
|
||||
@@ -11,14 +9,6 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func printRules(rules []tailcfg.FilterRule) {
|
||||
indent, err := json.MarshalIndent(rules, "", " ")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println(string(indent))
|
||||
}
|
||||
|
||||
func TestACLPolicy_BuildFilterRulesWildcards(t *testing.T) {
|
||||
p1 := createMachine("john@example.com")
|
||||
p2 := createMachine("jane@example.com")
|
||||
@@ -560,6 +550,15 @@ func TestACLPolicy_IsTagOwner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestACLPolicy_FindAutoApprovedIPsWhenNoAutoapproversAreSet(t *testing.T) {
|
||||
route1 := netip.MustParsePrefix("10.160.0.0/20")
|
||||
route2 := netip.MustParsePrefix("10.161.0.0/20")
|
||||
route3 := netip.MustParsePrefix("10.162.0.0/20")
|
||||
|
||||
policy := ACLPolicy{}
|
||||
assert.Nil(t, policy.FindAutoApprovedIPs([]netip.Prefix{route1, route2, route3}, nil, nil))
|
||||
}
|
||||
|
||||
func TestACLPolicy_FindAutoApprovedIPs(t *testing.T) {
|
||||
route1 := netip.MustParsePrefix("10.160.0.0/20")
|
||||
route2 := netip.MustParsePrefix("10.161.0.0/20")
|
||||
@@ -569,7 +568,7 @@ func TestACLPolicy_FindAutoApprovedIPs(t *testing.T) {
|
||||
Groups: map[string][]string{
|
||||
"group:admins": {"jane@example.com"},
|
||||
},
|
||||
AutoApprovers: AutoApprovers{
|
||||
AutoApprovers: &AutoApprovers{
|
||||
Routes: map[string][]string{
|
||||
route1.String(): {"group:admins"},
|
||||
route2.String(): {"john@example.com", "tag:router"},
|
||||
|
||||
@@ -65,7 +65,7 @@ func (r *repository) LoadApiKey(ctx context.Context, key string) (*ApiKey, error
|
||||
}
|
||||
|
||||
var m ApiKey
|
||||
tx := r.withContext(ctx).Preload("User").Preload("Tailnet").First(&m, "key = ?", split[0])
|
||||
tx := r.withContext(ctx).Preload("User").Preload("Tailnet").Take(&m, "key = ?", split[0])
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
@@ -79,7 +79,7 @@ func (r *repository) LoadApiKey(ctx context.Context, key string) (*ApiKey, error
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if !m.ExpiresAt.IsZero() && m.ExpiresAt.Before(time.Now()) {
|
||||
if m.ExpiresAt != nil && !m.ExpiresAt.IsZero() && m.ExpiresAt.Before(time.Now()) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
|
||||
+17
-15
@@ -11,7 +11,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func CreateAuthKey(tailnet *Tailnet, user *User, ephemeral bool, tags Tags, expiresAt *time.Time) (string, *AuthKey) {
|
||||
func CreateAuthKey(tailnet *Tailnet, user *User, ephemeral bool, preAuthorized bool, tags Tags, expiresAt *time.Time) (string, *AuthKey) {
|
||||
key := util.RandStringBytes(12)
|
||||
pwd := util.RandStringBytes(22)
|
||||
value := fmt.Sprintf("%s_%s", key, pwd)
|
||||
@@ -22,13 +22,14 @@ func CreateAuthKey(tailnet *Tailnet, user *User, ephemeral bool, tags Tags, expi
|
||||
}
|
||||
|
||||
return value, &AuthKey{
|
||||
ID: util.NextID(),
|
||||
Key: key,
|
||||
Hash: string(hash),
|
||||
Ephemeral: ephemeral,
|
||||
Tags: tags,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ExpiresAt: expiresAt,
|
||||
ID: util.NextID(),
|
||||
Key: key,
|
||||
Hash: string(hash),
|
||||
Ephemeral: ephemeral,
|
||||
PreAuthorized: preAuthorized,
|
||||
Tags: tags,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ExpiresAt: expiresAt,
|
||||
|
||||
TailnetID: tailnet.ID,
|
||||
UserID: user.ID,
|
||||
@@ -36,11 +37,12 @@ func CreateAuthKey(tailnet *Tailnet, user *User, ephemeral bool, tags Tags, expi
|
||||
}
|
||||
|
||||
type AuthKey struct {
|
||||
ID uint64 `gorm:"primary_key"`
|
||||
Key string
|
||||
Hash string
|
||||
Ephemeral bool
|
||||
Tags Tags
|
||||
ID uint64 `gorm:"primary_key"`
|
||||
Key string
|
||||
Hash string
|
||||
Ephemeral bool
|
||||
PreAuthorized bool
|
||||
Tags Tags
|
||||
|
||||
CreatedAt time.Time
|
||||
ExpiresAt *time.Time
|
||||
@@ -134,7 +136,7 @@ func (r *repository) LoadAuthKey(ctx context.Context, key string) (*AuthKey, err
|
||||
}
|
||||
|
||||
var m AuthKey
|
||||
tx := r.withContext(ctx).Preload("User").Preload("Tailnet").First(&m, "key = ?", split[0])
|
||||
tx := r.withContext(ctx).Preload("User").Preload("Tailnet").Take(&m, "key = ?", split[0])
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
@@ -148,7 +150,7 @@ func (r *repository) LoadAuthKey(ctx context.Context, key string) (*AuthKey, err
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if !m.ExpiresAt.IsZero() && m.ExpiresAt.Before(time.Now()) {
|
||||
if m.ExpiresAt != nil && !m.ExpiresAt.IsZero() && m.ExpiresAt.Before(time.Now()) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ func (r *repository) SaveAuthenticationRequest(ctx context.Context, session *Aut
|
||||
|
||||
func (r *repository) GetAuthenticationRequest(ctx context.Context, key string) (*AuthenticationRequest, error) {
|
||||
var m AuthenticationRequest
|
||||
tx := r.withContext(ctx).First(&m, "key = ?", key)
|
||||
tx := r.withContext(ctx).Take(&m, "key = ?", key)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
type DERPMap struct {
|
||||
Checksum string
|
||||
DERPMap tailcfg.DERPMap
|
||||
}
|
||||
|
||||
func (hi *DERPMap) Scan(destination interface{}) error {
|
||||
switch value := destination.(type) {
|
||||
case []byte:
|
||||
return json.Unmarshal(value, hi)
|
||||
default:
|
||||
return fmt.Errorf("unexpected data type %T", destination)
|
||||
}
|
||||
}
|
||||
|
||||
func (hi DERPMap) Value() (driver.Value, error) {
|
||||
bytes, err := json.Marshal(hi)
|
||||
return bytes, err
|
||||
}
|
||||
|
||||
// GormDataType gorm common data type
|
||||
func (DERPMap) GormDataType() string {
|
||||
return "json"
|
||||
}
|
||||
|
||||
// GormDBDataType gorm db data type
|
||||
func (DERPMap) GormDBDataType(db *gorm.DB, field *schema.Field) string {
|
||||
switch db.Dialector.Name() {
|
||||
case "sqlite":
|
||||
return "JSON"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type DefaultDERPMap interface {
|
||||
GetDERPMap(ctx context.Context) (*DERPMap, error)
|
||||
}
|
||||
@@ -9,10 +9,11 @@ import (
|
||||
)
|
||||
|
||||
type DNSConfig struct {
|
||||
MagicDNS bool `json:"magic_dns"`
|
||||
OverrideLocalDNS bool `json:"override_local_dns"`
|
||||
Nameservers []string `json:"nameservers"`
|
||||
Routes map[string][]string `json:"routes"`
|
||||
HttpsCertsEnabled bool `json:"http_certs"`
|
||||
MagicDNS bool `json:"magic_dns"`
|
||||
OverrideLocalDNS bool `json:"override_local_dns"`
|
||||
Nameservers []string `json:"nameservers"`
|
||||
Routes map[string][]string `json:"routes"`
|
||||
}
|
||||
|
||||
func (i *DNSConfig) Scan(destination interface{}) error {
|
||||
|
||||
@@ -11,6 +11,10 @@ import (
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
func DefaultIAMPolicy() IAMPolicy {
|
||||
return IAMPolicy{}
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
UserID string
|
||||
Username string
|
||||
|
||||
@@ -24,6 +24,7 @@ type Machine struct {
|
||||
RegisteredTags Tags
|
||||
Tags Tags
|
||||
KeyExpiryDisabled bool
|
||||
Authorized bool
|
||||
|
||||
HostInfo HostInfo
|
||||
Endpoints Endpoints
|
||||
@@ -46,6 +47,13 @@ type Machine struct {
|
||||
|
||||
type Machines []Machine
|
||||
|
||||
func (m *Machine) CompleteName() string {
|
||||
if m.NameIdx != 0 {
|
||||
return fmt.Sprintf("%s-%d", m.Name, m.NameIdx)
|
||||
}
|
||||
return m.Name
|
||||
}
|
||||
|
||||
func (m *Machine) IPs() []string {
|
||||
return []string{m.IPv4.String(), m.IPv6.String()}
|
||||
}
|
||||
@@ -349,7 +357,7 @@ func (r *repository) DeleteMachine(ctx context.Context, id uint64) (bool, error)
|
||||
|
||||
func (r *repository) GetMachine(ctx context.Context, machineID uint64) (*Machine, error) {
|
||||
var m Machine
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("User").First(&m, "id = ?", machineID)
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("User").Take(&m, machineID)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
@@ -368,7 +376,7 @@ func (r *repository) GetNextMachineNameIndex(ctx context.Context, tailnetID uint
|
||||
tx := r.withContext(ctx).
|
||||
Where("name = ? AND tailnet_id = ?", name, tailnetID).
|
||||
Order("name_idx desc").
|
||||
First(&m)
|
||||
Take(&m)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return 0, nil
|
||||
@@ -383,7 +391,7 @@ func (r *repository) GetNextMachineNameIndex(ctx context.Context, tailnetID uint
|
||||
|
||||
func (r *repository) GetMachineByKey(ctx context.Context, tailnetID uint64, machineKey string) (*Machine, error) {
|
||||
var m Machine
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("User").First(&m, "tailnet_id = ? AND machine_key = ?", tailnetID, machineKey)
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("User").Take(&m, "tailnet_id = ? AND machine_key = ?", tailnetID, machineKey)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
@@ -398,7 +406,7 @@ func (r *repository) GetMachineByKey(ctx context.Context, tailnetID uint64, mach
|
||||
|
||||
func (r *repository) GetMachineByKeys(ctx context.Context, machineKey string, nodeKey string) (*Machine, error) {
|
||||
var m Machine
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("User").First(&m, "machine_key = ? AND node_key = ?", machineKey, nodeKey)
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("User").Take(&m, "machine_key = ? AND node_key = ?", machineKey, nodeKey)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
|
||||
@@ -19,6 +19,7 @@ type RegistrationRequest struct {
|
||||
CreatedAt time.Time
|
||||
Authenticated bool
|
||||
Error string
|
||||
UserID uint64
|
||||
}
|
||||
|
||||
func (r *RegistrationRequest) IsFinished() bool {
|
||||
@@ -67,7 +68,7 @@ func (r *repository) SaveRegistrationRequest(ctx context.Context, request *Regis
|
||||
|
||||
func (r *repository) GetRegistrationRequestByKey(ctx context.Context, key string) (*RegistrationRequest, error) {
|
||||
var m RegistrationRequest
|
||||
tx := r.withContext(ctx).First(&m, "key = ?", key)
|
||||
tx := r.withContext(ctx).Take(&m, "key = ?", key)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
@@ -82,7 +83,7 @@ func (r *repository) GetRegistrationRequestByKey(ctx context.Context, key string
|
||||
|
||||
func (r *repository) GetRegistrationRequestByMachineKey(ctx context.Context, key string) (*RegistrationRequest, error) {
|
||||
var m RegistrationRequest
|
||||
tx := r.withContext(ctx).First(&m, "machine_key = ?", key)
|
||||
tx := r.withContext(ctx).Take(&m, "machine_key = ?", key)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
|
||||
@@ -3,6 +3,7 @@ package domain
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
"sync"
|
||||
@@ -14,15 +15,18 @@ type Repository interface {
|
||||
GetControlKeys(ctx context.Context) (*ControlKeys, error)
|
||||
SetControlKeys(ctx context.Context, keys *ControlKeys) error
|
||||
|
||||
GetDERPMap(ctx context.Context) (*tailcfg.DERPMap, error)
|
||||
SetDERPMap(ctx context.Context, v *tailcfg.DERPMap) error
|
||||
GetJSONWebKeySet(ctx context.Context) (*JSONWebKeys, error)
|
||||
SetJSONWebKeySet(ctx context.Context, keys *JSONWebKeys) error
|
||||
|
||||
GetDERPMap(ctx context.Context) (*DERPMap, error)
|
||||
SetDERPMap(ctx context.Context, v *DERPMap) error
|
||||
|
||||
GetAccount(ctx context.Context, accountID uint64) (*Account, error)
|
||||
GetOrCreateAccount(ctx context.Context, externalID, loginName string) (*Account, bool, error)
|
||||
|
||||
SaveTailnet(ctx context.Context, tailnet *Tailnet) error
|
||||
GetOrCreateTailnet(ctx context.Context, name string, iamPolicy IAMPolicy) (*Tailnet, bool, error)
|
||||
GetTailnet(ctx context.Context, id uint64) (*Tailnet, error)
|
||||
GetTailnetByAlias(ctx context.Context, alias string) (*Tailnet, error)
|
||||
ListTailnets(ctx context.Context) ([]Tailnet, error)
|
||||
DeleteTailnet(ctx context.Context, id uint64) error
|
||||
|
||||
@@ -73,6 +77,10 @@ type Repository interface {
|
||||
GetAuthenticationRequest(ctx context.Context, key string) (*AuthenticationRequest, error)
|
||||
DeleteAuthenticationRequest(ctx context.Context, key string) error
|
||||
|
||||
SaveSSHActionRequest(ctx context.Context, session *SSHActionRequest) error
|
||||
GetSSHActionRequest(ctx context.Context, key string) (*SSHActionRequest, error)
|
||||
DeleteSSHActionRequest(ctx context.Context, key string) error
|
||||
|
||||
Transaction(func(rp Repository) error) error
|
||||
}
|
||||
|
||||
@@ -100,10 +108,10 @@ func (r *repository) Transaction(action func(Repository) error) error {
|
||||
|
||||
type derpMapCache struct {
|
||||
sync.RWMutex
|
||||
value *tailcfg.DERPMap
|
||||
value *DERPMap
|
||||
}
|
||||
|
||||
func (d *derpMapCache) Get() (*tailcfg.DERPMap, error) {
|
||||
func (d *derpMapCache) Get() (*DERPMap, error) {
|
||||
d.RLock()
|
||||
|
||||
if d.value != nil {
|
||||
@@ -131,7 +139,10 @@ func (d *derpMapCache) Get() (*tailcfg.DERPMap, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d.value = m
|
||||
d.value = &DERPMap{
|
||||
Checksum: util.Checksum(m),
|
||||
DERPMap: *m,
|
||||
}
|
||||
|
||||
return d.value, nil
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@ package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"tailscale.com/tailcfg"
|
||||
tkey "tailscale.com/types/key"
|
||||
"time"
|
||||
)
|
||||
|
||||
type configKey string
|
||||
@@ -14,8 +16,23 @@ type configKey string
|
||||
const (
|
||||
derpMapConfigKey configKey = "derp_map"
|
||||
controlKeysConfigKey configKey = "control_keys"
|
||||
jwksConfigKey configKey = "jwks"
|
||||
)
|
||||
|
||||
type JSONWebKeys struct {
|
||||
Key JSONWebKey
|
||||
}
|
||||
|
||||
type JSONWebKey struct {
|
||||
Id string
|
||||
PrivateKey rsa.PrivateKey
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (j JSONWebKey) Public() crypto.PublicKey {
|
||||
return j.PrivateKey.Public()
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Key configKey `gorm:"primary_key"`
|
||||
Value []byte
|
||||
@@ -45,8 +62,27 @@ func (r *repository) SetControlKeys(ctx context.Context, v *ControlKeys) error {
|
||||
return r.setServerConfig(ctx, controlKeysConfigKey, v)
|
||||
}
|
||||
|
||||
func (r *repository) GetDERPMap(ctx context.Context) (*tailcfg.DERPMap, error) {
|
||||
var m tailcfg.DERPMap
|
||||
func (r *repository) GetJSONWebKeySet(ctx context.Context) (*JSONWebKeys, error) {
|
||||
var m JSONWebKeys
|
||||
err := r.getServerConfig(ctx, jwksConfigKey, &m)
|
||||
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
func (r *repository) SetJSONWebKeySet(ctx context.Context, v *JSONWebKeys) error {
|
||||
return r.setServerConfig(ctx, jwksConfigKey, v)
|
||||
}
|
||||
|
||||
func (r *repository) GetDERPMap(ctx context.Context) (*DERPMap, error) {
|
||||
var m DERPMap
|
||||
|
||||
err := r.getServerConfig(ctx, derpMapConfigKey, &m)
|
||||
|
||||
@@ -54,6 +90,10 @@ func (r *repository) GetDERPMap(ctx context.Context) (*tailcfg.DERPMap, error) {
|
||||
return r.defaultDERPMap.Get()
|
||||
}
|
||||
|
||||
if m.Checksum == "" {
|
||||
return r.defaultDERPMap.Get()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -61,7 +101,7 @@ func (r *repository) GetDERPMap(ctx context.Context) (*tailcfg.DERPMap, error) {
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
func (r *repository) SetDERPMap(ctx context.Context, v *tailcfg.DERPMap) error {
|
||||
func (r *repository) SetDERPMap(ctx context.Context, v *DERPMap) error {
|
||||
return r.setServerConfig(ctx, "derp_map", v)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SSHActionRequest struct {
|
||||
Key string `gorm:"primary_key"`
|
||||
Action string
|
||||
SrcMachineID uint64
|
||||
DstMachineID uint64
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (r *repository) SaveSSHActionRequest(ctx context.Context, session *SSHActionRequest) error {
|
||||
tx := r.withContext(ctx).Save(session)
|
||||
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) GetSSHActionRequest(ctx context.Context, key string) (*SSHActionRequest, error) {
|
||||
var m SSHActionRequest
|
||||
tx := r.withContext(ctx).Take(&m, "key = ?", key)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
func (r *repository) DeleteSSHActionRequest(ctx context.Context, key string) error {
|
||||
tx := r.withContext(ctx).Delete(&SSHActionRequest{Key: key})
|
||||
return tx.Error
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func (r *repository) LoadSystemApiKey(ctx context.Context, token string) (*Syste
|
||||
}
|
||||
|
||||
var m SystemApiKey
|
||||
tx := r.withContext(ctx).Preload("Account").First(&m, "key = ?", key)
|
||||
tx := r.withContext(ctx).Preload("Account").Take(&m, "key = ?", key)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
|
||||
+33
-22
@@ -3,7 +3,6 @@ package domain
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
"gorm.io/gorm"
|
||||
"net/mail"
|
||||
"strings"
|
||||
@@ -11,11 +10,24 @@ import (
|
||||
)
|
||||
|
||||
type Tailnet struct {
|
||||
ID uint64 `gorm:"primary_key"`
|
||||
Name string
|
||||
DNSConfig DNSConfig
|
||||
IAMPolicy IAMPolicy
|
||||
ACLPolicy ACLPolicy
|
||||
ID uint64 `gorm:"primary_key"`
|
||||
Name string
|
||||
DNSConfig DNSConfig
|
||||
IAMPolicy IAMPolicy
|
||||
ACLPolicy ACLPolicy
|
||||
DERPMap DERPMap
|
||||
ServiceCollectionEnabled bool
|
||||
FileSharingEnabled bool
|
||||
SSHEnabled bool
|
||||
MachineAuthorizationEnabled bool
|
||||
}
|
||||
|
||||
func (t Tailnet) GetDERPMap(ctx context.Context, fallack DefaultDERPMap) (*DERPMap, error) {
|
||||
if t.DERPMap.Checksum == "" {
|
||||
return fallack.GetDERPMap(ctx)
|
||||
} else {
|
||||
return &t.DERPMap, nil
|
||||
}
|
||||
}
|
||||
|
||||
func SanitizeTailnetName(name string) string {
|
||||
@@ -45,22 +57,6 @@ func (r *repository) SaveTailnet(ctx context.Context, tailnet *Tailnet) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) GetOrCreateTailnet(ctx context.Context, name string, iamPolicy IAMPolicy) (*Tailnet, bool, error) {
|
||||
tailnet := &Tailnet{}
|
||||
id := util.NextID()
|
||||
|
||||
tx := r.withContext(ctx).
|
||||
Where(Tailnet{Name: name}).
|
||||
Attrs(Tailnet{ID: id, ACLPolicy: DefaultPolicy(), IAMPolicy: iamPolicy}).
|
||||
FirstOrCreate(tailnet)
|
||||
|
||||
if tx.Error != nil {
|
||||
return nil, false, tx.Error
|
||||
}
|
||||
|
||||
return tailnet, tailnet.ID == id, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetTailnet(ctx context.Context, id uint64) (*Tailnet, error) {
|
||||
var t Tailnet
|
||||
tx := r.withContext(ctx).Take(&t, "id = ?", id)
|
||||
@@ -76,6 +72,21 @@ func (r *repository) GetTailnet(ctx context.Context, id uint64) (*Tailnet, error
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetTailnetByAlias(ctx context.Context, alias string) (*Tailnet, error) {
|
||||
var t Tailnet
|
||||
tx := r.withContext(ctx).Take(&t, "alias = ?", alias)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (r *repository) ListTailnets(ctx context.Context) ([]Tailnet, error) {
|
||||
var tailnets = []Tailnet{}
|
||||
tx := r.withContext(ctx).Find(&tailnets)
|
||||
|
||||
@@ -100,7 +100,7 @@ func (r *repository) GetOrCreateUserWithAccount(ctx context.Context, tailnet *Ta
|
||||
|
||||
func (r *repository) GetUser(ctx context.Context, userID uint64) (*User, error) {
|
||||
var m User
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("Account").First(&m, "id = ? and user_type = ?", userID, UserTypePerson)
|
||||
tx := r.withContext(ctx).Preload("Tailnet").Preload("Account").Take(&m, "id = ?", userID)
|
||||
|
||||
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
|
||||
@@ -3,8 +3,9 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/jsiebens/ionscale/internal/addr"
|
||||
"github.com/jsiebens/ionscale/internal/provider"
|
||||
"github.com/jsiebens/ionscale/internal/auth"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/mr-tron/base58"
|
||||
"net/http"
|
||||
@@ -20,7 +21,7 @@ import (
|
||||
|
||||
func NewAuthenticationHandlers(
|
||||
config *config.Config,
|
||||
authProvider provider.AuthProvider,
|
||||
authProvider auth.Provider,
|
||||
systemIAMPolicy *domain.IAMPolicy,
|
||||
repository domain.Repository) *AuthenticationHandlers {
|
||||
|
||||
@@ -34,7 +35,7 @@ func NewAuthenticationHandlers(
|
||||
|
||||
type AuthenticationHandlers struct {
|
||||
repository domain.Repository
|
||||
authProvider provider.AuthProvider
|
||||
authProvider auth.Provider
|
||||
config *config.Config
|
||||
systemIAMPolicy *domain.IAMPolicy
|
||||
}
|
||||
@@ -56,21 +57,42 @@ type oauthState struct {
|
||||
Flow string
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) StartCliAuth(c echo.Context) error {
|
||||
func (h *AuthenticationHandlers) StartAuth(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
flow := c.Param("flow")
|
||||
key := c.Param("key")
|
||||
|
||||
if s, err := h.repository.GetAuthenticationRequest(ctx, key); err != nil || s == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
// machine registration auth flow
|
||||
if flow == "r" || flow == "" {
|
||||
if req, err := h.repository.GetRegistrationRequestByKey(ctx, key); err != nil || req == nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
csrf := c.Get(middleware.DefaultCSRFConfig.ContextKey).(string)
|
||||
return c.Render(http.StatusOK, "auth.html", &AuthFormData{ProviderAvailable: h.authProvider != nil, Csrf: csrf})
|
||||
}
|
||||
|
||||
// cli auth flow
|
||||
if flow == "c" {
|
||||
if s, err := h.repository.GetAuthenticationRequest(ctx, key); err != nil || s == nil {
|
||||
return logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
// ssh check auth flow
|
||||
if flow == "s" {
|
||||
if s, err := h.repository.GetSSHActionRequest(ctx, key); err != nil || s == nil {
|
||||
return logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if h.authProvider == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(fmt.Errorf("unable to start auth flow as no auth provider is configured"))
|
||||
}
|
||||
|
||||
state, err := h.createState("c", key)
|
||||
state, err := h.createState(flow, key)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
redirectUrl := h.authProvider.GetLoginURL(h.config.CreateUrl("/a/callback"), state)
|
||||
@@ -78,18 +100,6 @@ func (h *AuthenticationHandlers) StartCliAuth(c echo.Context) error {
|
||||
return c.Redirect(http.StatusFound, redirectUrl)
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) StartAuth(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
key := c.Param("key")
|
||||
|
||||
if req, err := h.repository.GetRegistrationRequestByKey(ctx, key); err != nil || req == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
}
|
||||
|
||||
csrf := c.Get(middleware.DefaultCSRFConfig.ContextKey).(string)
|
||||
return c.Render(http.StatusOK, "auth.html", &AuthFormData{ProviderAvailable: h.authProvider != nil, Csrf: csrf})
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) ProcessAuth(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
|
||||
@@ -99,7 +109,7 @@ func (h *AuthenticationHandlers) ProcessAuth(c echo.Context) error {
|
||||
|
||||
req, err := h.repository.GetRegistrationRequestByKey(ctx, key)
|
||||
if err != nil || req == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if authKey != "" {
|
||||
@@ -109,7 +119,7 @@ func (h *AuthenticationHandlers) ProcessAuth(c echo.Context) error {
|
||||
if interactive != "" {
|
||||
state, err := h.createState("r", key)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
redirectUrl := h.authProvider.GetLoginURL(h.config.CreateUrl("/a/callback"), state)
|
||||
@@ -126,22 +136,48 @@ func (h *AuthenticationHandlers) Callback(c echo.Context) error {
|
||||
code := c.QueryParam("code")
|
||||
state, err := h.readState(c.QueryParam("state"))
|
||||
if err != nil {
|
||||
return err
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Invalid state parameter")
|
||||
}
|
||||
|
||||
user, err := h.exchangeUser(code)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tailnets, err := h.listAvailableTailnets(ctx, user)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
account, _, err := h.repository.GetOrCreateAccount(ctx, user.ID, user.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if state.Flow == "s" {
|
||||
sshActionReq, err := h.repository.GetSSHActionRequest(ctx, state.Key)
|
||||
if err != nil || sshActionReq == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error?e=ua")
|
||||
}
|
||||
|
||||
machine, err := h.repository.GetMachine(ctx, sshActionReq.SrcMachineID)
|
||||
if err != nil || sshActionReq == nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if !machine.HasTags() && machine.User.AccountID != nil && *machine.User.AccountID == account.ID {
|
||||
sshActionReq.Action = "accept"
|
||||
if err := h.repository.SaveSSHActionRequest(ctx, sshActionReq); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
return c.Redirect(http.StatusFound, "/a/success")
|
||||
}
|
||||
|
||||
sshActionReq.Action = "reject"
|
||||
if err := h.repository.SaveSSHActionRequest(ctx, sshActionReq); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
return c.Redirect(http.StatusFound, "/a/error?e=nmo")
|
||||
}
|
||||
|
||||
tailnets, err := h.listAvailableTailnets(ctx, user)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
csrf := c.Get(middleware.DefaultCSRFConfig.ContextKey).(string)
|
||||
@@ -166,7 +202,7 @@ func (h *AuthenticationHandlers) Callback(c echo.Context) error {
|
||||
if state.Flow == "c" {
|
||||
isSystemAdmin, err := h.isSystemAdmin(ctx, user)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if !isSystemAdmin && len(tailnets) == 0 {
|
||||
@@ -185,14 +221,14 @@ func (h *AuthenticationHandlers) Callback(c echo.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return echo.NewHTTPError(http.StatusNotFound)
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) isSystemAdmin(ctx context.Context, u *provider.User) (bool, error) {
|
||||
func (h *AuthenticationHandlers) isSystemAdmin(ctx context.Context, u *auth.User) (bool, error) {
|
||||
return h.systemIAMPolicy.EvaluatePolicy(&domain.Identity{UserID: u.ID, Email: u.Name, Attr: u.Attr})
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) listAvailableTailnets(ctx context.Context, u *provider.User) ([]domain.Tailnet, error) {
|
||||
func (h *AuthenticationHandlers) listAvailableTailnets(ctx context.Context, u *auth.User) ([]domain.Tailnet, error) {
|
||||
var result = []domain.Tailnet{}
|
||||
tailnets, err := h.repository.ListTailnets(ctx)
|
||||
if err != nil {
|
||||
@@ -215,13 +251,13 @@ func (h *AuthenticationHandlers) EndOAuth(c echo.Context) error {
|
||||
|
||||
state, err := h.readState(c.QueryParam("state"))
|
||||
if err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Invalid state parameter")
|
||||
}
|
||||
|
||||
if state.Flow == "r" {
|
||||
req, err := h.repository.GetRegistrationRequestByKey(ctx, state.Key)
|
||||
if err != nil || req == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
return h.endMachineRegistrationFlow(c, req, state)
|
||||
@@ -229,13 +265,18 @@ func (h *AuthenticationHandlers) EndOAuth(c echo.Context) error {
|
||||
|
||||
req, err := h.repository.GetAuthenticationRequest(ctx, state.Key)
|
||||
if err != nil || req == nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
return h.endCliAuthenticationFlow(c, req, state)
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) Success(c echo.Context) error {
|
||||
s := c.QueryParam("s")
|
||||
switch s {
|
||||
case "nma":
|
||||
return c.Render(http.StatusOK, "newmachine.html", nil)
|
||||
}
|
||||
return c.Render(http.StatusOK, "success.html", nil)
|
||||
}
|
||||
|
||||
@@ -248,6 +289,8 @@ func (h *AuthenticationHandlers) Error(c echo.Context) error {
|
||||
return c.Render(http.StatusForbidden, "unauthorized.html", nil)
|
||||
case "nto":
|
||||
return c.Render(http.StatusForbidden, "notagowner.html", nil)
|
||||
case "nmo":
|
||||
return c.Render(http.StatusForbidden, "notmachineowner.html", nil)
|
||||
}
|
||||
return c.Render(http.StatusOK, "error.html", nil)
|
||||
}
|
||||
@@ -264,12 +307,12 @@ func (h *AuthenticationHandlers) endCliAuthenticationFlow(c echo.Context, req *d
|
||||
|
||||
var form TailnetSelectionForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
account, err := h.repository.GetAccount(ctx, form.AccountID)
|
||||
if err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
// continue as system admin?
|
||||
@@ -280,27 +323,27 @@ func (h *AuthenticationHandlers) endCliAuthenticationFlow(c echo.Context, req *d
|
||||
|
||||
err := h.repository.Transaction(func(rp domain.Repository) error {
|
||||
if err := rp.SaveSystemApiKey(ctx, apiKey); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
if err := rp.SaveAuthenticationRequest(ctx, req); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
return c.Redirect(http.StatusFound, "/a/success")
|
||||
}
|
||||
|
||||
tailnet, err := h.repository.GetTailnet(ctx, form.TailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
user, _, err := h.repository.GetOrCreateUserWithAccount(ctx, tailnet, account)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
expiresAt := time.Now().Add(24 * time.Hour)
|
||||
@@ -318,7 +361,7 @@ func (h *AuthenticationHandlers) endCliAuthenticationFlow(c echo.Context, req *d
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
return c.Redirect(http.StatusFound, "/a/success")
|
||||
@@ -329,7 +372,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
|
||||
var form TailnetSelectionForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
req := tailcfg.RegisterRequest(registrationRequest.Data)
|
||||
@@ -340,11 +383,12 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
var user *domain.User
|
||||
var ephemeral bool
|
||||
var tags = []string{}
|
||||
var authorized = false
|
||||
|
||||
if form.AuthKey != "" {
|
||||
authKey, err := h.repository.LoadAuthKey(ctx, form.AuthKey)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if authKey == nil {
|
||||
@@ -353,7 +397,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
registrationRequest.Error = "invalid auth key"
|
||||
|
||||
if err := h.repository.SaveRegistrationRequest(ctx, registrationRequest); err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
return c.Redirect(http.StatusFound, "/a/error?e=iak")
|
||||
@@ -363,20 +407,21 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
user = &authKey.User
|
||||
tags = authKey.Tags
|
||||
ephemeral = authKey.Ephemeral
|
||||
authorized = authKey.PreAuthorized
|
||||
} else {
|
||||
selectedTailnet, err := h.repository.GetTailnet(ctx, form.TailnetID)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
account, err := h.repository.GetAccount(ctx, form.AccountID)
|
||||
if err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
selectedUser, _, err := h.repository.GetOrCreateUserWithAccount(ctx, selectedTailnet, account)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
user = selectedUser
|
||||
@@ -388,7 +433,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
registrationRequest.Authenticated = false
|
||||
registrationRequest.Error = err.Error()
|
||||
if err := h.repository.SaveRegistrationRequest(ctx, registrationRequest); err != nil {
|
||||
return c.Redirect(http.StatusFound, "/a/error")
|
||||
return logError(err)
|
||||
}
|
||||
return c.Redirect(http.StatusFound, "/a/error?e=nto")
|
||||
}
|
||||
@@ -399,7 +444,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
|
||||
m, err := h.repository.GetMachineByKey(ctx, tailnet.ID, machineKey)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
@@ -412,7 +457,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
sanitizeHostname := dnsname.SanitizeHostname(req.Hostinfo.Hostname)
|
||||
nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
m = &domain.Machine{
|
||||
@@ -428,6 +473,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
CreatedAt: now,
|
||||
ExpiresAt: now.Add(180 * 24 * time.Hour).UTC(),
|
||||
KeyExpiryDisabled: len(tags) != 0,
|
||||
Authorized: !tailnet.MachineAuthorizationEnabled || authorized,
|
||||
|
||||
User: *user,
|
||||
Tailnet: *tailnet,
|
||||
@@ -435,7 +481,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
|
||||
ipv4, ipv6, err := addr.SelectIP(checkIP(ctx, h.repository.CountMachinesWithIPv4))
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
m.IPv4 = domain.IP{Addr: ipv4}
|
||||
m.IPv6 = domain.IP{Addr: ipv6}
|
||||
@@ -448,7 +494,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
if m.Name != sanitizeHostname {
|
||||
nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
m.Name = sanitizeHostname
|
||||
m.NameIdx = nameIdx
|
||||
@@ -468,6 +514,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
err = h.repository.Transaction(func(rp domain.Repository) error {
|
||||
registrationRequest.Authenticated = true
|
||||
registrationRequest.Error = ""
|
||||
registrationRequest.UserID = user.ID
|
||||
|
||||
if err := rp.SaveMachine(ctx, m); err != nil {
|
||||
return err
|
||||
@@ -481,13 +528,17 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
return c.Redirect(http.StatusFound, "/a/success")
|
||||
if m.Authorized {
|
||||
return c.Redirect(http.StatusFound, "/a/success")
|
||||
} else {
|
||||
return c.Redirect(http.StatusFound, "/a/success?s=nma")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AuthenticationHandlers) exchangeUser(code string) (*provider.User, error) {
|
||||
func (h *AuthenticationHandlers) exchangeUser(code string) (*auth.User, error) {
|
||||
redirectUrl := h.config.CreateUrl("/a/callback")
|
||||
|
||||
user, err := h.authProvider.Exchange(redirectUrl, code)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/jsiebens/ionscale/internal/bind"
|
||||
"github.com/jsiebens/ionscale/internal/dns"
|
||||
"github.com/labstack/echo/v4"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"tailscale.com/tailcfg"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NewDNSHandlers(createBinder bind.Factory, provider dns.Provider) *DNSHandlers {
|
||||
return &DNSHandlers{
|
||||
createBinder: createBinder,
|
||||
provider: provider,
|
||||
}
|
||||
}
|
||||
|
||||
type DNSHandlers struct {
|
||||
createBinder bind.Factory
|
||||
provider dns.Provider
|
||||
}
|
||||
|
||||
func (h *DNSHandlers) SetDNS(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
|
||||
binder, err := h.createBinder(c)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
req := &tailcfg.SetDNSRequest{}
|
||||
if err := binder.BindRequest(c, req); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if h.provider == nil {
|
||||
return echo.NewHTTPError(http.StatusNotFound)
|
||||
}
|
||||
|
||||
if err := h.provider.SetRecord(ctx, req.Type, req.Name, req.Value); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(req.Name, "_acme-challenge") && req.Type == "TXT" {
|
||||
// Listen to connection close
|
||||
notify := ctx.Done()
|
||||
timeout := time.After(5 * time.Minute)
|
||||
tick := time.NewTicker(5 * time.Second)
|
||||
|
||||
defer func() { tick.Stop() }()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-tick.C:
|
||||
txtrecords, _ := net.LookupTXT(req.Name)
|
||||
for _, txt := range txtrecords {
|
||||
if txt == req.Value {
|
||||
return binder.WriteResponse(c, http.StatusOK, tailcfg.SetDNSResponse{})
|
||||
}
|
||||
}
|
||||
case <-timeout:
|
||||
return binder.WriteResponse(c, http.StatusOK, tailcfg.SetDNSResponse{})
|
||||
case <-notify:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return binder.WriteResponse(c, http.StatusOK, tailcfg.SetDNSResponse{})
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/jsiebens/ionscale/internal/bind"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
"github.com/labstack/echo/v4"
|
||||
"gopkg.in/square/go-jose.v2"
|
||||
"net/http"
|
||||
"tailscale.com/tailcfg"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NewIDTokenHandlers(createBinder bind.Factory, config *config.Config, repository domain.Repository) *IDTokenHandlers {
|
||||
return &IDTokenHandlers{
|
||||
issuer: config.ServerUrl,
|
||||
jwksUri: config.CreateUrl("/.well-known/jwks"),
|
||||
createBinder: createBinder,
|
||||
repository: repository,
|
||||
}
|
||||
}
|
||||
|
||||
type IDTokenHandlers struct {
|
||||
issuer string
|
||||
jwksUri string
|
||||
createBinder bind.Factory
|
||||
repository domain.Repository
|
||||
}
|
||||
|
||||
func (h *IDTokenHandlers) OpenIDConfig(c echo.Context) error {
|
||||
v := map[string]interface{}{}
|
||||
|
||||
v["issuer"] = h.issuer
|
||||
v["jwks_uri"] = h.jwksUri
|
||||
v["subject_types_supported"] = []string{"public"}
|
||||
v["response_types_supported"] = []string{"id_token"}
|
||||
v["scopes_supported"] = []string{"openid"}
|
||||
v["id_token_signing_alg_values_supported"] = []string{"RS256"}
|
||||
v["claims_supported"] = []string{
|
||||
"sub",
|
||||
"aud",
|
||||
"exp",
|
||||
"iat",
|
||||
"iss",
|
||||
"jti",
|
||||
"nbf",
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, v)
|
||||
}
|
||||
|
||||
func (h *IDTokenHandlers) Jwks(c echo.Context) error {
|
||||
keySet, err := h.repository.GetJSONWebKeySet(c.Request().Context())
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
pub := jose.JSONWebKey{Key: keySet.Key.Public(), KeyID: keySet.Key.Id, Algorithm: "RS256", Use: "sig"}
|
||||
set := jose.JSONWebKeySet{Keys: []jose.JSONWebKey{pub}}
|
||||
return c.JSON(http.StatusOK, set)
|
||||
}
|
||||
|
||||
func (h *IDTokenHandlers) FetchToken(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
|
||||
keySet, err := h.repository.GetJSONWebKeySet(c.Request().Context())
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
binder, err := h.createBinder(c)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
req := &tailcfg.TokenRequest{}
|
||||
if err := binder.BindRequest(c, req); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
machineKey := binder.Peer().String()
|
||||
nodeKey := req.NodeKey.String()
|
||||
|
||||
var m *domain.Machine
|
||||
m, err = h.repository.GetMachineByKeys(ctx, machineKey, nodeKey)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest)
|
||||
}
|
||||
|
||||
_, tailnetDomain, sub := h.names(m)
|
||||
|
||||
now := time.Now()
|
||||
|
||||
claims := jwt.MapClaims{
|
||||
"jit": fmt.Sprintf("%d", util.NextID()),
|
||||
"iss": h.issuer,
|
||||
"sub": sub,
|
||||
"aud": []string{req.Audience},
|
||||
"exp": jwt.NewNumericDate(now.Add(5 * time.Minute)),
|
||||
"nbf": jwt.NewNumericDate(now),
|
||||
"iat": jwt.NewNumericDate(now),
|
||||
|
||||
"key": m.NodeKey,
|
||||
"addresses": []string{m.IPv4.String(), m.IPv6.String()},
|
||||
"nid": m.ID,
|
||||
"node": sub,
|
||||
"domain": tailnetDomain,
|
||||
}
|
||||
|
||||
if m.HasTags() {
|
||||
tags := []string{}
|
||||
for _, t := range m.Tags {
|
||||
tags = append(tags, fmt.Sprintf("%s:%s", tailnetDomain, t))
|
||||
}
|
||||
claims["tags"] = tags
|
||||
} else {
|
||||
claims["user"] = fmt.Sprintf("%s:%s", tailnetDomain, m.User.Name)
|
||||
claims["uid"] = m.UserID
|
||||
}
|
||||
|
||||
unsignedToken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
unsignedToken.Header["kid"] = keySet.Key.Id
|
||||
|
||||
jwtB64, err := unsignedToken.SignedString(&keySet.Key.PrivateKey)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
resp := tailcfg.TokenResponse{IDToken: jwtB64}
|
||||
return binder.WriteResponse(c, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (h *IDTokenHandlers) names(m *domain.Machine) (string, string, string) {
|
||||
var name = m.Name
|
||||
if m.NameIdx != 0 {
|
||||
name = fmt.Sprintf("%s-%d", m.Name, m.NameIdx)
|
||||
}
|
||||
|
||||
sanitizedTailnetName := domain.SanitizeTailnetName(m.Tailnet.Name)
|
||||
return name, sanitizedTailnetName, fmt.Sprintf("%s.%s", name, sanitizedTailnetName)
|
||||
}
|
||||
@@ -22,7 +22,7 @@ func KeyHandler(keys *config.ServerKeys) echo.HandlerFunc {
|
||||
if v != "" {
|
||||
clientCapabilityVersion, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return c.String(http.StatusBadRequest, "Invalid version")
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Invalid version")
|
||||
}
|
||||
|
||||
if clientCapabilityVersion >= NoiseCapabilityVersion {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"github.com/labstack/echo/v4"
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/h2c"
|
||||
"io"
|
||||
"net/http"
|
||||
"tailscale.com/control/controlhttp"
|
||||
"tailscale.com/net/netutil"
|
||||
@@ -25,14 +27,17 @@ func NewNoiseHandlers(controlKey key.MachinePrivate, createPeerHandler CreatePee
|
||||
}
|
||||
|
||||
func (h *NoiseHandlers) Upgrade(c echo.Context) error {
|
||||
conn, err := controlhttp.AcceptHTTP(c.Request().Context(), c.Response(), c.Request(), h.controlKey)
|
||||
conn, err := controlhttp.AcceptHTTP(c.Request().Context(), c.Response(), c.Request(), h.controlKey, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
handler := h.createPeerHandler(conn.Peer())
|
||||
|
||||
server := http.Server{}
|
||||
server.Handler = h2c.NewHandler(handler, &http2.Server{})
|
||||
return server.Serve(netutil.NewOneConnListener(conn, nil))
|
||||
if err := server.Serve(netutil.NewOneConnListener(conn, nil)); err != nil && !stderrors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+104
-125
@@ -3,49 +3,48 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"github.com/jsiebens/ionscale/internal/bind"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/core"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/mapping"
|
||||
"github.com/labstack/echo/v4"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"tailscale.com/tailcfg"
|
||||
"tailscale.com/types/opt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NewPollNetMapHandler(
|
||||
createBinder bind.Factory,
|
||||
brokers broker.Pubsub,
|
||||
repository domain.Repository,
|
||||
offlineTimers *OfflineTimers) *PollNetMapHandler {
|
||||
sessionManager core.PollMapSessionManager,
|
||||
repository domain.Repository) *PollNetMapHandler {
|
||||
|
||||
handler := &PollNetMapHandler{
|
||||
createBinder: createBinder,
|
||||
brokers: brokers,
|
||||
repository: repository,
|
||||
offlineTimers: offlineTimers,
|
||||
createBinder: createBinder,
|
||||
sessionManager: sessionManager,
|
||||
repository: repository,
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
type PollNetMapHandler struct {
|
||||
createBinder bind.Factory
|
||||
repository domain.Repository
|
||||
brokers broker.Pubsub
|
||||
offlineTimers *OfflineTimers
|
||||
createBinder bind.Factory
|
||||
repository domain.Repository
|
||||
sessionManager core.PollMapSessionManager
|
||||
}
|
||||
|
||||
func (h *PollNetMapHandler) PollNetMap(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
binder, err := h.createBinder(c)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
req := &tailcfg.MapRequest{}
|
||||
if err := binder.BindRequest(c, req); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
machineKey := binder.Peer().String()
|
||||
@@ -54,7 +53,7 @@ func (h *PollNetMapHandler) PollNetMap(c echo.Context) error {
|
||||
var m *domain.Machine
|
||||
m, err = h.repository.GetMachineByKeys(ctx, machineKey, nodeKey)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
@@ -79,59 +78,55 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m *
|
||||
m.LastSeen = &now
|
||||
|
||||
if err := h.repository.SaveMachine(ctx, m); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
tailnetID := m.TailnetID
|
||||
machineID := m.ID
|
||||
|
||||
h.brokers.Publish(tailnetID, &broker.Signal{PeerUpdated: &machineID})
|
||||
h.sessionManager.NotifyAll(tailnetID)
|
||||
|
||||
if !mapRequest.Stream {
|
||||
return c.String(http.StatusOK, "")
|
||||
}
|
||||
|
||||
var syncedPeers = make(map[uint64]bool)
|
||||
var derpMapChecksum = ""
|
||||
|
||||
response, syncedPeers, err := h.createMapResponse(m, binder, mapRequest, false, make(map[uint64]bool))
|
||||
response, syncedPeers, derpMapChecksum, err := h.createMapResponse(m, binder, mapRequest, false, make(map[uint64]bool), derpMapChecksum)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
updateChan := make(chan *broker.Signal, 20)
|
||||
|
||||
unsubscribe, err := h.brokers.Subscribe(tailnetID, updateChan)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.cancelOfflineMessage(machineID)
|
||||
updateChan := make(chan *core.Ping, 20)
|
||||
h.sessionManager.Register(m.TailnetID, m.ID, updateChan)
|
||||
|
||||
// Listen to connection close
|
||||
notify := c.Request().Context().Done()
|
||||
|
||||
keepAliveResponse, err := h.createKeepAliveResponse(binder, mapRequest)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
keepAliveTicker := time.NewTicker(config.KeepAliveInterval())
|
||||
syncTicker := time.NewTicker(5 * time.Second)
|
||||
|
||||
c.Response().WriteHeader(http.StatusOK)
|
||||
|
||||
if _, err := c.Response().Write(response); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
c.Response().Flush()
|
||||
|
||||
connectedDevices.WithLabelValues(m.Tailnet.Name).Inc()
|
||||
|
||||
keepAliveTicker := time.NewTicker(config.KeepAliveInterval())
|
||||
syncTicker := time.NewTicker(5 * time.Second)
|
||||
|
||||
defer func() {
|
||||
connectedDevices.WithLabelValues(m.Tailnet.Name).Dec()
|
||||
unsubscribe()
|
||||
h.sessionManager.Deregister(m.TailnetID, m.ID)
|
||||
keepAliveTicker.Stop()
|
||||
syncTicker.Stop()
|
||||
_ = h.repository.SetMachineLastSeen(ctx, machineID)
|
||||
h.scheduleOfflineMessage(tailnetID, machineID)
|
||||
}()
|
||||
|
||||
var latestSync = time.Now()
|
||||
@@ -144,7 +139,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m *
|
||||
case <-keepAliveTicker.C:
|
||||
if mapRequest.KeepAlive {
|
||||
if _, err := c.Response().Write(keepAliveResponse); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
_ = h.repository.SetMachineLastSeen(ctx, machineID)
|
||||
c.Response().Flush()
|
||||
@@ -153,7 +148,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m *
|
||||
if latestSync.Before(latestUpdate) {
|
||||
machine, err := h.repository.GetMachine(ctx, machineID)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
if machine == nil {
|
||||
return nil
|
||||
@@ -162,14 +157,14 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m *
|
||||
var payload []byte
|
||||
var payloadErr error
|
||||
|
||||
payload, syncedPeers, payloadErr = h.createMapResponse(machine, binder, mapRequest, true, syncedPeers)
|
||||
payload, syncedPeers, derpMapChecksum, payloadErr = h.createMapResponse(machine, binder, mapRequest, true, syncedPeers, derpMapChecksum)
|
||||
|
||||
if payloadErr != nil {
|
||||
return payloadErr
|
||||
}
|
||||
|
||||
if _, err := c.Response().Write(payload); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
c.Response().Flush()
|
||||
|
||||
@@ -188,24 +183,16 @@ func (h *PollNetMapHandler) handleReadOnly(c echo.Context, binder bind.Binder, m
|
||||
m.DiscoKey = request.DiscoKey.String()
|
||||
|
||||
if err := h.repository.SaveMachine(ctx, m); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
response, _, err := h.createMapResponse(m, binder, request, false, map[uint64]bool{})
|
||||
response, _, _, err := h.createMapResponse(m, binder, request, false, map[uint64]bool{}, "")
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
_, err = c.Response().Write(response)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *PollNetMapHandler) scheduleOfflineMessage(tailnetID, machineID uint64) {
|
||||
h.offlineTimers.startCh <- [2]uint64{tailnetID, machineID}
|
||||
}
|
||||
|
||||
func (h *PollNetMapHandler) cancelOfflineMessage(machineID uint64) {
|
||||
h.offlineTimers.stopCh <- machineID
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
func (h *PollNetMapHandler) createKeepAliveResponse(binder bind.Binder, request *tailcfg.MapRequest) ([]byte, error) {
|
||||
@@ -216,17 +203,25 @@ func (h *PollNetMapHandler) createKeepAliveResponse(binder bind.Binder, request
|
||||
return binder.Marshal(request.Compress, mapResponse)
|
||||
}
|
||||
|
||||
func (h *PollNetMapHandler) createMapResponse(m *domain.Machine, binder bind.Binder, request *tailcfg.MapRequest, delta bool, prevSyncedPeerIDs map[uint64]bool) ([]byte, map[uint64]bool, error) {
|
||||
func (h *PollNetMapHandler) createMapResponse(m *domain.Machine, binder bind.Binder, request *tailcfg.MapRequest, delta bool, prevSyncedPeerIDs map[uint64]bool, prevDerpMapChecksum string) ([]byte, map[uint64]bool, string, error) {
|
||||
ctx := context.TODO()
|
||||
|
||||
node, user, err := mapping.ToNode(m)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
prc := &primaryRoutesCollector{flagged: map[netip.Prefix]bool{}}
|
||||
|
||||
tailnet, err := h.repository.GetTailnet(ctx, m.TailnetID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, "", err
|
||||
}
|
||||
|
||||
serviceUser, _, err := h.repository.GetOrCreateServiceUser(ctx, tailnet)
|
||||
if err != nil {
|
||||
return nil, nil, "", err
|
||||
}
|
||||
|
||||
hostinfo := tailcfg.Hostinfo(m.HostInfo)
|
||||
node, user, err := mapping.ToNode(m, tailnet, serviceUser, false, true, prc.filter)
|
||||
if err != nil {
|
||||
return nil, nil, "", err
|
||||
}
|
||||
|
||||
policies := tailnet.ACLPolicy
|
||||
@@ -236,20 +231,22 @@ func (h *PollNetMapHandler) createMapResponse(m *domain.Machine, binder bind.Bin
|
||||
|
||||
candidatePeers, err := h.repository.ListMachinePeers(ctx, m.TailnetID, m.MachineKey)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, "", err
|
||||
}
|
||||
|
||||
syncedPeerIDs := map[uint64]bool{}
|
||||
syncedUserIDs := map[tailcfg.UserID]bool{}
|
||||
syncedUserIDs := map[tailcfg.UserID]bool{user.ID: true}
|
||||
|
||||
for _, peer := range candidatePeers {
|
||||
if peer.IsExpired() {
|
||||
continue
|
||||
}
|
||||
if policies.IsValidPeer(m, &peer) || policies.IsValidPeer(&peer, m) {
|
||||
n, u, err := mapping.ToNode(&peer)
|
||||
isConnected := h.sessionManager.HasSession(peer.TailnetID, peer.ID)
|
||||
|
||||
n, u, err := mapping.ToNode(&peer, tailnet, serviceUser, true, isConnected, prc.filter)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, "", err
|
||||
}
|
||||
changedPeers = append(changedPeers, n)
|
||||
syncedPeerIDs[peer.ID] = true
|
||||
@@ -268,43 +265,52 @@ func (h *PollNetMapHandler) createMapResponse(m *domain.Machine, binder bind.Bin
|
||||
|
||||
dnsConfig := tailnet.DNSConfig
|
||||
|
||||
derpMap, err := h.repository.GetDERPMap(ctx)
|
||||
derpMap, err := m.Tailnet.GetDERPMap(ctx, h.repository)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, "", err
|
||||
}
|
||||
|
||||
rules := policies.BuildFilterRules(candidatePeers, m)
|
||||
filterRules := policies.BuildFilterRules(candidatePeers, m)
|
||||
|
||||
controlTime := time.Now().UTC()
|
||||
var mapResponse *tailcfg.MapResponse
|
||||
|
||||
if !delta {
|
||||
mapResponse = &tailcfg.MapResponse{
|
||||
KeepAlive: false,
|
||||
Node: node,
|
||||
DNSConfig: mapping.ToDNSConfig(&m.Tailnet, &dnsConfig),
|
||||
PacketFilter: rules,
|
||||
DERPMap: derpMap,
|
||||
Domain: domain.SanitizeTailnetName(m.Tailnet.Name),
|
||||
Peers: changedPeers,
|
||||
UserProfiles: users,
|
||||
ControlTime: &controlTime,
|
||||
KeepAlive: false,
|
||||
Node: node,
|
||||
DNSConfig: mapping.ToDNSConfig(m, &m.Tailnet, &dnsConfig),
|
||||
PacketFilter: filterRules,
|
||||
DERPMap: &derpMap.DERPMap,
|
||||
Domain: domain.SanitizeTailnetName(m.Tailnet.Name),
|
||||
Peers: changedPeers,
|
||||
UserProfiles: users,
|
||||
ControlTime: &controlTime,
|
||||
CollectServices: optBool(tailnet.ServiceCollectionEnabled),
|
||||
Debug: &tailcfg.Debug{
|
||||
DisableLogTail: true,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
mapResponse = &tailcfg.MapResponse{
|
||||
Node: node,
|
||||
DNSConfig: mapping.ToDNSConfig(&m.Tailnet, &dnsConfig),
|
||||
PacketFilter: rules,
|
||||
DERPMap: derpMap,
|
||||
Domain: domain.SanitizeTailnetName(m.Tailnet.Name),
|
||||
PeersChanged: changedPeers,
|
||||
PeersRemoved: removedPeers,
|
||||
UserProfiles: users,
|
||||
ControlTime: &controlTime,
|
||||
Node: node,
|
||||
DNSConfig: mapping.ToDNSConfig(m, &m.Tailnet, &dnsConfig),
|
||||
PacketFilter: filterRules,
|
||||
Domain: domain.SanitizeTailnetName(m.Tailnet.Name),
|
||||
PeersChanged: changedPeers,
|
||||
PeersRemoved: removedPeers,
|
||||
UserProfiles: users,
|
||||
ControlTime: &controlTime,
|
||||
CollectServices: optBool(tailnet.ServiceCollectionEnabled),
|
||||
}
|
||||
|
||||
if prevDerpMapChecksum != derpMap.Checksum {
|
||||
mapResponse.DERPMap = &derpMap.DERPMap
|
||||
}
|
||||
}
|
||||
|
||||
if tailnet.SSHEnabled && hostinfo.TailscaleSSHEnabled() {
|
||||
mapResponse.SSHPolicy = policies.BuildSSHPolicy(candidatePeers, m)
|
||||
}
|
||||
|
||||
if request.OmitPeers {
|
||||
@@ -315,59 +321,32 @@ func (h *PollNetMapHandler) createMapResponse(m *domain.Machine, binder bind.Bin
|
||||
|
||||
payload, err := binder.Marshal(request.Compress, mapResponse)
|
||||
|
||||
return payload, syncedPeerIDs, nil
|
||||
return payload, syncedPeerIDs, derpMap.Checksum, nil
|
||||
}
|
||||
|
||||
func NewOfflineTimers(repository domain.Repository, pubsub broker.Pubsub) *OfflineTimers {
|
||||
return &OfflineTimers{
|
||||
repository: repository,
|
||||
pubsub: pubsub,
|
||||
data: make(map[uint64]*time.Timer),
|
||||
startCh: make(chan [2]uint64),
|
||||
stopCh: make(chan uint64),
|
||||
}
|
||||
func optBool(v bool) opt.Bool {
|
||||
b := opt.Bool("")
|
||||
b.Set(v)
|
||||
return b
|
||||
}
|
||||
|
||||
type OfflineTimers struct {
|
||||
repository domain.Repository
|
||||
pubsub broker.Pubsub
|
||||
data map[uint64]*time.Timer
|
||||
stopCh chan uint64
|
||||
startCh chan [2]uint64
|
||||
type primaryRoutesCollector struct {
|
||||
flagged map[netip.Prefix]bool
|
||||
}
|
||||
|
||||
func (o *OfflineTimers) Start() {
|
||||
for {
|
||||
select {
|
||||
case i := <-o.startCh:
|
||||
o.scheduleOfflineMessage(i[0], i[1])
|
||||
case m := <-o.stopCh:
|
||||
o.cancelOfflineMessage(m)
|
||||
func (p *primaryRoutesCollector) filter(m *domain.Machine) []netip.Prefix {
|
||||
var result = []netip.Prefix{}
|
||||
for _, r := range m.AllowIPs {
|
||||
if _, ok := p.flagged[r]; r.Bits() != 0 && !ok {
|
||||
result = append(result, r)
|
||||
p.flagged[r] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OfflineTimers) scheduleOfflineMessage(tailnetID, machineID uint64) {
|
||||
t, ok := o.data[machineID]
|
||||
if ok {
|
||||
t.Stop()
|
||||
delete(o.data, machineID)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(config.KeepAliveInterval())
|
||||
go func() {
|
||||
<-timer.C
|
||||
o.pubsub.Publish(tailnetID, &broker.Signal{PeerUpdated: &machineID})
|
||||
o.stopCh <- machineID
|
||||
}()
|
||||
|
||||
o.data[machineID] = timer
|
||||
}
|
||||
|
||||
func (o *OfflineTimers) cancelOfflineMessage(machineID uint64) {
|
||||
t, ok := o.data[machineID]
|
||||
if ok {
|
||||
t.Stop()
|
||||
delete(o.data, machineID)
|
||||
for _, r := range m.AutoAllowIPs {
|
||||
if _, ok := p.flagged[r]; r.Bits() != 0 && !ok {
|
||||
result = append(result, r)
|
||||
p.flagged[r] = true
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import (
|
||||
"context"
|
||||
"github.com/jsiebens/ionscale/internal/addr"
|
||||
"github.com/jsiebens/ionscale/internal/bind"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/core"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/mapping"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
"github.com/labstack/echo/v4"
|
||||
"net/http"
|
||||
@@ -19,21 +20,21 @@ import (
|
||||
func NewRegistrationHandlers(
|
||||
createBinder bind.Factory,
|
||||
config *config.Config,
|
||||
brokers broker.Pubsub,
|
||||
sessionManager core.PollMapSessionManager,
|
||||
repository domain.Repository) *RegistrationHandlers {
|
||||
return &RegistrationHandlers{
|
||||
createBinder: createBinder,
|
||||
pubsub: brokers,
|
||||
repository: repository,
|
||||
config: config,
|
||||
createBinder: createBinder,
|
||||
sessionManager: sessionManager,
|
||||
repository: repository,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
type RegistrationHandlers struct {
|
||||
createBinder bind.Factory
|
||||
repository domain.Repository
|
||||
pubsub broker.Pubsub
|
||||
config *config.Config
|
||||
createBinder bind.Factory
|
||||
repository domain.Repository
|
||||
sessionManager core.PollMapSessionManager
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
func (h *RegistrationHandlers) Register(c echo.Context) error {
|
||||
@@ -41,12 +42,12 @@ func (h *RegistrationHandlers) Register(c echo.Context) error {
|
||||
|
||||
binder, err := h.createBinder(c)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
req := &tailcfg.RegisterRequest{}
|
||||
if err := binder.BindRequest(c, req); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
machineKey := binder.Peer().String()
|
||||
@@ -56,7 +57,7 @@ func (h *RegistrationHandlers) Register(c echo.Context) error {
|
||||
m, err = h.repository.GetMachineByKeys(ctx, machineKey, nodeKey)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if m != nil {
|
||||
@@ -68,12 +69,18 @@ func (h *RegistrationHandlers) Register(c echo.Context) error {
|
||||
if !req.Expiry.IsZero() && req.Expiry.Before(time.Now()) {
|
||||
m.ExpiresAt = req.Expiry
|
||||
|
||||
if err := h.repository.SaveMachine(ctx, m); err != nil {
|
||||
return err
|
||||
if m.Ephemeral {
|
||||
if _, err := h.repository.DeleteMachine(ctx, m.ID); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
h.sessionManager.NotifyAll(m.TailnetID)
|
||||
} else {
|
||||
if err := h.repository.SaveMachine(ctx, m); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
h.sessionManager.NotifyAll(m.TailnetID)
|
||||
}
|
||||
|
||||
h.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
|
||||
response := tailcfg.RegisterResponse{NodeKeyExpired: true}
|
||||
return binder.WriteResponse(c, http.StatusOK, response)
|
||||
}
|
||||
@@ -82,7 +89,7 @@ func (h *RegistrationHandlers) Register(c echo.Context) error {
|
||||
if m.Name != sanitizeHostname {
|
||||
nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, m.TailnetID, sanitizeHostname)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
m.Name = sanitizeHostname
|
||||
m.NameIdx = nameIdx
|
||||
@@ -93,10 +100,17 @@ func (h *RegistrationHandlers) Register(c echo.Context) error {
|
||||
m.Tags = append(m.RegisteredTags, advertisedTags...)
|
||||
|
||||
if err := h.repository.SaveMachine(ctx, m); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
tUser, tLogin := mapping.ToUser(m.User)
|
||||
|
||||
response := tailcfg.RegisterResponse{
|
||||
MachineAuthorized: m.Authorized,
|
||||
User: tUser,
|
||||
Login: tLogin,
|
||||
}
|
||||
|
||||
response := tailcfg.RegisterResponse{MachineAuthorized: true}
|
||||
return binder.WriteResponse(c, http.StatusOK, response)
|
||||
}
|
||||
|
||||
@@ -112,7 +126,7 @@ func (h *RegistrationHandlers) authenticateMachine(c echo.Context, binder bind.B
|
||||
|
||||
if req.Auth.AuthKey == "" {
|
||||
key := util.RandStringBytes(8)
|
||||
authUrl := h.config.CreateUrl("/a/%s", key)
|
||||
authUrl := h.config.CreateUrl("/a/r/%s", key)
|
||||
|
||||
request := domain.RegistrationRequest{
|
||||
MachineKey: machineKey,
|
||||
@@ -140,7 +154,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
|
||||
authKey, err := h.repository.LoadAuthKey(ctx, req.Auth.AuthKey)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if authKey == nil {
|
||||
@@ -166,7 +180,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
|
||||
m, err = h.repository.GetMachineByKey(ctx, tailnet.ID, machineKey)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
@@ -175,7 +189,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
sanitizeHostname := dnsname.SanitizeHostname(req.Hostinfo.Hostname)
|
||||
nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
m = &domain.Machine{
|
||||
@@ -191,6 +205,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
CreatedAt: now,
|
||||
ExpiresAt: now.Add(180 * 24 * time.Hour).UTC(),
|
||||
KeyExpiryDisabled: len(tags) != 0,
|
||||
Authorized: !tailnet.MachineAuthorizationEnabled || authKey.PreAuthorized,
|
||||
|
||||
User: user,
|
||||
Tailnet: tailnet,
|
||||
@@ -202,7 +217,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
|
||||
ipv4, ipv6, err := addr.SelectIP(checkIP(ctx, h.repository.CountMachinesWithIPv4))
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
m.IPv4 = domain.IP{Addr: ipv4}
|
||||
m.IPv6 = domain.IP{Addr: ipv6}
|
||||
@@ -211,7 +226,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
if m.Name != sanitizeHostname {
|
||||
nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname)
|
||||
if err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
m.Name = sanitizeHostname
|
||||
m.NameIdx = nameIdx
|
||||
@@ -229,10 +244,16 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi
|
||||
}
|
||||
|
||||
if err := h.repository.SaveMachine(ctx, m); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
tUser, tLogin := mapping.ToUser(m.User)
|
||||
response := tailcfg.RegisterResponse{
|
||||
MachineAuthorized: true,
|
||||
User: tUser,
|
||||
Login: tLogin,
|
||||
}
|
||||
|
||||
response := tailcfg.RegisterResponse{MachineAuthorized: true}
|
||||
return binder.WriteResponse(c, http.StatusOK, response)
|
||||
}
|
||||
|
||||
@@ -257,7 +278,19 @@ func (h *RegistrationHandlers) followup(c echo.Context, binder bind.Binder, req
|
||||
}
|
||||
|
||||
if m != nil && m.IsFinished() {
|
||||
response := tailcfg.RegisterResponse{MachineAuthorized: len(m.Error) != 0, Error: m.Error}
|
||||
user, err := h.repository.GetUser(ctx, m.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u, l := mapping.ToUser(*user)
|
||||
|
||||
response := tailcfg.RegisterResponse{
|
||||
MachineAuthorized: len(m.Error) != 0,
|
||||
Error: m.Error,
|
||||
User: u,
|
||||
Login: l,
|
||||
}
|
||||
return binder.WriteResponse(c, http.StatusOK, response)
|
||||
}
|
||||
case <-notify:
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/jsiebens/ionscale/internal/bind"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
"github.com/labstack/echo/v4"
|
||||
"net/http"
|
||||
"tailscale.com/tailcfg"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NewSSHActionHandlers(createBinder bind.Factory, config *config.Config, repository domain.Repository) *SSHActionHandlers {
|
||||
return &SSHActionHandlers{
|
||||
createBinder: createBinder,
|
||||
repository: repository,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
type SSHActionHandlers struct {
|
||||
createBinder bind.Factory
|
||||
repository domain.Repository
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
type sshActionRequestData struct {
|
||||
SrcMachineID uint64 `param:"src_machine_id"`
|
||||
DstMachineID uint64 `param:"dst_machine_id"`
|
||||
}
|
||||
|
||||
func (h *SSHActionHandlers) StartAuth(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
|
||||
binder, err := h.createBinder(c)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
data := new(sshActionRequestData)
|
||||
if err = c.Bind(data); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
key := util.RandStringBytes(8)
|
||||
request := &domain.SSHActionRequest{
|
||||
Key: key,
|
||||
SrcMachineID: data.SrcMachineID,
|
||||
DstMachineID: data.DstMachineID,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
authUrl := h.config.CreateUrl("/a/s/%s", key)
|
||||
|
||||
if err := h.repository.SaveSSHActionRequest(ctx, request); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
resp := &tailcfg.SSHAction{
|
||||
Message: fmt.Sprintf("# Tailscale SSH requires an additional check.\n# To authenticate, visit: %s\n", authUrl),
|
||||
HoldAndDelegate: fmt.Sprintf("https://unused/machine/ssh/action/check/%s", key),
|
||||
}
|
||||
|
||||
return binder.WriteResponse(c, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (h *SSHActionHandlers) CheckAuth(c echo.Context) error {
|
||||
// Listen to connection close
|
||||
ctx := c.Request().Context()
|
||||
notify := ctx.Done()
|
||||
|
||||
binder, err := h.createBinder(c)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
tick := time.NewTicker(2 * time.Second)
|
||||
|
||||
defer func() { tick.Stop() }()
|
||||
|
||||
key := c.Param("key")
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-tick.C:
|
||||
m, err := h.repository.GetSSHActionRequest(ctx, key)
|
||||
|
||||
if err != nil || m == nil {
|
||||
return binder.WriteResponse(c, http.StatusOK, &tailcfg.SSHAction{Reject: true})
|
||||
}
|
||||
|
||||
if m.Action == "accept" {
|
||||
action := &tailcfg.SSHAction{
|
||||
Accept: true,
|
||||
AllowAgentForwarding: true,
|
||||
AllowLocalPortForwarding: true,
|
||||
}
|
||||
_ = h.repository.DeleteSSHActionRequest(ctx, key)
|
||||
return binder.WriteResponse(c, http.StatusOK, action)
|
||||
}
|
||||
|
||||
if m.Action == "reject" {
|
||||
action := &tailcfg.SSHAction{Reject: true}
|
||||
_ = h.repository.DeleteSSHActionRequest(ctx, key)
|
||||
return binder.WriteResponse(c, http.StatusOK, action)
|
||||
}
|
||||
case <-notify:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"github.com/jsiebens/ionscale/internal/version"
|
||||
"github.com/labstack/echo/v4"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@@ -14,3 +15,8 @@ func Version(c echo.Context) error {
|
||||
}
|
||||
return c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func logError(err error) error {
|
||||
zap.L().WithOptions(zap.AddCallerSkip(1)).Error("error processing request", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
+76
-26
@@ -27,8 +27,12 @@ func CopyViaJson[F any, T any](f F, t T) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func ToDNSConfig(tailnet *domain.Tailnet, c *domain.DNSConfig) *tailcfg.DNSConfig {
|
||||
tailnetDomain := domain.SanitizeTailnetName(tailnet.Name)
|
||||
func ToDNSConfig(m *domain.Machine, tailnet *domain.Tailnet, c *domain.DNSConfig) *tailcfg.DNSConfig {
|
||||
certsEnabled := c.HttpsCertsEnabled && config.DNSProviderConfigured()
|
||||
|
||||
sanitizeTailnetName := domain.SanitizeTailnetName(tailnet.Name)
|
||||
tailnetDomain := fmt.Sprintf("%s.%s", sanitizeTailnetName, config.MagicDNSSuffix())
|
||||
|
||||
resolvers := []*dnstype.Resolver{}
|
||||
for _, r := range c.Nameservers {
|
||||
resolver := &dnstype.Resolver{
|
||||
@@ -40,10 +44,15 @@ func ToDNSConfig(tailnet *domain.Tailnet, c *domain.DNSConfig) *tailcfg.DNSConfi
|
||||
dnsConfig := &tailcfg.DNSConfig{}
|
||||
|
||||
var domains []string
|
||||
var certDomains []string
|
||||
|
||||
if c.MagicDNS {
|
||||
domains = append(domains, fmt.Sprintf("%s.%s", tailnetDomain, config.MagicDNSSuffix()))
|
||||
domains = append(domains, tailnetDomain)
|
||||
dnsConfig.Proxied = true
|
||||
|
||||
if certsEnabled {
|
||||
certDomains = append(certDomains, fmt.Sprintf("%s.%s", m.CompleteName(), tailnetDomain))
|
||||
}
|
||||
}
|
||||
|
||||
if c.OverrideLocalDNS {
|
||||
@@ -52,8 +61,9 @@ func ToDNSConfig(tailnet *domain.Tailnet, c *domain.DNSConfig) *tailcfg.DNSConfi
|
||||
dnsConfig.FallbackResolvers = resolvers
|
||||
}
|
||||
|
||||
if len(c.Routes) != 0 {
|
||||
if len(c.Routes) != 0 || certsEnabled {
|
||||
routes := make(map[string][]*dnstype.Resolver)
|
||||
|
||||
for r, s := range c.Routes {
|
||||
routeResolver := []*dnstype.Resolver{}
|
||||
for _, addr := range s {
|
||||
@@ -67,11 +77,30 @@ func ToDNSConfig(tailnet *domain.Tailnet, c *domain.DNSConfig) *tailcfg.DNSConfi
|
||||
}
|
||||
|
||||
dnsConfig.Domains = domains
|
||||
dnsConfig.CertDomains = certDomains
|
||||
|
||||
return dnsConfig
|
||||
}
|
||||
|
||||
func ToNode(m *domain.Machine) (*tailcfg.Node, *tailcfg.UserProfile, error) {
|
||||
func ToNode(m *domain.Machine, tailnet *domain.Tailnet, taggedDevicesUser *domain.User, peer bool, connected bool, routeFilter func(m *domain.Machine) []netip.Prefix) (*tailcfg.Node, *tailcfg.UserProfile, error) {
|
||||
role := tailnet.IAMPolicy.GetRole(m.User)
|
||||
|
||||
var capabilities []string
|
||||
|
||||
if !peer {
|
||||
if !m.HasTags() && role == domain.UserRoleAdmin {
|
||||
capabilities = append(capabilities, tailcfg.CapabilityAdmin)
|
||||
}
|
||||
|
||||
if tailnet.FileSharingEnabled {
|
||||
capabilities = append(capabilities, tailcfg.CapabilityFileSharing)
|
||||
}
|
||||
|
||||
if tailnet.SSHEnabled {
|
||||
capabilities = append(capabilities, tailcfg.CapabilitySSH)
|
||||
}
|
||||
}
|
||||
|
||||
nKey, err := util.ParseNodePublicKey(m.NodeKey)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -115,8 +144,13 @@ func ToNode(m *domain.Machine) (*tailcfg.Node, *tailcfg.UserProfile, error) {
|
||||
allowedIPs = append(allowedIPs, ipv6)
|
||||
}
|
||||
|
||||
allowedIPs = append(allowedIPs, m.AllowIPs...)
|
||||
allowedIPs = append(allowedIPs, m.AutoAllowIPs...)
|
||||
if connected {
|
||||
allowedIPs = append(allowedIPs, routeFilter(m)...)
|
||||
}
|
||||
|
||||
if m.IsAllowedExitNode() {
|
||||
allowedIPs = append(allowedIPs, netip.MustParsePrefix("0.0.0.0/0"), netip.MustParsePrefix("::/0"))
|
||||
}
|
||||
|
||||
var derp string
|
||||
if hostinfo.NetInfo != nil {
|
||||
@@ -125,17 +159,14 @@ func ToNode(m *domain.Machine) (*tailcfg.Node, *tailcfg.UserProfile, error) {
|
||||
derp = "127.3.3.40:0"
|
||||
}
|
||||
|
||||
var name = m.Name
|
||||
if m.NameIdx != 0 {
|
||||
name = fmt.Sprintf("%s-%d", m.Name, m.NameIdx)
|
||||
}
|
||||
var name = m.CompleteName()
|
||||
|
||||
sanitizedTailnetName := domain.SanitizeTailnetName(m.Tailnet.Name)
|
||||
|
||||
hostInfo := tailcfg.Hostinfo{
|
||||
OS: hostinfo.OS,
|
||||
Hostname: hostinfo.Hostname,
|
||||
Services: hostinfo.Services,
|
||||
Services: filterServices(hostinfo.Services),
|
||||
}
|
||||
|
||||
n := tailcfg.Node{
|
||||
@@ -150,11 +181,12 @@ func ToNode(m *domain.Machine) (*tailcfg.Node, *tailcfg.UserProfile, error) {
|
||||
Endpoints: endpoints,
|
||||
DERP: derp,
|
||||
|
||||
Hostinfo: hostInfo.View(),
|
||||
Hostinfo: hostInfo.View(),
|
||||
Capabilities: capabilities,
|
||||
|
||||
Created: m.CreatedAt.UTC(),
|
||||
|
||||
MachineAuthorized: true,
|
||||
MachineAuthorized: m.Authorized,
|
||||
User: tailcfg.UserID(m.UserID),
|
||||
}
|
||||
|
||||
@@ -167,19 +199,17 @@ func ToNode(m *domain.Machine) (*tailcfg.Node, *tailcfg.UserProfile, error) {
|
||||
n.KeyExpiry = time.Time{}
|
||||
}
|
||||
|
||||
if m.LastSeen != nil {
|
||||
l := m.LastSeen.UTC()
|
||||
online := m.LastSeen.After(time.Now().Add(-config.KeepAliveInterval()))
|
||||
n.LastSeen = &l
|
||||
n.Online = &online
|
||||
n.Online = &connected
|
||||
if !connected && m.LastSeen != nil {
|
||||
n.LastSeen = m.LastSeen
|
||||
}
|
||||
|
||||
var user = ToUserProfile(m.User)
|
||||
|
||||
if m.HasTags() {
|
||||
n.User = tailcfg.UserID(m.ID)
|
||||
n.User = tailcfg.UserID(taggedDevicesUser.ID)
|
||||
user = tailcfg.UserProfile{
|
||||
ID: tailcfg.UserID(m.ID),
|
||||
ID: tailcfg.UserID(taggedDevicesUser.ID),
|
||||
LoginName: "tagged-devices",
|
||||
DisplayName: "Tagged Devices",
|
||||
}
|
||||
@@ -197,10 +227,30 @@ func ToUserProfile(u domain.User) tailcfg.UserProfile {
|
||||
return profile
|
||||
}
|
||||
|
||||
func ToUserProfiles(users domain.Users) []tailcfg.UserProfile {
|
||||
var profiles []tailcfg.UserProfile
|
||||
for _, u := range users {
|
||||
profiles = append(profiles, ToUserProfile(u))
|
||||
func ToUser(u domain.User) (tailcfg.User, tailcfg.Login) {
|
||||
user := tailcfg.User{
|
||||
ID: tailcfg.UserID(u.ID),
|
||||
LoginName: u.Name,
|
||||
DisplayName: u.Name,
|
||||
Logins: []tailcfg.LoginID{tailcfg.LoginID(u.ID)},
|
||||
Domain: u.Tailnet.Name,
|
||||
}
|
||||
return profiles
|
||||
login := tailcfg.Login{
|
||||
ID: tailcfg.LoginID(u.ID),
|
||||
LoginName: u.Name,
|
||||
DisplayName: u.Name,
|
||||
Domain: u.Tailnet.Name,
|
||||
}
|
||||
return user, login
|
||||
}
|
||||
|
||||
func filterServices(services []tailcfg.Service) []tailcfg.Service {
|
||||
result := []tailcfg.Service{}
|
||||
for _, s := range services {
|
||||
if s.Proto == tailcfg.TCP || s.Proto == tailcfg.UDP {
|
||||
continue
|
||||
}
|
||||
result = append(result, s)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
+42
-20
@@ -2,17 +2,35 @@ package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/labstack/echo-contrib/prometheus"
|
||||
"github.com/labstack/echo/v4"
|
||||
"runtime"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func EchoLogger(logger hclog.Logger) echo.MiddlewareFunc {
|
||||
httpLogger := logger.Named("http")
|
||||
func EchoErrorHandler() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
request := c.Request()
|
||||
|
||||
err := next(c)
|
||||
|
||||
if err != nil && strings.HasPrefix(request.RequestURI, "/a/") {
|
||||
return c.Render(http.StatusInternalServerError, "error.html", nil)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func EchoLogger(logger *zap.Logger) echo.MiddlewareFunc {
|
||||
httpLogger := logger.Sugar()
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) (err error) {
|
||||
if !httpLogger.IsTrace() {
|
||||
if !httpLogger.Level().Enabled(zap.DebugLevel) {
|
||||
return next(c)
|
||||
}
|
||||
|
||||
@@ -23,7 +41,7 @@ func EchoLogger(logger hclog.Logger) echo.MiddlewareFunc {
|
||||
c.Error(err)
|
||||
}
|
||||
|
||||
httpLogger.Trace("finished server http call",
|
||||
httpLogger.Debugw("finished server http call",
|
||||
"http.code", response.Status,
|
||||
"http.method", request.Method,
|
||||
"http.uri", request.RequestURI,
|
||||
@@ -35,23 +53,27 @@ func EchoLogger(logger hclog.Logger) echo.MiddlewareFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func EchoRecover(logger hclog.Logger) echo.MiddlewareFunc {
|
||||
httpLogger := logger.Named("http")
|
||||
func EchoRecover() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err, ok := r.(error)
|
||||
if !ok {
|
||||
err = fmt.Errorf("%v", r)
|
||||
apply := func() (topErr error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err, ok := r.(error)
|
||||
if !ok {
|
||||
err = fmt.Errorf("%v", r)
|
||||
}
|
||||
zap.L().Error("panic when processing request", zap.Error(err))
|
||||
topErr = err
|
||||
}
|
||||
stack := make([]byte, 4<<10) // 4 KB
|
||||
length := runtime.Stack(stack, false)
|
||||
httpLogger.Error("panic handling request", "err", err, "stack", string(stack[:length]))
|
||||
c.Error(err)
|
||||
}
|
||||
}()
|
||||
return next(c)
|
||||
}()
|
||||
return next(c)
|
||||
}
|
||||
return apply()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func EchoMetrics(p *prometheus.Prometheus) echo.MiddlewareFunc {
|
||||
return p.HandlerFunc
|
||||
}
|
||||
|
||||
@@ -10,6 +10,6 @@ import (
|
||||
)
|
||||
|
||||
func NewRpcHandler(systemAdminKey *key.ServerPrivate, repository domain.Repository, handler apiconnect.IonscaleServiceHandler) (string, http.Handler) {
|
||||
interceptors := connect.WithInterceptors(service.AuthenticationInterceptor(systemAdminKey, repository))
|
||||
interceptors := connect.WithInterceptors(service.NewErrorInterceptor(), service.AuthenticationInterceptor(systemAdminKey, repository))
|
||||
return apiconnect.NewIonscaleServiceHandler(handler, interceptors)
|
||||
}
|
||||
|
||||
+90
-72
@@ -5,27 +5,28 @@ import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"github.com/caddyserver/certmagic"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/jsiebens/ionscale/internal/auth"
|
||||
"github.com/jsiebens/ionscale/internal/bind"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/core"
|
||||
"github.com/jsiebens/ionscale/internal/database"
|
||||
"github.com/jsiebens/ionscale/internal/dns"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/handlers"
|
||||
"github.com/jsiebens/ionscale/internal/provider"
|
||||
"github.com/jsiebens/ionscale/internal/service"
|
||||
"github.com/jsiebens/ionscale/internal/templates"
|
||||
echo_prometheus "github.com/labstack/echo-contrib/prometheus"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/h2c"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"tailscale.com/types/key"
|
||||
)
|
||||
|
||||
@@ -37,11 +38,16 @@ func Start(c *config.Config) error {
|
||||
|
||||
logger.Info("Starting ionscale server")
|
||||
|
||||
repository, brokers, err := database.OpenDB(&c.Database, logger)
|
||||
httpLogger := logger.Named("http")
|
||||
dbLogger := logger.Named("db")
|
||||
|
||||
repository, err := database.OpenDB(&c.Database, dbLogger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sessionManager := core.NewPollMapSessionManager()
|
||||
|
||||
defaultControlKeys, err := repository.GetControlKeys(context.Background())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -52,11 +58,7 @@ func Start(c *config.Config) error {
|
||||
return err
|
||||
}
|
||||
|
||||
offlineTimers := handlers.NewOfflineTimers(repository, brokers)
|
||||
reaper := handlers.NewReaper(brokers, repository)
|
||||
|
||||
go offlineTimers.Start()
|
||||
go reaper.Start()
|
||||
core.StartReaper(repository, sessionManager)
|
||||
|
||||
serverUrl, err := url.Parse(c.ServerUrl)
|
||||
if err != nil {
|
||||
@@ -68,6 +70,7 @@ func Start(c *config.Config) error {
|
||||
certmagic.DefaultACME.Agreed = true
|
||||
certmagic.DefaultACME.Email = c.Tls.AcmeEmail
|
||||
certmagic.DefaultACME.CA = c.Tls.AcmeCA
|
||||
certmagic.Default.Logger = logger.Named("certmagic")
|
||||
if c.Tls.AcmePath != "" {
|
||||
certmagic.Default.Storage = &certmagic.FileStorage{Path: c.Tls.AcmePath}
|
||||
}
|
||||
@@ -81,27 +84,47 @@ func Start(c *config.Config) error {
|
||||
c.HttpsListenAddr = fmt.Sprintf(":%d", certmagic.HTTPSPort)
|
||||
}
|
||||
|
||||
createPeerHandler := func(p key.MachinePublic) http.Handler {
|
||||
registrationHandlers := handlers.NewRegistrationHandlers(bind.DefaultBinder(p), c, brokers, repository)
|
||||
pollNetMapHandler := handlers.NewPollNetMapHandler(bind.DefaultBinder(p), brokers, repository, offlineTimers)
|
||||
|
||||
e := echo.New()
|
||||
e.Use(EchoLogger(logger))
|
||||
e.Use(EchoRecover(logger))
|
||||
e.POST("/machine/register", registrationHandlers.Register)
|
||||
e.POST("/machine/map", pollNetMapHandler.PollNetMap)
|
||||
|
||||
return e
|
||||
}
|
||||
|
||||
authProvider, systemIAMPolicy, err := setupAuthProvider(c.AuthProvider)
|
||||
authProvider, systemIAMPolicy, err := setupAuthProvider(c.Auth)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error configuring OIDC provider: %v", err)
|
||||
}
|
||||
|
||||
dnsProvider, err := dns.NewProvider(c.DNS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p := echo_prometheus.NewPrometheus("http", nil)
|
||||
|
||||
metricsHandler := echo.New()
|
||||
p.SetMetricsPath(metricsHandler)
|
||||
|
||||
createPeerHandler := func(machinePublicKey key.MachinePublic) http.Handler {
|
||||
binder := bind.DefaultBinder(machinePublicKey)
|
||||
|
||||
registrationHandlers := handlers.NewRegistrationHandlers(binder, c, sessionManager, repository)
|
||||
pollNetMapHandler := handlers.NewPollNetMapHandler(binder, sessionManager, repository)
|
||||
dnsHandlers := handlers.NewDNSHandlers(binder, dnsProvider)
|
||||
idTokenHandlers := handlers.NewIDTokenHandlers(binder, c, repository)
|
||||
sshActionHandlers := handlers.NewSSHActionHandlers(binder, c, repository)
|
||||
|
||||
e := echo.New()
|
||||
e.Use(EchoMetrics(p), EchoLogger(httpLogger), EchoErrorHandler(), EchoRecover())
|
||||
e.POST("/machine/register", registrationHandlers.Register)
|
||||
e.POST("/machine/map", pollNetMapHandler.PollNetMap)
|
||||
e.POST("/machine/set-dns", dnsHandlers.SetDNS)
|
||||
e.POST("/machine/id-token", idTokenHandlers.FetchToken)
|
||||
e.GET("/machine/ssh/action/:src_machine_id/to/:dst_machine_id", sshActionHandlers.StartAuth)
|
||||
e.GET("/machine/ssh/action/check/:key", sshActionHandlers.CheckAuth)
|
||||
|
||||
return e
|
||||
}
|
||||
|
||||
noiseHandlers := handlers.NewNoiseHandlers(serverKey.ControlKey, createPeerHandler)
|
||||
registrationHandlers := handlers.NewRegistrationHandlers(bind.BoxBinder(serverKey.LegacyControlKey), c, brokers, repository)
|
||||
pollNetMapHandler := handlers.NewPollNetMapHandler(bind.BoxBinder(serverKey.LegacyControlKey), brokers, repository, offlineTimers)
|
||||
registrationHandlers := handlers.NewRegistrationHandlers(bind.BoxBinder(serverKey.LegacyControlKey), c, sessionManager, repository)
|
||||
pollNetMapHandler := handlers.NewPollNetMapHandler(bind.BoxBinder(serverKey.LegacyControlKey), sessionManager, repository)
|
||||
dnsHandlers := handlers.NewDNSHandlers(bind.BoxBinder(serverKey.LegacyControlKey), dnsProvider)
|
||||
idTokenHandlers := handlers.NewIDTokenHandlers(bind.BoxBinder(serverKey.LegacyControlKey), c, repository)
|
||||
authenticationHandlers := handlers.NewAuthenticationHandlers(
|
||||
c,
|
||||
authProvider,
|
||||
@@ -109,27 +132,18 @@ func Start(c *config.Config) error {
|
||||
repository,
|
||||
)
|
||||
|
||||
rpcService := service.NewService(c, authProvider, repository, brokers)
|
||||
rpcService := service.NewService(c, authProvider, repository, sessionManager)
|
||||
rpcPath, rpcHandler := NewRpcHandler(serverKey.SystemAdminKey, repository, rpcService)
|
||||
|
||||
p := echo_prometheus.NewPrometheus("http", nil)
|
||||
|
||||
metricsHandler := echo.New()
|
||||
p.SetMetricsPath(metricsHandler)
|
||||
|
||||
nonTlsAppHandler := echo.New()
|
||||
nonTlsAppHandler.Use(EchoRecover(logger))
|
||||
nonTlsAppHandler.Use(EchoLogger(logger))
|
||||
nonTlsAppHandler.Use(p.HandlerFunc)
|
||||
nonTlsAppHandler.Use(EchoMetrics(p), EchoLogger(httpLogger), EchoErrorHandler(), EchoRecover())
|
||||
nonTlsAppHandler.POST("/ts2021", noiseHandlers.Upgrade)
|
||||
nonTlsAppHandler.Any("/*", handlers.HttpRedirectHandler(c.Tls))
|
||||
|
||||
tlsAppHandler := echo.New()
|
||||
tlsAppHandler.Pre(handlers.HttpsRedirect(c.Tls))
|
||||
tlsAppHandler.Renderer = templates.NewTemplates()
|
||||
tlsAppHandler.Use(EchoRecover(logger))
|
||||
tlsAppHandler.Use(EchoLogger(logger))
|
||||
tlsAppHandler.Use(p.HandlerFunc)
|
||||
tlsAppHandler.Pre(handlers.HttpsRedirect(c.Tls))
|
||||
tlsAppHandler.Use(EchoMetrics(p), EchoLogger(logger), EchoErrorHandler(), EchoRecover())
|
||||
|
||||
tlsAppHandler.Any("/*", handlers.IndexHandler(http.StatusNotFound))
|
||||
tlsAppHandler.Any("/", handlers.IndexHandler(http.StatusOK))
|
||||
@@ -139,14 +153,16 @@ func Start(c *config.Config) error {
|
||||
tlsAppHandler.POST("/ts2021", noiseHandlers.Upgrade)
|
||||
tlsAppHandler.POST("/machine/:id", registrationHandlers.Register)
|
||||
tlsAppHandler.POST("/machine/:id/map", pollNetMapHandler.PollNetMap)
|
||||
tlsAppHandler.POST("/machine/:id/set-dns", dnsHandlers.SetDNS)
|
||||
tlsAppHandler.GET("/.well-known/jwks", idTokenHandlers.Jwks)
|
||||
tlsAppHandler.GET("/.well-known/openid-configuration", idTokenHandlers.OpenIDConfig)
|
||||
|
||||
auth := tlsAppHandler.Group("/a")
|
||||
auth.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
|
||||
TokenLookup: "form:_csrf",
|
||||
}))
|
||||
auth.GET("/:key", authenticationHandlers.StartAuth)
|
||||
auth.POST("/:key", authenticationHandlers.ProcessAuth)
|
||||
auth.GET("/c/:key", authenticationHandlers.StartCliAuth)
|
||||
auth.GET("/:flow/:key", authenticationHandlers.StartAuth)
|
||||
auth.POST("/:flow/:key", authenticationHandlers.ProcessAuth)
|
||||
auth.GET("/callback", authenticationHandlers.Callback)
|
||||
auth.POST("/callback", authenticationHandlers.EndOAuth)
|
||||
auth.GET("/success", authenticationHandlers.Success)
|
||||
@@ -179,25 +195,25 @@ func Start(c *config.Config) error {
|
||||
}
|
||||
|
||||
if c.Tls.AcmeEnabled {
|
||||
logger.Info("TLS is enabled with ACME", "domain", serverUrl.Host)
|
||||
logger.Info("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr)
|
||||
logger.Sugar().Infow("TLS is enabled with ACME", "domain", serverUrl.Host)
|
||||
logger.Sugar().Infow("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr)
|
||||
} else if !c.Tls.Disable {
|
||||
logger.Info("TLS is enabled", "cert", c.Tls.CertFile)
|
||||
logger.Info("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr)
|
||||
logger.Sugar().Infow("TLS is enabled", "cert", c.Tls.CertFile)
|
||||
logger.Sugar().Infow("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr)
|
||||
} else {
|
||||
logger.Warn("TLS is disabled")
|
||||
logger.Info("Server is running", "http_addr", c.HttpListenAddr, "metrics_addr", c.MetricsListenAddr)
|
||||
logger.Sugar().Warnw("TLS is disabled")
|
||||
logger.Sugar().Infow("Server is running", "http_addr", c.HttpListenAddr, "metrics_addr", c.MetricsListenAddr)
|
||||
}
|
||||
|
||||
return g.Wait()
|
||||
}
|
||||
|
||||
func setupAuthProvider(config config.AuthProvider) (provider.AuthProvider, *domain.IAMPolicy, error) {
|
||||
if len(config.Issuer) == 0 {
|
||||
func setupAuthProvider(config config.Auth) (auth.Provider, *domain.IAMPolicy, error) {
|
||||
if len(config.Provider.Issuer) == 0 {
|
||||
return nil, &domain.IAMPolicy{}, nil
|
||||
}
|
||||
|
||||
authProvider, err := provider.NewOIDCProvider(&config)
|
||||
authProvider, err := auth.NewOIDCProvider(&config.Provider)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -255,32 +271,34 @@ func selectListener(a net.Listener, b net.Listener) net.Listener {
|
||||
return b
|
||||
}
|
||||
|
||||
func setupLogging(config config.Logging) (hclog.Logger, error) {
|
||||
file, err := createLogFile(config)
|
||||
func setupLogging(config config.Logging) (*zap.Logger, error) {
|
||||
level, err := zap.ParseAtomicLevel(config.Level)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
appLogger := hclog.New(&hclog.LoggerOptions{
|
||||
Name: "ionscale",
|
||||
Level: hclog.LevelFromString(config.Level),
|
||||
JSONFormat: strings.ToLower(config.Format) == "json",
|
||||
Output: file,
|
||||
})
|
||||
|
||||
log.SetOutput(appLogger.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true}))
|
||||
log.SetPrefix("")
|
||||
log.SetFlags(0)
|
||||
pc := zap.NewProductionConfig()
|
||||
pc.Level = level
|
||||
pc.DisableStacktrace = true
|
||||
pc.OutputPaths = []string{"stdout"}
|
||||
pc.Encoding = "console"
|
||||
pc.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
|
||||
pc.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||
|
||||
return appLogger, nil
|
||||
}
|
||||
|
||||
func createLogFile(config config.Logging) (*os.File, error) {
|
||||
if config.File != "" {
|
||||
f, err := os.OpenFile(config.File, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
pc.OutputPaths = []string{config.File}
|
||||
}
|
||||
return os.Stdout, nil
|
||||
|
||||
if config.Format == "json" {
|
||||
pc.Encoding = "json"
|
||||
}
|
||||
|
||||
logger, err := pc.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
zap.ReplaceGlobals(logger)
|
||||
|
||||
return logger, nil
|
||||
}
|
||||
|
||||
+8
-10
@@ -2,10 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/mapping"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
@@ -14,12 +12,12 @@ import (
|
||||
func (s *Service) GetACLPolicy(ctx context.Context, req *connect.Request[api.GetACLPolicyRequest]) (*connect.Response[api.GetACLPolicyResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist"))
|
||||
@@ -27,7 +25,7 @@ func (s *Service) GetACLPolicy(ctx context.Context, req *connect.Request[api.Get
|
||||
|
||||
var policy api.ACLPolicy
|
||||
if err := mapping.CopyViaJson(&tailnet.ACLPolicy, &policy); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.GetACLPolicyResponse{Policy: &policy}), nil
|
||||
@@ -36,12 +34,12 @@ func (s *Service) GetACLPolicy(ctx context.Context, req *connect.Request[api.Get
|
||||
func (s *Service) SetACLPolicy(ctx context.Context, req *connect.Request[api.SetACLPolicyRequest]) (*connect.Response[api.SetACLPolicyResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist"))
|
||||
@@ -49,15 +47,15 @@ func (s *Service) SetACLPolicy(ctx context.Context, req *connect.Request[api.Set
|
||||
|
||||
var policy domain.ACLPolicy
|
||||
if err := mapping.CopyViaJson(req.Msg.Policy, &policy); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
tailnet.ACLPolicy = policy
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(tailnet.ID, &broker.Signal{ACLUpdated: true})
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
|
||||
return connect.NewResponse(&api.SetACLPolicyResponse{}), nil
|
||||
}
|
||||
|
||||
+16
-13
@@ -2,7 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.AuthenticationRequest], stream *connect.ServerStream[api.AuthenticationResponse]) error {
|
||||
func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.AuthenticateRequest], stream *connect.ServerStream[api.AuthenticateResponse]) error {
|
||||
if s.authProvider == nil {
|
||||
return connect.NewError(connect.CodeFailedPrecondition, errors.New("no authentication method available, contact your ionscale administrator for more information"))
|
||||
return connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("no authentication method available, contact your ionscale administrator for more information"))
|
||||
}
|
||||
|
||||
key := util.RandStringBytes(8)
|
||||
@@ -24,11 +24,11 @@ func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.Aut
|
||||
}
|
||||
|
||||
if err := s.repository.SaveAuthenticationRequest(ctx, session); err != nil {
|
||||
return err
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if err := stream.Send(&api.AuthenticationResponse{AuthUrl: authUrl}); err != nil {
|
||||
return err
|
||||
if err := stream.Send(&api.AuthenticateResponse{AuthUrl: authUrl}); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
notify := ctx.Done()
|
||||
@@ -43,24 +43,27 @@ func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.Aut
|
||||
select {
|
||||
case <-tick.C:
|
||||
m, err := s.repository.GetAuthenticationRequest(ctx, key)
|
||||
if err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
if err != nil || m == nil {
|
||||
return connect.NewError(connect.CodeInternal, errors.New("something went wrong"))
|
||||
if m == nil {
|
||||
return connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("invalid authentication request"))
|
||||
}
|
||||
|
||||
if len(m.Token) != 0 {
|
||||
if err := stream.Send(&api.AuthenticationResponse{Token: m.Token, TailnetId: m.TailnetID}); err != nil {
|
||||
return err
|
||||
if err := stream.Send(&api.AuthenticateResponse{Token: m.Token, TailnetId: m.TailnetID}); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(m.Error) != 0 {
|
||||
return connect.NewError(connect.CodePermissionDenied, errors.New(m.Error))
|
||||
return connect.NewError(connect.CodePermissionDenied, fmt.Errorf(m.Error))
|
||||
}
|
||||
|
||||
if err := stream.Send(&api.AuthenticationResponse{AuthUrl: authUrl}); err != nil {
|
||||
return err
|
||||
if err := stream.Send(&api.AuthenticateResponse{AuthUrl: authUrl}); err != nil {
|
||||
return logError(err)
|
||||
}
|
||||
|
||||
case <-notify:
|
||||
|
||||
@@ -2,7 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
@@ -15,15 +15,15 @@ func (s *Service) GetAuthKey(ctx context.Context, req *connect.Request[api.GetAu
|
||||
|
||||
key, err := s.repository.GetAuthKey(ctx, req.Msg.AuthKeyId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if key == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("auth key not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("auth key not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(key.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
var expiresAt *timestamppb.Timestamp
|
||||
@@ -74,16 +74,16 @@ func mapAuthKeysToApi(authKeys []domain.AuthKey) []*api.AuthKey {
|
||||
func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.ListAuthKeysRequest]) (*connect.Response[api.ListAuthKeysResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
response := api.ListAuthKeysResponse{}
|
||||
@@ -91,7 +91,7 @@ func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.Lis
|
||||
if principal.IsSystemAdmin() {
|
||||
authKeys, err := s.repository.ListAuthKeys(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
response.AuthKeys = mapAuthKeysToApi(authKeys)
|
||||
@@ -101,7 +101,7 @@ func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.Lis
|
||||
if principal.User != nil {
|
||||
authKeys, err := s.repository.ListAuthKeysByTailnetAndUser(ctx, req.Msg.TailnetId, principal.User.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
response.AuthKeys = mapAuthKeysToApi(authKeys)
|
||||
@@ -114,11 +114,11 @@ func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.Lis
|
||||
func (s *Service) CreateAuthKey(ctx context.Context, req *connect.Request[api.CreateAuthKeyRequest]) (*connect.Response[api.CreateAuthKeyResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if principal.User == nil && len(req.Msg.Tags) == 0 {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("at least one tag is required when creating an auth key"))
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("at least one tag is required when creating an auth key"))
|
||||
}
|
||||
|
||||
if err := domain.CheckTags(req.Msg.Tags); err != nil {
|
||||
@@ -127,11 +127,11 @@ func (s *Service) CreateAuthKey(ctx context.Context, req *connect.Request[api.Cr
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() {
|
||||
@@ -154,17 +154,17 @@ func (s *Service) CreateAuthKey(ctx context.Context, req *connect.Request[api.Cr
|
||||
if user == nil {
|
||||
u, _, err := s.repository.GetOrCreateServiceUser(ctx, tailnet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
user = u
|
||||
}
|
||||
|
||||
tags := domain.SanitizeTags(req.Msg.Tags)
|
||||
|
||||
v, authKey := domain.CreateAuthKey(tailnet, user, req.Msg.Ephemeral, tags, expiresAt)
|
||||
v, authKey := domain.CreateAuthKey(tailnet, user, req.Msg.Ephemeral, req.Msg.PreAuthorized, tags, expiresAt)
|
||||
|
||||
if err := s.repository.SaveAuthKey(ctx, authKey); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
response := api.CreateAuthKeyResponse{
|
||||
@@ -190,19 +190,19 @@ func (s *Service) DeleteAuthKey(ctx context.Context, req *connect.Request[api.De
|
||||
|
||||
key, err := s.repository.GetAuthKey(ctx, req.Msg.AuthKeyId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if key == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("auth key not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("auth key not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(key.UserID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if _, err := s.repository.DeleteAuthKey(ctx, req.Msg.AuthKeyId); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
return connect.NewResponse(&api.DeleteAuthKeyResponse{}), nil
|
||||
}
|
||||
|
||||
@@ -3,56 +3,85 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
func (s *Service) GetDERPMap(ctx context.Context, _ *connect.Request[api.GetDERPMapRequest]) (*connect.Response[api.GetDERPMapResponse], error) {
|
||||
func (s *Service) GetDefaultDERPMap(ctx context.Context, _ *connect.Request[api.GetDefaultDERPMapRequest]) (*connect.Response[api.GetDefaultDERPMapResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
derpMap, err := s.repository.GetDERPMap(ctx)
|
||||
dm, err := s.repository.GetDERPMap(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(derpMap)
|
||||
raw, err := json.Marshal(dm.DERPMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.GetDERPMapResponse{Value: raw}), nil
|
||||
return connect.NewResponse(&api.GetDefaultDERPMapResponse{Value: raw}), nil
|
||||
}
|
||||
|
||||
func (s *Service) SetDERPMap(ctx context.Context, req *connect.Request[api.SetDERPMapRequest]) (*connect.Response[api.SetDERPMapResponse], error) {
|
||||
func (s *Service) SetDefaultDERPMap(ctx context.Context, req *connect.Request[api.SetDefaultDERPMapRequest]) (*connect.Response[api.SetDefaultDERPMapResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
var derpMap tailcfg.DERPMap
|
||||
err := json.Unmarshal(req.Msg.Value, &derpMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if err := json.Unmarshal(req.Msg.Value, &derpMap); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
dp := domain.DERPMap{
|
||||
Checksum: util.Checksum(&derpMap),
|
||||
DERPMap: derpMap,
|
||||
}
|
||||
|
||||
if err := s.repository.SetDERPMap(ctx, &dp); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
tailnets, err := s.repository.ListTailnets(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.repository.SetDERPMap(ctx, &derpMap); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
for _, t := range tailnets {
|
||||
s.pubsub.Publish(t.ID, &broker.Signal{})
|
||||
s.sessionManager.NotifyAll(t.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.SetDERPMapResponse{Value: req.Msg.Value}), nil
|
||||
return connect.NewResponse(&api.SetDefaultDERPMapResponse{Value: req.Msg.Value}), nil
|
||||
}
|
||||
|
||||
func (s *Service) ResetDefaultDERPMap(ctx context.Context, req *connect.Request[api.ResetDefaultDERPMapRequest]) (*connect.Response[api.ResetDefaultDERPMapResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
dp := domain.DERPMap{}
|
||||
|
||||
if err := s.repository.SetDERPMap(ctx, &dp); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
tailnets, err := s.repository.ListTailnets(ctx)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
for _, t := range tailnets {
|
||||
s.sessionManager.NotifyAll(t.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.ResetDefaultDERPMapResponse{}), nil
|
||||
}
|
||||
|
||||
+43
-26
@@ -2,10 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
@@ -14,28 +12,19 @@ import (
|
||||
func (s *Service) GetDNSConfig(ctx context.Context, req *connect.Request[api.GetDNSConfigRequest]) (*connect.Response[api.GetDNSConfigResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
dnsConfig := tailnet.DNSConfig
|
||||
tailnetDomain := domain.SanitizeTailnetName(tailnet.Name)
|
||||
|
||||
resp := &api.GetDNSConfigResponse{
|
||||
Config: &api.DNSConfig{
|
||||
MagicDns: dnsConfig.MagicDNS,
|
||||
MagicDnsSuffix: fmt.Sprintf("%s.%s", tailnetDomain, config.MagicDNSSuffix()),
|
||||
OverrideLocalDns: dnsConfig.OverrideLocalDNS,
|
||||
Nameservers: dnsConfig.Nameservers,
|
||||
Routes: domainRoutesToApiRoutes(dnsConfig.Routes),
|
||||
},
|
||||
Config: domainDNSConfigToApiDNSConfig(tailnet),
|
||||
}
|
||||
|
||||
return connect.NewResponse(resp), nil
|
||||
@@ -44,35 +33,36 @@ func (s *Service) GetDNSConfig(ctx context.Context, req *connect.Request[api.Get
|
||||
func (s *Service) SetDNSConfig(ctx context.Context, req *connect.Request[api.SetDNSConfigRequest]) (*connect.Response[api.SetDNSConfigResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
dnsConfig := req.Msg.Config
|
||||
|
||||
if dnsConfig.MagicDns && len(dnsConfig.Nameservers) == 0 {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("at least one global nameserver is required when enabling magic dns"))
|
||||
if dnsConfig.HttpsCerts && !dnsConfig.MagicDns {
|
||||
return nil, connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("MagicDNS must be enabled when enabling HTTPS Certs"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
tailnet.DNSConfig = domain.DNSConfig{
|
||||
MagicDNS: dnsConfig.MagicDns,
|
||||
OverrideLocalDNS: dnsConfig.OverrideLocalDns,
|
||||
Nameservers: dnsConfig.Nameservers,
|
||||
Routes: apiRoutesToDomainRoutes(dnsConfig.Routes),
|
||||
MagicDNS: dnsConfig.MagicDns,
|
||||
HttpsCertsEnabled: dnsConfig.HttpsCerts,
|
||||
OverrideLocalDNS: dnsConfig.OverrideLocalDns,
|
||||
Nameservers: dnsConfig.Nameservers,
|
||||
Routes: apiRoutesToDomainRoutes(dnsConfig.Routes),
|
||||
}
|
||||
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(tailnet.ID, &broker.Signal{DNSUpdated: true})
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
|
||||
resp := &api.SetDNSConfigResponse{Config: dnsConfig}
|
||||
|
||||
@@ -94,3 +84,30 @@ func apiRoutesToDomainRoutes(routes map[string]*api.Routes) map[string][]string
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func apiDNSConfigToDomainDNSConfig(dnsConfig *api.DNSConfig) domain.DNSConfig {
|
||||
if dnsConfig == nil {
|
||||
return domain.DNSConfig{}
|
||||
}
|
||||
|
||||
return domain.DNSConfig{
|
||||
MagicDNS: dnsConfig.MagicDns,
|
||||
HttpsCertsEnabled: dnsConfig.HttpsCerts,
|
||||
OverrideLocalDNS: dnsConfig.OverrideLocalDns,
|
||||
Nameservers: dnsConfig.Nameservers,
|
||||
Routes: apiRoutesToDomainRoutes(dnsConfig.Routes),
|
||||
}
|
||||
}
|
||||
|
||||
func domainDNSConfigToApiDNSConfig(tailnet *domain.Tailnet) *api.DNSConfig {
|
||||
tailnetDomain := domain.SanitizeTailnetName(tailnet.Name)
|
||||
dnsConfig := tailnet.DNSConfig
|
||||
return &api.DNSConfig{
|
||||
MagicDns: dnsConfig.MagicDNS,
|
||||
HttpsCerts: dnsConfig.HttpsCertsEnabled,
|
||||
MagicDnsSuffix: fmt.Sprintf("%s.%s", tailnetDomain, config.MagicDNSSuffix()),
|
||||
OverrideLocalDns: dnsConfig.OverrideLocalDNS,
|
||||
Nameservers: dnsConfig.Nameservers,
|
||||
Routes: domainRoutesToApiRoutes(dnsConfig.Routes),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
@@ -12,12 +11,12 @@ import (
|
||||
func (s *Service) GetIAMPolicy(ctx context.Context, req *connect.Request[api.GetIAMPolicyRequest]) (*connect.Response[api.GetIAMPolicyResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist"))
|
||||
@@ -36,12 +35,12 @@ func (s *Service) GetIAMPolicy(ctx context.Context, req *connect.Request[api.Get
|
||||
func (s *Service) SetIAMPolicy(ctx context.Context, req *connect.Request[api.SetIAMPolicyRequest]) (*connect.Response[api.SetIAMPolicyResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist"))
|
||||
@@ -55,7 +54,7 @@ func (s *Service) SetIAMPolicy(ctx context.Context, req *connect.Request[api.Set
|
||||
}
|
||||
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.SetIAMPolicyResponse{}), nil
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/key"
|
||||
"github.com/jsiebens/ionscale/internal/token"
|
||||
"go.uber.org/zap"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -75,3 +76,48 @@ func exchangeToken(ctx context.Context, systemAdminKey *key.ServerPrivate, repos
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewErrorInterceptor() *ErrorInterceptor {
|
||||
return &ErrorInterceptor{}
|
||||
}
|
||||
|
||||
type ErrorInterceptor struct {
|
||||
}
|
||||
|
||||
func (e *ErrorInterceptor) handleError(err error) error {
|
||||
if err == nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch err.(type) {
|
||||
case *connect.Error:
|
||||
return err
|
||||
default:
|
||||
return connect.NewError(connect.CodeInternal, fmt.Errorf("internal server error"))
|
||||
}
|
||||
}
|
||||
|
||||
func (e *ErrorInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
|
||||
return func(ctx context.Context, request connect.AnyRequest) (connect.AnyResponse, error) {
|
||||
response, err := next(ctx, request)
|
||||
return response, e.handleError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *ErrorInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
|
||||
return func(ctx context.Context, spec connect.Spec) connect.StreamingClientConn {
|
||||
return next(ctx, spec)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *ErrorInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
|
||||
return func(ctx context.Context, conn connect.StreamingHandlerConn) error {
|
||||
err := next(ctx, conn)
|
||||
return e.handleError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func logError(err error) error {
|
||||
zap.L().WithOptions(zap.AddCallerSkip(1)).Error("error processing request", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
+134
-70
@@ -2,11 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
@@ -22,10 +19,9 @@ func (s *Service) machineToApi(m *domain.Machine) *api.Machine {
|
||||
name = fmt.Sprintf("%s-%d", m.Name, m.NameIdx)
|
||||
}
|
||||
|
||||
online := false
|
||||
online := s.sessionManager.HasSession(m.TailnetID, m.ID)
|
||||
if m.LastSeen != nil {
|
||||
lastSeen = timestamppb.New(*m.LastSeen)
|
||||
online = m.LastSeen.After(time.Now().Add(-config.KeepAliveInterval()))
|
||||
}
|
||||
|
||||
return &api.Machine{
|
||||
@@ -57,26 +53,27 @@ func (s *Service) machineToApi(m *domain.Machine) *api.Machine {
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
Authorized: m.Authorized,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) ListMachines(ctx context.Context, req *connect.Request[api.ListMachinesRequest]) (*connect.Response[api.ListMachinesResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
machines, err := s.repository.ListMachineByTailnet(ctx, tailnet.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
response := &api.ListMachinesResponse{}
|
||||
@@ -92,15 +89,15 @@ func (s *Service) GetMachine(ctx context.Context, req *connect.Request[api.GetMa
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.GetMachineResponse{Machine: s.machineToApi(m)}), nil
|
||||
@@ -111,22 +108,22 @@ func (s *Service) DeleteMachine(ctx context.Context, req *connect.Request[api.De
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if _, err := s.repository.DeleteMachine(ctx, req.Msg.MachineId); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeersRemoved: []uint64{m.ID}})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return connect.NewResponse(&api.DeleteMachineResponse{}), nil
|
||||
}
|
||||
@@ -136,15 +133,15 @@ func (s *Service) ExpireMachine(ctx context.Context, req *connect.Request[api.Ex
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
timestamp := time.Unix(123, 0)
|
||||
@@ -152,23 +149,40 @@ func (s *Service) ExpireMachine(ctx context.Context, req *connect.Request[api.Ex
|
||||
m.KeyExpiryDisabled = false
|
||||
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return connect.NewResponse(&api.ExpireMachineResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) createMachineRoutesResponse(m *domain.Machine) (*connect.Response[api.GetMachineRoutesResponse], error) {
|
||||
response := api.GetMachineRoutesResponse{
|
||||
AdvertisedRoutes: m.AdvertisedPrefixes(),
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
func (s *Service) AuthorizeMachine(ctx context.Context, req *connect.Request[api.AuthorizeMachineRequest]) (*connect.Response[api.AuthorizeMachineResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&response), nil
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if !m.Authorized {
|
||||
m.Authorized = true
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return connect.NewResponse(&api.AuthorizeMachineResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) GetMachineRoutes(ctx context.Context, req *connect.Request[api.GetMachineRoutesRequest]) (*connect.Response[api.GetMachineRoutesResponse], error) {
|
||||
@@ -176,34 +190,44 @@ func (s *Service) GetMachineRoutes(ctx context.Context, req *connect.Request[api
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
return s.createMachineRoutesResponse(m)
|
||||
response := api.GetMachineRoutesResponse{
|
||||
MachineId: m.ID,
|
||||
Routes: &api.MachineRoutes{
|
||||
AdvertisedRoutes: m.AdvertisedPrefixes(),
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
},
|
||||
}
|
||||
|
||||
return connect.NewResponse(&response), nil
|
||||
}
|
||||
|
||||
func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[api.EnableMachineRoutesRequest]) (*connect.Response[api.GetMachineRoutesResponse], error) {
|
||||
func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[api.EnableMachineRoutesRequest]) (*connect.Response[api.EnableMachineRoutesResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
var allowIPs = domain.NewAllowIPsSet(m.AllowIPs)
|
||||
@@ -217,7 +241,7 @@ func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[
|
||||
for _, r := range req.Msg.Routes {
|
||||
prefix, err := netip.ParsePrefix(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
allowIPs.Add(prefix)
|
||||
}
|
||||
@@ -225,28 +249,38 @@ func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[
|
||||
m.AllowIPs = allowIPs.Items()
|
||||
m.AutoAllowIPs = autoAllowIPs.Items()
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return s.createMachineRoutesResponse(m)
|
||||
response := api.EnableMachineRoutesResponse{
|
||||
MachineId: m.ID,
|
||||
Routes: &api.MachineRoutes{
|
||||
AdvertisedRoutes: m.AdvertisedPrefixes(),
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
},
|
||||
}
|
||||
|
||||
return connect.NewResponse(&response), nil
|
||||
}
|
||||
|
||||
func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request[api.DisableMachineRoutesRequest]) (*connect.Response[api.GetMachineRoutesResponse], error) {
|
||||
func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request[api.DisableMachineRoutesRequest]) (*connect.Response[api.DisableMachineRoutesResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
allowIPs := domain.NewAllowIPsSet(m.AllowIPs)
|
||||
@@ -255,7 +289,7 @@ func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request
|
||||
for _, r := range req.Msg.Routes {
|
||||
prefix, err := netip.ParsePrefix(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
allowIPs.Remove(prefix)
|
||||
autoAllowIPs.Remove(prefix)
|
||||
@@ -264,32 +298,42 @@ func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request
|
||||
m.AllowIPs = allowIPs.Items()
|
||||
m.AutoAllowIPs = autoAllowIPs.Items()
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return s.createMachineRoutesResponse(m)
|
||||
response := api.DisableMachineRoutesResponse{
|
||||
MachineId: m.ID,
|
||||
Routes: &api.MachineRoutes{
|
||||
AdvertisedRoutes: m.AdvertisedPrefixes(),
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
},
|
||||
}
|
||||
|
||||
return connect.NewResponse(&response), nil
|
||||
}
|
||||
|
||||
func (s *Service) EnableExitNode(ctx context.Context, req *connect.Request[api.EnableExitNodeRequest]) (*connect.Response[api.GetMachineRoutesResponse], error) {
|
||||
func (s *Service) EnableExitNode(ctx context.Context, req *connect.Request[api.EnableExitNodeRequest]) (*connect.Response[api.EnableExitNodeResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if !m.IsAdvertisedExitNode() {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("machine is not a valid exit node"))
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("machine is not a valid exit node"))
|
||||
}
|
||||
|
||||
prefix4 := netip.MustParsePrefix("0.0.0.0/0")
|
||||
@@ -301,32 +345,42 @@ func (s *Service) EnableExitNode(ctx context.Context, req *connect.Request[api.E
|
||||
m.AllowIPs = allowIPs.Items()
|
||||
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return s.createMachineRoutesResponse(m)
|
||||
response := api.EnableExitNodeResponse{
|
||||
MachineId: m.ID,
|
||||
Routes: &api.MachineRoutes{
|
||||
AdvertisedRoutes: m.AdvertisedPrefixes(),
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
},
|
||||
}
|
||||
|
||||
return connect.NewResponse(&response), nil
|
||||
}
|
||||
|
||||
func (s *Service) DisableExitNode(ctx context.Context, req *connect.Request[api.DisableExitNodeRequest]) (*connect.Response[api.GetMachineRoutesResponse], error) {
|
||||
func (s *Service) DisableExitNode(ctx context.Context, req *connect.Request[api.DisableExitNodeRequest]) (*connect.Response[api.DisableExitNodeResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if !m.IsAdvertisedExitNode() {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("machine is not a valid exit node"))
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("machine is not a valid exit node"))
|
||||
}
|
||||
|
||||
prefix4 := netip.MustParsePrefix("0.0.0.0/0")
|
||||
@@ -342,12 +396,22 @@ func (s *Service) DisableExitNode(ctx context.Context, req *connect.Request[api.
|
||||
m.AutoAllowIPs = autoAllowIPs.Items()
|
||||
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return s.createMachineRoutesResponse(m)
|
||||
response := api.DisableExitNodeResponse{
|
||||
MachineId: m.ID,
|
||||
Routes: &api.MachineRoutes{
|
||||
AdvertisedRoutes: m.AdvertisedPrefixes(),
|
||||
EnabledRoutes: m.AllowedPrefixes(),
|
||||
AdvertisedExitNode: m.IsAdvertisedExitNode(),
|
||||
EnabledExitNode: m.IsAllowedExitNode(),
|
||||
},
|
||||
}
|
||||
|
||||
return connect.NewResponse(&response), nil
|
||||
}
|
||||
|
||||
func (s *Service) SetMachineKeyExpiry(ctx context.Context, req *connect.Request[api.SetMachineKeyExpiryRequest]) (*connect.Response[api.SetMachineKeyExpiryResponse], error) {
|
||||
@@ -355,24 +419,24 @@ func (s *Service) SetMachineKeyExpiry(ctx context.Context, req *connect.Request[
|
||||
|
||||
m, err := s.repository.GetMachine(ctx, req.Msg.MachineId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if m == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("machine not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("machine not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(m.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
m.KeyExpiryDisabled = req.Msg.Disabled
|
||||
|
||||
if err := s.repository.SaveMachine(ctx, m); err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(m.TailnetID, &broker.Signal{PeerUpdated: &m.ID})
|
||||
s.sessionManager.NotifyAll(m.TailnetID)
|
||||
|
||||
return connect.NewResponse(&api.SetMachineKeyExpiryResponse{}), nil
|
||||
}
|
||||
|
||||
+11
-11
@@ -3,28 +3,28 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/auth"
|
||||
"github.com/jsiebens/ionscale/internal/config"
|
||||
"github.com/jsiebens/ionscale/internal/core"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/provider"
|
||||
"github.com/jsiebens/ionscale/internal/version"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
)
|
||||
|
||||
func NewService(config *config.Config, authProvider provider.AuthProvider, repository domain.Repository, pubsub broker.Pubsub) *Service {
|
||||
func NewService(config *config.Config, authProvider auth.Provider, repository domain.Repository, sessionManager core.PollMapSessionManager) *Service {
|
||||
return &Service{
|
||||
config: config,
|
||||
authProvider: authProvider,
|
||||
repository: repository,
|
||||
pubsub: pubsub,
|
||||
config: config,
|
||||
authProvider: authProvider,
|
||||
repository: repository,
|
||||
sessionManager: sessionManager,
|
||||
}
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
config *config.Config
|
||||
authProvider provider.AuthProvider
|
||||
repository domain.Repository
|
||||
pubsub broker.Pubsub
|
||||
config *config.Config
|
||||
authProvider auth.Provider
|
||||
repository domain.Repository
|
||||
sessionManager core.PollMapSessionManager
|
||||
}
|
||||
|
||||
func (s *Service) GetVersion(_ context.Context, _ *connect.Request[api.GetVersionRequest]) (*connect.Response[api.GetVersionResponse], error) {
|
||||
|
||||
+425
-32
@@ -2,41 +2,138 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
"github.com/jsiebens/ionscale/internal/mapping"
|
||||
"github.com/jsiebens/ionscale/internal/util"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
func domainTailnetToApiTailnet(tailnet *domain.Tailnet) (*api.Tailnet, error) {
|
||||
t := &api.Tailnet{
|
||||
Id: tailnet.ID,
|
||||
Name: tailnet.Name,
|
||||
IamPolicy: new(api.IAMPolicy),
|
||||
AclPolicy: new(api.ACLPolicy),
|
||||
DnsConfig: domainDNSConfigToApiDNSConfig(tailnet),
|
||||
ServiceCollectionEnabled: tailnet.ServiceCollectionEnabled,
|
||||
FileSharingEnabled: tailnet.FileSharingEnabled,
|
||||
SshEnabled: tailnet.SSHEnabled,
|
||||
MachineAuthorizationEnabled: tailnet.MachineAuthorizationEnabled,
|
||||
}
|
||||
|
||||
if err := mapping.CopyViaJson(tailnet.IAMPolicy, t.IamPolicy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := mapping.CopyViaJson(tailnet.ACLPolicy, t.AclPolicy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateTailnet(ctx context.Context, req *connect.Request[api.CreateTailnetRequest]) (*connect.Response[api.CreateTailnetResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
name := req.Msg.Name
|
||||
iamPolicy := domain.IAMPolicy{
|
||||
Subs: req.Msg.IamPolicy.Subs,
|
||||
Emails: req.Msg.IamPolicy.Emails,
|
||||
Filters: req.Msg.IamPolicy.Filters,
|
||||
Roles: apiRolesMapToDomainRolesMap(req.Msg.IamPolicy.Roles),
|
||||
tailnet := &domain.Tailnet{
|
||||
ID: util.NextID(),
|
||||
Name: req.Msg.Name,
|
||||
IAMPolicy: domain.IAMPolicy{},
|
||||
ACLPolicy: domain.ACLPolicy{},
|
||||
DNSConfig: apiDNSConfigToDomainDNSConfig(req.Msg.DnsConfig),
|
||||
ServiceCollectionEnabled: req.Msg.ServiceCollectionEnabled,
|
||||
FileSharingEnabled: req.Msg.FileSharingEnabled,
|
||||
SSHEnabled: req.Msg.SshEnabled,
|
||||
MachineAuthorizationEnabled: req.Msg.MachineAuthorizationEnabled,
|
||||
}
|
||||
|
||||
tailnet, created, err := s.repository.GetOrCreateTailnet(ctx, name, iamPolicy)
|
||||
if req.Msg.IamPolicy != nil {
|
||||
if err := mapping.CopyViaJson(req.Msg.IamPolicy, &tailnet.IAMPolicy); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
} else {
|
||||
tailnet.IAMPolicy = domain.DefaultIAMPolicy()
|
||||
}
|
||||
|
||||
if req.Msg.AclPolicy != nil {
|
||||
if err := mapping.CopyViaJson(req.Msg.AclPolicy, &tailnet.ACLPolicy); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
} else {
|
||||
tailnet.ACLPolicy = domain.DefaultACLPolicy()
|
||||
}
|
||||
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
t, err := domainTailnetToApiTailnet(tailnet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if !created {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("tailnet already exists"))
|
||||
resp := &api.CreateTailnetResponse{Tailnet: t}
|
||||
|
||||
return connect.NewResponse(resp), nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateTailnet(ctx context.Context, req *connect.Request[api.UpdateTailnetRequest]) (*connect.Response[api.UpdateTailnetResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
resp := &api.CreateTailnetResponse{Tailnet: &api.Tailnet{
|
||||
Id: tailnet.ID,
|
||||
Name: tailnet.Name,
|
||||
}}
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if req.Msg.IamPolicy != nil {
|
||||
tailnet.IAMPolicy = domain.IAMPolicy{}
|
||||
if err := mapping.CopyViaJson(req.Msg.IamPolicy, &tailnet.IAMPolicy); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if req.Msg.AclPolicy != nil {
|
||||
tailnet.ACLPolicy = domain.ACLPolicy{}
|
||||
if err := mapping.CopyViaJson(req.Msg.AclPolicy, &tailnet.ACLPolicy); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if req.Msg.DnsConfig != nil {
|
||||
tailnet.DNSConfig = apiDNSConfigToDomainDNSConfig(req.Msg.DnsConfig)
|
||||
}
|
||||
|
||||
tailnet.ServiceCollectionEnabled = req.Msg.ServiceCollectionEnabled
|
||||
tailnet.FileSharingEnabled = req.Msg.FileSharingEnabled
|
||||
tailnet.SSHEnabled = req.Msg.SshEnabled
|
||||
tailnet.MachineAuthorizationEnabled = req.Msg.MachineAuthorizationEnabled
|
||||
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
|
||||
t, err := domainTailnetToApiTailnet(tailnet)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
resp := &api.UpdateTailnetResponse{Tailnet: t}
|
||||
|
||||
return connect.NewResponse(resp), nil
|
||||
}
|
||||
@@ -44,33 +141,35 @@ func (s *Service) CreateTailnet(ctx context.Context, req *connect.Request[api.Cr
|
||||
func (s *Service) GetTailnet(ctx context.Context, req *connect.Request[api.GetTailnetRequest]) (*connect.Response[api.GetTailnetResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.Id) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.GetTailnetResponse{Tailnet: &api.Tailnet{
|
||||
Id: tailnet.ID,
|
||||
Name: tailnet.Name,
|
||||
}}), nil
|
||||
t, err := domainTailnetToApiTailnet(tailnet)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.GetTailnetResponse{Tailnet: t}), nil
|
||||
}
|
||||
|
||||
func (s *Service) ListTailnets(ctx context.Context, req *connect.Request[api.ListTailnetRequest]) (*connect.Response[api.ListTailnetResponse], error) {
|
||||
func (s *Service) ListTailnets(ctx context.Context, req *connect.Request[api.ListTailnetsRequest]) (*connect.Response[api.ListTailnetsResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
resp := &api.ListTailnetResponse{}
|
||||
resp := &api.ListTailnetsResponse{}
|
||||
|
||||
if principal.IsSystemAdmin() {
|
||||
tailnets, err := s.repository.ListTailnets(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
for _, t := range tailnets {
|
||||
gt := api.Tailnet{Id: t.ID, Name: t.Name}
|
||||
@@ -81,7 +180,7 @@ func (s *Service) ListTailnets(ctx context.Context, req *connect.Request[api.Lis
|
||||
if principal.User != nil {
|
||||
tailnet, err := s.repository.GetTailnet(ctx, principal.User.TailnetID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
gt := api.Tailnet{Id: tailnet.ID, Name: tailnet.Name}
|
||||
resp.Tailnet = append(resp.Tailnet, >)
|
||||
@@ -93,12 +192,12 @@ func (s *Service) ListTailnets(ctx context.Context, req *connect.Request[api.Lis
|
||||
func (s *Service) DeleteTailnet(ctx context.Context, req *connect.Request[api.DeleteTailnetRequest]) (*connect.Response[api.DeleteTailnetResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
count, err := s.repository.CountMachineByTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if !req.Msg.Force && count > 0 {
|
||||
@@ -130,10 +229,304 @@ func (s *Service) DeleteTailnet(ctx context.Context, req *connect.Request[api.De
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(req.Msg.TailnetId, &broker.Signal{})
|
||||
s.sessionManager.NotifyAll(req.Msg.TailnetId)
|
||||
|
||||
return connect.NewResponse(&api.DeleteTailnetResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) SetDERPMap(ctx context.Context, req *connect.Request[api.SetDERPMapRequest]) (*connect.Response[api.SetDERPMapResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
derpMap := tailcfg.DERPMap{}
|
||||
if err := json.Unmarshal(req.Msg.Value, &derpMap); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
tailnet.DERPMap = domain.DERPMap{
|
||||
Checksum: util.Checksum(&derpMap),
|
||||
DERPMap: derpMap,
|
||||
}
|
||||
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
|
||||
raw, err := json.Marshal(derpMap)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.SetDERPMapResponse{Value: raw}), nil
|
||||
}
|
||||
|
||||
func (s *Service) ResetDERPMap(ctx context.Context, req *connect.Request[api.ResetDERPMapRequest]) (*connect.Response[api.ResetDERPMapResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
tailnet.DERPMap = domain.DERPMap{}
|
||||
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
|
||||
return connect.NewResponse(&api.ResetDERPMapResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) GetDERPMap(ctx context.Context, req *connect.Request[api.GetDERPMapRequest]) (*connect.Response[api.GetDERPMapResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
derpMap, err := tailnet.GetDERPMap(ctx, s.repository)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(derpMap.DERPMap)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.GetDERPMapResponse{Value: raw}), nil
|
||||
}
|
||||
|
||||
func (s *Service) EnableFileSharing(ctx context.Context, req *connect.Request[api.EnableFileSharingRequest]) (*connect.Response[api.EnableFileSharingResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if !tailnet.FileSharingEnabled {
|
||||
tailnet.FileSharingEnabled = true
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.EnableFileSharingResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) DisableFileSharing(ctx context.Context, req *connect.Request[api.DisableFileSharingRequest]) (*connect.Response[api.DisableFileSharingResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if tailnet.FileSharingEnabled {
|
||||
tailnet.FileSharingEnabled = false
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.DisableFileSharingResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) EnableServiceCollection(ctx context.Context, req *connect.Request[api.EnableServiceCollectionRequest]) (*connect.Response[api.EnableServiceCollectionResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if !tailnet.ServiceCollectionEnabled {
|
||||
tailnet.ServiceCollectionEnabled = true
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.EnableServiceCollectionResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) DisableServiceCollection(ctx context.Context, req *connect.Request[api.DisableServiceCollectionRequest]) (*connect.Response[api.DisableServiceCollectionResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if tailnet.ServiceCollectionEnabled {
|
||||
tailnet.ServiceCollectionEnabled = false
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.DisableServiceCollectionResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) EnableSSH(ctx context.Context, req *connect.Request[api.EnableSSHRequest]) (*connect.Response[api.EnableSSHResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if !tailnet.SSHEnabled {
|
||||
tailnet.SSHEnabled = true
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.EnableSSHResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) DisableSSH(ctx context.Context, req *connect.Request[api.DisableSSHRequest]) (*connect.Response[api.DisableSSHResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if tailnet.SSHEnabled {
|
||||
tailnet.SSHEnabled = false
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.sessionManager.NotifyAll(tailnet.ID)
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.DisableSSHResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) EnableMachineAuthorization(ctx context.Context, req *connect.Request[api.EnableMachineAuthorizationRequest]) (*connect.Response[api.EnableMachineAuthorizationResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if !tailnet.MachineAuthorizationEnabled {
|
||||
tailnet.MachineAuthorizationEnabled = true
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.EnableMachineAuthorizationResponse{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) DisableMachineAuthorization(ctx context.Context, req *connect.Request[api.DisableMachineAuthorizationRequest]) (*connect.Response[api.DisableMachineAuthorizationResponse], error) {
|
||||
principal := CurrentPrincipal(ctx)
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(req.Msg.TailnetId) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if tailnet.MachineAuthorizationEnabled {
|
||||
tailnet.MachineAuthorizationEnabled = false
|
||||
if err := s.repository.SaveTailnet(ctx, tailnet); err != nil {
|
||||
return nil, logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return connect.NewResponse(&api.DisableMachineAuthorizationResponse{}), nil
|
||||
}
|
||||
|
||||
+15
-12
@@ -2,9 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/bufbuild/connect-go"
|
||||
"github.com/jsiebens/ionscale/internal/broker"
|
||||
"github.com/jsiebens/ionscale/internal/domain"
|
||||
api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1"
|
||||
)
|
||||
@@ -14,20 +13,20 @@ func (s *Service) ListUsers(ctx context.Context, req *connect.Request[api.ListUs
|
||||
|
||||
tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if tailnet == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("tailnet not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(tailnet.ID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
users, err := s.repository.ListUsers(ctx, tailnet.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
resp := &api.ListUsersResponse{}
|
||||
@@ -46,20 +45,24 @@ func (s *Service) DeleteUser(ctx context.Context, req *connect.Request[api.Delet
|
||||
principal := CurrentPrincipal(ctx)
|
||||
|
||||
if !principal.IsSystemAdmin() && principal.UserMatches(req.Msg.UserId) {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("unable delete yourself"))
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("unable to delete yourself"))
|
||||
}
|
||||
|
||||
user, err := s.repository.GetUser(ctx, req.Msg.UserId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
return nil, connect.NewError(connect.CodeNotFound, errors.New("user not found"))
|
||||
return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("user not found"))
|
||||
}
|
||||
|
||||
if !principal.IsSystemAdmin() && !principal.IsTailnetAdmin(user.TailnetID) {
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("permission denied"))
|
||||
return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
|
||||
}
|
||||
|
||||
if user.UserType == domain.UserTypeService {
|
||||
return nil, connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("unable delete service account"))
|
||||
}
|
||||
|
||||
err = s.repository.Transaction(func(tx domain.Repository) error {
|
||||
@@ -83,10 +86,10 @@ func (s *Service) DeleteUser(ctx context.Context, req *connect.Request[api.Delet
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, logError(err)
|
||||
}
|
||||
|
||||
s.pubsub.Publish(user.TailnetID, &broker.Signal{})
|
||||
s.sessionManager.NotifyAll(user.TailnetID)
|
||||
|
||||
return connect.NewResponse(&api.DeleteUserResponse{}), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Poppins', sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
padding: 10px;
|
||||
background: #379683;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
background: #fff;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
margin: 120px auto;
|
||||
padding: 25px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.selectionList li {
|
||||
position: relative;
|
||||
list-style: none;
|
||||
height: 45px;
|
||||
line-height: 45px;
|
||||
margin-bottom: 8px;
|
||||
background: #f2f2f2;
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.selectionList li button {
|
||||
margin: 0;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
}
|
||||
</style>
|
||||
<title>ionscale</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<div style="text-align: center">
|
||||
<p><b>Authentication successful</b></p>
|
||||
<small>but this is a <b style="color: blue">new machine</b> and needs to be authorized by your Tailnet admin.</small>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,63 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Poppins', sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
padding: 10px;
|
||||
background: #379683;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
background: #fff;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
margin: 120px auto;
|
||||
padding: 25px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.selectionList li {
|
||||
position: relative;
|
||||
list-style: none;
|
||||
height: 45px;
|
||||
line-height: 45px;
|
||||
margin-bottom: 8px;
|
||||
background: #f2f2f2;
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.selectionList li button {
|
||||
margin: 0;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
}
|
||||
</style>
|
||||
<title>ionscale</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<div style="text-align: center">
|
||||
<p><b>Authentication successful</b></p>
|
||||
<small>but you're <b style="color: red">not</b> a valid owner of the machine</small>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+37
-13
@@ -1,36 +1,60 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
var entropy *rand.Rand
|
||||
|
||||
func init() {
|
||||
seed := time.Now().UnixNano()
|
||||
source := rand.NewSource(seed)
|
||||
entropy = rand.New(source)
|
||||
}
|
||||
|
||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
func RandStringBytes(n int) string {
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = letterBytes[rand.Intn(len(letterBytes))]
|
||||
idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes))))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
b[i] = letterBytes[idx.Int64()]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func RandUint64(n uint64) uint64 {
|
||||
return entropy.Uint64() % n
|
||||
val, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return val.Uint64()
|
||||
}
|
||||
|
||||
func RandomBytes(size int) ([]byte, error) {
|
||||
buf := make([]byte, size)
|
||||
if _, err := entropy.Read(buf); err != nil {
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func NewPrivateKey() (*rsa.PrivateKey, string, error) {
|
||||
id := RandStringBytes(22)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return privateKey, id, nil
|
||||
}
|
||||
|
||||
func Checksum(v interface{}) string {
|
||||
marshal, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
sum := md5.Sum(marshal)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
serve:
|
||||
docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material
|
||||
@@ -0,0 +1,105 @@
|
||||
# Configuration Reference
|
||||
|
||||
__ionscale__ uses the YAML file format for configuration.
|
||||
A full configuration reference file is shown below, this provides comments and all available options.
|
||||
|
||||
```yaml
|
||||
# The address to bind to for HTTP.
|
||||
http_listen_addr: ":8080"
|
||||
|
||||
# The address to bind to for HTTPS.
|
||||
https_listen_addr: "8443"
|
||||
|
||||
# The address to bind to for the metrics.
|
||||
metrics_listen_addr: ":9091"
|
||||
|
||||
# The public URL at which the ionscale server can be reached by clients and the CLI.
|
||||
server_url: "https://ionscale.example.com"
|
||||
|
||||
tls:
|
||||
# Disable TLS (not recommended)
|
||||
# Use this flag to disable TLS e.g. when running behind a reverse proxy
|
||||
disable: false
|
||||
# Redirect HTTP requests to HTTPS requests
|
||||
force_https: true
|
||||
# The path to the certificate for TLS.
|
||||
# Required when TLS is enabled and ACME disabled
|
||||
cert_file: ""
|
||||
# The path to the private key for the certificate.
|
||||
# Required when TLS is enabled and ACME disabled
|
||||
key_file: ""
|
||||
# Enable automatic TLS certificates provisioning with Let's Encrypt
|
||||
acme: false
|
||||
# An email address, used when creating an ACME account and keeping you up-to-date regarding your certificates
|
||||
acme_email: ""
|
||||
# The URL to the ACME CA's directory.
|
||||
acme_ca: "https://acme-v02.api.letsencrypt.org/directory"
|
||||
# Path to store certificates and metadata needed by ACME
|
||||
acme_path: "./data"
|
||||
|
||||
database:
|
||||
# Type of databas to use, supported values are sqlite or postgres
|
||||
type: "sqlite"
|
||||
# The URL for connecting to the database
|
||||
# e.g
|
||||
# url: "/data/ionscale.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)"
|
||||
# url: "postgres://ionscale:ionscale@localhost/ionscale?sslmode=disable"
|
||||
url: "./ionscale.db"
|
||||
|
||||
keys:
|
||||
# A private, 32 bytes in hex, system admin key
|
||||
# Use this key with the CLI when configuring system-wide resources like tailnets
|
||||
# A key can be generated by:
|
||||
# - ionscale genkey
|
||||
# - openssl rand -hex 32
|
||||
system_admin_key: ""
|
||||
|
||||
poll_net:
|
||||
# Period to send keep alive messages to the connected devices
|
||||
keep_alive_interval: "60s"
|
||||
|
||||
# Optional authentication configuration
|
||||
auth:
|
||||
# OIDC provider configuration
|
||||
provider:
|
||||
# OIDC issuer URL where ionscale can find the OpenID Provider Configuration Document
|
||||
issuer: ""
|
||||
# OIDC client id and secrets
|
||||
client_id: ""
|
||||
client_secret: ""
|
||||
# additional OIDC scopes used in the OIDC flow
|
||||
additional_scopes: ""
|
||||
# IAM policy to mark some authenticated users as System Admin
|
||||
system_admins:
|
||||
# A list of emails of users that are System Admin
|
||||
emails: []
|
||||
# A list of ID (sub OIDC claim) of users that are System Admin
|
||||
subs: []
|
||||
# A list of BEXPR filters to mark authenticated users as System Admin
|
||||
filters: []
|
||||
|
||||
dns:
|
||||
# The base domain of the MagicDNS FQDN hostnames
|
||||
magic_dns_suffix: "ionscale.net"
|
||||
# A DNS provider for setting public TXT records
|
||||
# This is a requirement to enable Tailscale HTTPS certs.
|
||||
provider:
|
||||
# name of your provider, currently supported implementations:
|
||||
# - azure (https://github.com/libdns/azure)
|
||||
# - cloudflare (https://github.com/libdns/cloudflare)
|
||||
# - digitialocean (https://github.com/libdns/digitalocean)
|
||||
# - googleclouddns (https://github.com/libdns/googleclouddns)
|
||||
# - route53 (https://github.com/libdns/route53)
|
||||
name: ""
|
||||
# DNS zone
|
||||
zone: ""
|
||||
# Provider specific configuration
|
||||
config: {}
|
||||
|
||||
logging:
|
||||
# Output formatting for logs: text or json
|
||||
format: "text"
|
||||
level: "info"
|
||||
# Path of a target log file, if omitted logs are written to stdout
|
||||
file: ""
|
||||
```
|
||||
@@ -0,0 +1,72 @@
|
||||
# Getting started with Docker
|
||||
|
||||
You can install and run __ionscale__ using the Docker images published on [GitHub Container Registry](https://github.com/jsiebens/ionscale/pkgs/container/ionscale).
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Linux machine with port 80 and 443 open to ingress traffic.
|
||||
- Docker installed. See the [official installation documentation](https://docs.docker.com/install/)
|
||||
- A registered domain name.
|
||||
|
||||
## Step 1. Configure DNS
|
||||
|
||||
Set up a `A` DNS records: `ionscale.example.com` (We are assuming that your domain name is example.com.)
|
||||
|
||||
!!! tip
|
||||
|
||||
You can use `dig` to make sure that DNS records are propagated:
|
||||
|
||||
``` bash
|
||||
$ dig ionscale.example.com
|
||||
```
|
||||
|
||||
## Step 2. Run ionscale with Docker
|
||||
|
||||
### Configure ionscale
|
||||
|
||||
``` bash
|
||||
mkdir -p ionscale/data
|
||||
cd ./ionscale
|
||||
```
|
||||
|
||||
Generate a configuration file for __ionscale__ with the following commands:
|
||||
|
||||
``` bash
|
||||
export IONSCALE_DOMAIN=example.com
|
||||
export IONSCALE_ACME_EMAIL=<your email>
|
||||
```
|
||||
|
||||
``` bash
|
||||
tee ./config.yaml >/dev/null <<EOF
|
||||
http_listen_addr: ":80"
|
||||
https_listen_addr: ":443"
|
||||
server_url: "https://${IONSCALE_DOMAIN}"
|
||||
|
||||
tls:
|
||||
acme: true
|
||||
acme_email: "${IONSCALE_ACME_EMAIL}"
|
||||
acme_path: "/data/acme"
|
||||
|
||||
keys:
|
||||
system_admin_key: "$(ionscale genkey -n)"
|
||||
|
||||
database:
|
||||
url: "/data/ionscale.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)"
|
||||
|
||||
logging:
|
||||
level: info
|
||||
EOF
|
||||
```
|
||||
|
||||
### Start ionscale
|
||||
|
||||
Run an __ionscale__ instance with the following command:
|
||||
|
||||
``` bash
|
||||
docker run \
|
||||
-v $(pwd)/config.yaml:/etc/ionscale/config.yaml \
|
||||
-v $(pwd)/data:/data \
|
||||
-p 80:80 \
|
||||
-p 443:443 \
|
||||
ghcr.io/jsiebens/ionscale:0.8.2 server --config /etc/ionscale/config.yaml
|
||||
```
|
||||
@@ -0,0 +1,116 @@
|
||||
# Getting started on a Linux Server
|
||||
|
||||
This tutorial will guide you through the steps needed to install and run __ionscale__ on a Linux machine.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A Linux machine with port 80 and 443 open to ingress traffic.
|
||||
- A registered domain name.
|
||||
|
||||
## Step 1. Configure DNS
|
||||
|
||||
Set up a `A` DNS records: `ionscale.example.com` (We are assuming that your domain name is example.com.)
|
||||
|
||||
!!! tip
|
||||
|
||||
You can use `dig` to make sure that DNS records are propagated:
|
||||
|
||||
``` bash
|
||||
$ dig ionscale.example.com
|
||||
```
|
||||
|
||||
## Step 2. Set up ionscale on your Linux host
|
||||
|
||||
### Prepare installation
|
||||
|
||||
Run the following commands to prepare the installation:
|
||||
|
||||
``` bash
|
||||
sudo mkdir -p /etc/ionscale
|
||||
sudo mkdir -p /var/lib/ionscale
|
||||
|
||||
sudo useradd --system --no-create-home --shell /bin/false ionscale
|
||||
sudo chown ionscale:ionscale /etc/ionscale
|
||||
sudo chown ionscale:ionscale /var/lib/ionscale
|
||||
```
|
||||
|
||||
### Install ionscale
|
||||
|
||||
Run the following commands to install the __ionscale__ binary on your Linux host:
|
||||
|
||||
``` bash
|
||||
sudo curl \
|
||||
-o "/usr/local/bin/ionscale" \
|
||||
-sfL "https://github.com/jsiebens/ionscale/releases/download/v0.8.2/ionscale_linux_amd64"
|
||||
|
||||
sudo chmod +x "/usr/local/bin/ionscale"
|
||||
```
|
||||
|
||||
### Configure ionscale
|
||||
|
||||
Generate a system admin key for __ionscale__ using the `ionscale genkey` command and write it the an environment file:
|
||||
|
||||
``` bash
|
||||
sudo tee /etc/default/ionscale >/dev/null <<EOF
|
||||
IONSCALE_KEYS_SYSTEM_ADMIN_KEY=$(ionscale genkey -n)
|
||||
EOF
|
||||
```
|
||||
|
||||
Generate a configuration file for __ionscale__ with the following commands:
|
||||
|
||||
``` bash
|
||||
export IONSCALE_DOMAIN=example.com
|
||||
export IONSCALE_ACME_EMAIL=<your email>
|
||||
```
|
||||
|
||||
``` bash
|
||||
sudo tee /etc/ionscale/config.yaml >/dev/null <<EOF
|
||||
http_listen_addr: ":80"
|
||||
https_listen_addr: ":443"
|
||||
server_url: "https://${IONSCALE_DOMAIN}"
|
||||
|
||||
tls:
|
||||
acme: true
|
||||
acme_email: "${IONSCALE_ACME_EMAIL}"
|
||||
acme_path: "/var/lib/ionscale/acme"
|
||||
|
||||
database:
|
||||
url: "/var/lib/ionscale/ionscale.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)"
|
||||
|
||||
logging:
|
||||
level: info
|
||||
EOF
|
||||
```
|
||||
|
||||
Create a systemd service file for __ionscale__ with the following commands:
|
||||
|
||||
``` bash
|
||||
sudo tee /etc/systemd/system/ionscale.service >/dev/null <<EOF
|
||||
[Unit]
|
||||
Description=ionscale - a Tailscale Controller server
|
||||
Requires=network-online.target
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
EnvironmentFile=/etc/default/ionscale
|
||||
User=ionscale
|
||||
Group=ionscale
|
||||
ExecStart=/usr/local/bin/ionscale server --config /etc/ionscale/config.yaml
|
||||
Restart=on-failure
|
||||
RestartSec=10s
|
||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
```
|
||||
|
||||
### Start ionscale
|
||||
|
||||
On your Linux machine, run the following commands to enable and start the __ionscale__ daemon:
|
||||
|
||||
``` bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable ionscale
|
||||
sudo systemctl start ionscale
|
||||
```
|
||||
@@ -0,0 +1,35 @@
|
||||
# ionscale
|
||||
|
||||
> **Note**:
|
||||
> ionscale is currently beta quality, actively being developed and so subject to changes
|
||||
|
||||
**What is Tailscale?**
|
||||
|
||||
[Tailscale](https://tailscale.com) is a VPN service that makes the devices and applications you own accessible anywhere in the world, securely and effortlessly.
|
||||
It enables encrypted point-to-point connections using the open source [WireGuard](https://www.wireguard.com/) protocol, which means only devices on your private network can communicate with each other.
|
||||
|
||||
**What is ionscale?**
|
||||
|
||||
While the Tailscale software running on each node is open source, their centralized "coordination server" which act as a shared drop box for public keys is not.
|
||||
|
||||
_ionscale_ aims to implement such lightweight, open source alternative Tailscale control server.
|
||||
|
||||
## Features
|
||||
|
||||
- multi [tailnet](https://tailscale.com/kb/1136/tailnet/) support
|
||||
- multi user support
|
||||
- OIDC integration (not required, although recommended)
|
||||
- [Auth keys](https://tailscale.com/kb/1085/auth-keys/)
|
||||
- [Access control list](https://tailscale.com/kb/1018/acls/)
|
||||
- [DNS](https://tailscale.com/kb/1054/dns/)
|
||||
- nameservers
|
||||
- Split DNS
|
||||
- MagicDNS
|
||||
- [HTTPS Certs](https://tailscale.com/kb/1153/enabling-https/)
|
||||
- [Tailscale SSH](https://tailscale.com/kb/1193/tailscale-ssh/)
|
||||
- [Service collection](https://tailscale.com/kb/1100/services/)
|
||||
- [Taildrop](https://tailscale.com/kb/1106/taildrop/)
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This is not an official Tailscale or Tailscale Inc. project.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user