├── .gitignore ├── fixtures ├── tokens_policy_create_empty.json ├── accounts_captcha.json ├── tokens_policy_get.json ├── tokens_policy_update.json ├── tokens_policy_create.json ├── accounts_login.json ├── accounts_retrieve.json ├── tokens_create.json ├── domains_getresponsible.json ├── records_get.json ├── records_create.json ├── records_replace.json ├── records_update.json ├── records_create_bulk.json ├── records_update_bulk.json ├── tokens_policy_get_all.json ├── domains_getall.json ├── domains_get.json ├── domains_create.json ├── tokens_get.json ├── tokens_update.json ├── records_getall.json └── tokens_getall.json ├── Makefile ├── go.mod ├── .github └── workflows │ ├── go-cross.yml │ └── main.yml ├── pagination.go ├── desec_test.go ├── errors.go ├── pagination_test.go ├── .golangci.yml ├── readme.md ├── go.sum ├── account_test.go ├── tokens_test.go ├── desec.go ├── domains_test.go ├── token_policies_test.go ├── token_policies.go ├── domains.go ├── tokens.go ├── records_test.go ├── account.go ├── records.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | -------------------------------------------------------------------------------- /fixtures/tokens_policy_create_empty.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "a563a574-33c9-45d1-9201-e5577b42aaf1", 3 | "domain": null, 4 | "subname": null, 5 | "type": null 6 | } 7 | -------------------------------------------------------------------------------- /fixtures/accounts_captcha.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "aaa", 3 | "challenge": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8zxD3EwAFuwJYQcBz5wAAAABJRU5ErkJggg==" 4 | } -------------------------------------------------------------------------------- /fixtures/tokens_policy_get.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "fa6fdf60-6546-4cee-9168-5d144fe9339c", 3 | "domain": "example.com", 4 | "subname": "testing", 5 | "type": "A", 6 | "perm_write": true 7 | } 8 | -------------------------------------------------------------------------------- /fixtures/tokens_policy_update.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "fa6fdf60-6546-4cee-9168-5d144fe9339c", 3 | "domain": "example.com", 4 | "subname": "testing", 5 | "type": "A", 6 | "perm_write": false 7 | } 8 | -------------------------------------------------------------------------------- /fixtures/tokens_policy_create.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "2f133e8e-56a0-4b19-8e7e-f2e29c7ce263", 3 | "domain": "example.com", 4 | "subname": "testing", 5 | "type": "A", 6 | "perm_write": true 7 | } 8 | -------------------------------------------------------------------------------- /fixtures/accounts_login.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2018-09-06T09:07:43.762697Z", 3 | "id": "8f9cbae2-c862-48a4-b3f0-2cb1a80df168", 4 | "token": "f07Q0TRmEb-CRWPe4h64_iV2jbet", 5 | "name": "login" 6 | } -------------------------------------------------------------------------------- /fixtures/accounts_retrieve.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2019-10-16T18:09:17.715702Z", 3 | "email": "youremailaddress@example.com", 4 | "id": "9ab16e5c-805d-4ab1-9030-af3f5a541d47", 5 | "limit_domains": 5 6 | } -------------------------------------------------------------------------------- /fixtures/tokens_create.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2018-09-06T09:08:43.762697Z", 3 | "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 4 | "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", 5 | "name": "my new token" 6 | } -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: default clean check test 2 | 3 | default: clean check test build 4 | 5 | test: clean 6 | go test -v -cover ./... 7 | 8 | clean: 9 | rm -f cover.out 10 | 11 | build: 12 | go build 13 | 14 | check: 15 | golangci-lint run 16 | -------------------------------------------------------------------------------- /fixtures/domains_getresponsible.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "created": "2022-11-12T18:01:35.454616Z", 4 | "published": "2022-11-12T18:03:19.516440Z", 5 | "touched": "2022-11-12T18:03:19.516440Z", 6 | "name": "dev.example.org", 7 | "minimum_ttl": 3600 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /fixtures/records_get.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2020-05-06T11:46:07.641885Z", 3 | "domain": "example.dedyn.io", 4 | "subname": "_acme-challenge", 5 | "name": "_acme-challenge.example.dedyn.io.", 6 | "records": [ 7 | "\"txt\"" 8 | ], 9 | "ttl": 300, 10 | "type": "TXT", 11 | "touched": "2020-05-06T11:46:07.641885Z" 12 | } 13 | -------------------------------------------------------------------------------- /fixtures/records_create.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2020-05-06T11:46:07.641885Z", 3 | "domain": "example.dedyn.io", 4 | "subname": "_acme-challenge", 5 | "name": "_acme-challenge.example.dedyn.io.", 6 | "records": [ 7 | "\"txt\"" 8 | ], 9 | "ttl": 300, 10 | "type": "TXT", 11 | "touched": "2020-05-06T11:46:07.641885Z" 12 | } 13 | -------------------------------------------------------------------------------- /fixtures/records_replace.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2020-05-06T11:46:07.641885Z", 3 | "domain": "example.dedyn.io", 4 | "subname": "_acme-challenge", 5 | "name": "_acme-challenge.example.dedyn.io.", 6 | "records": [ 7 | "\"updated\"" 8 | ], 9 | "ttl": 300, 10 | "type": "TXT", 11 | "touched": "2020-05-06T11:46:07.641885Z" 12 | } 13 | -------------------------------------------------------------------------------- /fixtures/records_update.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2020-05-06T11:46:07.641885Z", 3 | "domain": "example.dedyn.io", 4 | "subname": "_acme-challenge", 5 | "name": "_acme-challenge.example.dedyn.io.", 6 | "records": [ 7 | "\"updated\"" 8 | ], 9 | "ttl": 300, 10 | "type": "TXT", 11 | "touched": "2020-05-06T11:46:07.641885Z" 12 | } 13 | -------------------------------------------------------------------------------- /fixtures/records_create_bulk.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "created": "2020-05-06T11:46:07.641885Z", 4 | "domain": "example.dedyn.io", 5 | "subname": "_acme-challenge", 6 | "name": "_acme-challenge.example.dedyn.io.", 7 | "records": [ 8 | "\"txt\"" 9 | ], 10 | "ttl": 300, 11 | "type": "TXT", 12 | "touched": "2020-05-06T11:46:07.641885Z" 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /fixtures/records_update_bulk.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "created": "2020-05-06T11:46:07.641885Z", 4 | "domain": "example.dedyn.io", 5 | "subname": "_acme-challenge", 6 | "name": "_acme-challenge.example.dedyn.io.", 7 | "records": [ 8 | "\"updated\"" 9 | ], 10 | "ttl": 300, 11 | "type": "TXT", 12 | "touched": "2020-05-06T11:46:07.641885Z" 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /fixtures/tokens_policy_get_all.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "7aed3f71-bc81-4f7e-90ae-8f0df0d1c211", 4 | "domain": "example.com", 5 | "subname": "testing", 6 | "type": null, 7 | "perm_write": false 8 | }, 9 | { 10 | "id": "fa6fdf60-6546-4cee-9168-5d144fe9339c", 11 | "domain": "example.com", 12 | "subname": "testing", 13 | "type": "A", 14 | "perm_write": true 15 | } 16 | ] 17 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/nrdcg/desec 2 | 3 | go 1.23 4 | 5 | require ( 6 | github.com/hashicorp/go-retryablehttp v0.7.8 7 | github.com/peterhellberg/link v1.2.0 8 | github.com/stretchr/testify v1.11.1 9 | ) 10 | 11 | require ( 12 | github.com/davecgh/go-spew v1.1.1 // indirect 13 | github.com/hashicorp/go-cleanhttp v0.5.2 // indirect 14 | github.com/pmezard/go-difflib v1.0.0 // indirect 15 | gopkg.in/yaml.v3 v3.0.1 // indirect 16 | ) 17 | -------------------------------------------------------------------------------- /fixtures/domains_getall.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "created": "2020-05-13T11:35:40.954616Z", 4 | "touched": "2020-05-13T12:25:19.816440Z", 5 | "published": "2020-05-13T12:25:19.816440Z", 6 | "name": "example.org", 7 | "minimum_ttl": 3600 8 | }, 9 | { 10 | "created": "2020-05-05T23:17:36.101470Z", 11 | "published": "2020-05-06T12:13:06.138443Z", 12 | "touched": "2020-05-06T12:13:06.138443Z", 13 | "name": "example.dedyn.io", 14 | "minimum_ttl": 60 15 | } 16 | ] 17 | -------------------------------------------------------------------------------- /fixtures/domains_get.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2018-09-18T16:36:16.510368Z", 3 | "keys": [ 4 | { 5 | "dnskey": "257 3 13 WFRl60...", 6 | "ds": [ 7 | "6006 13 1 8581e9...", 8 | "6006 13 2 f34b75...", 9 | "6006 13 3 dfb325...", 10 | "6006 13 4 2fdcf8..." 11 | ], 12 | "flags": 257, 13 | "keytype": "csk" 14 | } 15 | ], 16 | "minimum_ttl": 3600, 17 | "name": "example.com", 18 | "published": "2018-09-18T17:21:38.348112Z", 19 | "touched": "2018-09-18T17:21:38.348112Z" 20 | } 21 | -------------------------------------------------------------------------------- /fixtures/domains_create.json: -------------------------------------------------------------------------------- 1 | { 2 | "created": "2018-09-18T16:36:16.510368Z", 3 | "keys": [ 4 | { 5 | "dnskey": "257 3 13 WFRl60...", 6 | "ds": [ 7 | "6006 13 1 8581e9...", 8 | "6006 13 2 f34b75...", 9 | "6006 13 3 dfb325...", 10 | "6006 13 4 2fdcf8..." 11 | ], 12 | "flags": 257, 13 | "keytype": "csk" 14 | } 15 | ], 16 | "minimum_ttl": 3600, 17 | "name": "example.com", 18 | "published": "2018-09-18T17:21:38.348112Z", 19 | "touched": "2018-09-18T17:21:38.348112Z" 20 | } 21 | -------------------------------------------------------------------------------- /fixtures/tokens_get.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 3 | "created": "2018-09-06T09:08:43.762697Z", 4 | "last_used": null, 5 | "owner": "youremailaddress@example.com", 6 | "user_override": null, 7 | "max_age": "365 00:00:00", 8 | "max_unused_period": null, 9 | "name": "my new token", 10 | "perm_create_domain": false, 11 | "perm_delete_domain": false, 12 | "perm_manage_tokens": false, 13 | "allowed_subnets": [ 14 | "0.0.0.0/0", 15 | "::/0" 16 | ], 17 | "auto_policy": false, 18 | "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S" 19 | } 20 | -------------------------------------------------------------------------------- /fixtures/tokens_update.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 3 | "created": "2018-09-06T09:08:43.762697Z", 4 | "last_used": null, 5 | "owner": "youremailaddress@example.com", 6 | "user_override": null, 7 | "max_age": "365 00:00:00", 8 | "max_unused_period": null, 9 | "name": "my new token", 10 | "perm_create_domain": true, 11 | "perm_delete_domain": false, 12 | "perm_manage_tokens": true, 13 | "allowed_subnets": [ 14 | "0.0.0.0/0", 15 | "::/0" 16 | ], 17 | "auto_policy": false, 18 | "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S" 19 | } 20 | -------------------------------------------------------------------------------- /fixtures/records_getall.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "created": "2020-05-06T11:46:07.641885Z", 4 | "domain": "example.dedyn.io", 5 | "subname": "", 6 | "name": "example.dedyn.io.", 7 | "records": [ 8 | "10.10.10.10" 9 | ], 10 | "ttl": 60, 11 | "type": "A", 12 | "touched": "2020-05-06T11:46:07.641885Z" 13 | }, 14 | { 15 | "created": "2020-05-06T11:46:07.641885Z", 16 | "domain": "example.dedyn.io", 17 | "subname": "", 18 | "name": "example.dedyn.io.", 19 | "records": [ 20 | "ns1.desec.io.", 21 | "ns2.desec.org." 22 | ], 23 | "ttl": 3600, 24 | "type": "NS", 25 | "touched": "2020-05-06T11:46:07.641885Z" 26 | } 27 | ] 28 | -------------------------------------------------------------------------------- /.github/workflows/go-cross.yml: -------------------------------------------------------------------------------- 1 | name: Go Matrix 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | 13 | cross: 14 | name: Go 15 | runs-on: ${{ matrix.os }} 16 | env: 17 | CGO_ENABLED: 0 18 | 19 | strategy: 20 | matrix: 21 | go-version: [ oldstable, stable] 22 | os: [ubuntu-latest, macos-latest, windows-latest] 23 | 24 | steps: 25 | - uses: actions/checkout@v5 26 | - uses: actions/setup-go@v6 27 | with: 28 | go-version: ${{ matrix.go-version }} 29 | 30 | - name: Test 31 | run: go test -v -cover ./... 32 | 33 | - name: Build 34 | run: go build -v -ldflags "-s -w" -trimpath 35 | -------------------------------------------------------------------------------- /pagination.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "net/http" 5 | "net/url" 6 | 7 | "github.com/peterhellberg/link" 8 | ) 9 | 10 | // Cursors allows to retrieve the next (or previous) page. 11 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#pagination 12 | type Cursors struct { 13 | First string 14 | Prev string 15 | Next string 16 | } 17 | 18 | func parseCursor(h http.Header) (*Cursors, error) { 19 | links := link.ParseHeader(h) 20 | 21 | c := &Cursors{} 22 | 23 | for s, l := range links { 24 | uri, err := url.ParseRequestURI(l.URI) 25 | if err != nil { 26 | return nil, err 27 | } 28 | 29 | query := uri.Query() 30 | 31 | switch s { 32 | case "first": 33 | c.First = query.Get("cursor") 34 | case "prev": 35 | c.Prev = query.Get("cursor") 36 | case "next": 37 | c.Next = query.Get("cursor") 38 | } 39 | } 40 | 41 | return c, nil 42 | } 43 | -------------------------------------------------------------------------------- /fixtures/tokens_getall.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "created": "2018-09-06T07:05:54.080564Z", 4 | "id": "3159e485-5499-46c0-ae2b-aeb84d627a8e", 5 | "name": "login" 6 | }, 7 | { 8 | "created": "2018-09-06T08:53:26.428396Z", 9 | "id": "76d6e39d-65bc-4ab2-a1b7-6e94eee0a534", 10 | "name": "sample" 11 | }, 12 | { 13 | "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 14 | "created": "2018-09-06T09:08:43.762697Z", 15 | "last_used": null, 16 | "owner": "youremailaddress@example.com", 17 | "user_override": null, 18 | "max_age": "365 00:00:00", 19 | "max_unused_period": null, 20 | "name": "my new token", 21 | "perm_create_domain": false, 22 | "perm_delete_domain": false, 23 | "perm_manage_tokens": false, 24 | "allowed_subnets": [ 25 | "0.0.0.0/0", 26 | "::/0" 27 | ], 28 | "auto_policy": false, 29 | "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S" 30 | } 31 | ] 32 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | 13 | main: 14 | name: Main Process 15 | runs-on: ubuntu-latest 16 | env: 17 | GO_VERSION: stable 18 | GOLANGCI_LINT_VERSION: v2.5.0 19 | CGO_ENABLED: 0 20 | 21 | steps: 22 | - uses: actions/checkout@v5 23 | - uses: actions/setup-go@v6 24 | with: 25 | go-version: ${{ env.GO_VERSION }} 26 | 27 | - name: Check and get dependencies 28 | run: | 29 | go mod tidy 30 | git diff --exit-code go.mod 31 | git diff --exit-code go.sum 32 | 33 | # https://golangci-lint.run/usage/install#other-ci 34 | - name: Install golangci-lint ${{ env.GOLANGCI_LINT_VERSION }} 35 | run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/HEAD/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} 36 | 37 | - name: Make 38 | run: make 39 | -------------------------------------------------------------------------------- /desec_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "io" 5 | "net/http" 6 | "net/http/httptest" 7 | "os" 8 | "path/filepath" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func setupTest(t *testing.T, token string) (*Client, *http.ServeMux) { 14 | t.Helper() 15 | 16 | mux := http.NewServeMux() 17 | server := httptest.NewServer(mux) 18 | t.Cleanup(server.Close) 19 | 20 | options := NewDefaultClientOptions() 21 | options.HTTPClient = server.Client() 22 | 23 | client := New(token, options) 24 | client.BaseURL = server.URL 25 | 26 | return client, mux 27 | } 28 | 29 | func fromFixtures(filename string, statusCode int) http.HandlerFunc { 30 | return func(rw http.ResponseWriter, _ *http.Request) { 31 | rw.Header().Set("Content-Type", "application/json") 32 | 33 | file, err := os.Open(filepath.Clean(filepath.Join("fixtures", filename))) 34 | if err != nil { 35 | http.Error(rw, err.Error(), http.StatusInternalServerError) 36 | 37 | return 38 | } 39 | 40 | defer func() { _ = file.Close() }() 41 | 42 | rw.WriteHeader(statusCode) 43 | 44 | _, err = io.Copy(rw, file) 45 | if err != nil { 46 | http.Error(rw, err.Error(), http.StatusInternalServerError) 47 | 48 | return 49 | } 50 | } 51 | } 52 | 53 | func mustParseTime(value string) *time.Time { 54 | date, _ := time.Parse(time.RFC3339, value) 55 | return &date 56 | } 57 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | ) 9 | 10 | // NotFoundError Not found error. 11 | type NotFoundError struct { 12 | Detail string `json:"detail"` 13 | } 14 | 15 | func (n NotFoundError) Error() string { 16 | return n.Detail 17 | } 18 | 19 | // APIError error from API. 20 | type APIError struct { 21 | StatusCode int 22 | err error 23 | } 24 | 25 | func (e APIError) Error() string { 26 | return fmt.Sprintf("%d: %v", e.StatusCode, e.err) 27 | } 28 | 29 | // Unwrap unwraps error. 30 | func (e APIError) Unwrap() error { 31 | return e.err 32 | } 33 | 34 | func readError(resp *http.Response, er error) error { 35 | body, err := io.ReadAll(resp.Body) 36 | if err != nil { 37 | return &APIError{ 38 | StatusCode: resp.StatusCode, 39 | err: fmt.Errorf("failed to read response body: %w", err), 40 | } 41 | } 42 | 43 | err = json.Unmarshal(body, er) 44 | if err != nil { 45 | return &APIError{ 46 | StatusCode: resp.StatusCode, 47 | err: fmt.Errorf("failed to unmarshall response body: %w: %s", err, string(body)), 48 | } 49 | } 50 | 51 | return &APIError{ 52 | StatusCode: resp.StatusCode, 53 | err: er, 54 | } 55 | } 56 | 57 | func readRawError(resp *http.Response) error { 58 | body, err := io.ReadAll(resp.Body) 59 | if err != nil { 60 | return &APIError{ 61 | StatusCode: resp.StatusCode, 62 | err: fmt.Errorf("failed to read response body: %w", err), 63 | } 64 | } 65 | 66 | return &APIError{StatusCode: resp.StatusCode, err: fmt.Errorf("body: %s", string(body))} 67 | } 68 | -------------------------------------------------------------------------------- /pagination_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func Test_parseCursor(t *testing.T) { 11 | testCases := []struct { 12 | desc string 13 | header string 14 | expected *Cursors 15 | }{ 16 | { 17 | desc: "all cursors", 18 | header: `; rel="first", ; rel="prev", ; rel="next"`, 19 | expected: &Cursors{First: "", Prev: ":prev_cursor", Next: ":next_cursor"}, 20 | }, 21 | { 22 | desc: "first page", 23 | header: `; rel="first", ; rel="next"`, 24 | expected: &Cursors{First: "", Prev: "", Next: ":next_cursor"}, 25 | }, 26 | { 27 | desc: "last page", 28 | header: `; rel="first", ; rel="prev"`, 29 | expected: &Cursors{First: "", Prev: ":prev_cursor", Next: ""}, 30 | }, 31 | { 32 | desc: "empty", 33 | header: ``, 34 | expected: &Cursors{First: "", Prev: "", Next: ""}, 35 | }, 36 | } 37 | 38 | for _, test := range testCases { 39 | t.Run(test.desc, func(t *testing.T) { 40 | t.Parallel() 41 | 42 | h := http.Header{} 43 | h.Set("Link", test.header) 44 | 45 | cursor, err := parseCursor(h) 46 | require.NoError(t, err) 47 | 48 | require.Equal(t, test.expected, cursor) 49 | }) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | 3 | formatters: 4 | enable: 5 | - gci 6 | - gofumpt 7 | settings: 8 | gofumpt: 9 | extra-rules: true 10 | 11 | linters: 12 | default: all 13 | disable: 14 | - cyclop # duplicate of gocyclo 15 | - dupl 16 | - err113 17 | - exhaustive 18 | - exhaustruct 19 | - forcetypeassert 20 | - funcorder 21 | - lll 22 | - mnd 23 | - nilnil 24 | - nlreturn 25 | - noinlineerr 26 | - paralleltest 27 | - prealloc 28 | - rowserrcheck # not relevant (SQL) 29 | - sqlclosecheck # not relevant (SQL) 30 | - testpackage 31 | - tparallel 32 | - varnamelen 33 | - wrapcheck 34 | - wsl # deprecated 35 | 36 | settings: 37 | depguard: 38 | rules: 39 | main: 40 | deny: 41 | - pkg: github.com/instana/testify 42 | desc: not allowed 43 | - pkg: github.com/pkg/errors 44 | desc: Should be replaced by standard lib errors package 45 | funlen: 46 | lines: -1 47 | statements: 40 48 | goconst: 49 | min-len: 5 50 | min-occurrences: 3 51 | gocritic: 52 | disabled-checks: 53 | - sloppyReassign 54 | - rangeValCopy 55 | - octalLiteral 56 | - paramTypeCombine # already handle by gofumpt.extra-rules 57 | enabled-tags: 58 | - diagnostic 59 | - style 60 | - performance 61 | settings: 62 | hugeParam: 63 | sizeThreshold: 120 64 | gocyclo: 65 | min-complexity: 15 66 | godox: 67 | keywords: 68 | - FIXME 69 | govet: 70 | disable: 71 | - fieldalignment 72 | enable-all: true 73 | misspell: 74 | locale: US 75 | tagliatelle: 76 | case: 77 | rules: 78 | json: snake 79 | perfsprint: 80 | err-error: true 81 | errorf: true 82 | sprintf1: true 83 | strconcat: false 84 | 85 | exclusions: 86 | warn-unused: true 87 | presets: 88 | - comments 89 | - std-error-handling 90 | rules: 91 | - linters: 92 | - funlen 93 | path: .*_test.go 94 | 95 | issues: 96 | max-issues-per-linter: 0 97 | max-same-issues: 0 98 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Go library for accessing the deSEC API 2 | 3 | [![Build Status](https://github.com/nrdcg/desec/workflows/Main/badge.svg?branch=main)](https://github.com/nrdcg/desec/actions) 4 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/nrdcg/desec)](https://pkg.go.dev/github.com/nrdcg/desec) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/nrdcg/desec)](https://goreportcard.com/report/github.com/nrdcg/desec) 6 | 7 | An deSEC API client written in Go. 8 | 9 | desec is a Go client library for accessing the deSEC API. 10 | 11 | ## Examples 12 | 13 | ```go 14 | package main 15 | 16 | import ( 17 | "context" 18 | "fmt" 19 | 20 | "github.com/nrdcg/desec" 21 | ) 22 | 23 | func main() { 24 | client := desec.NewClient("token") 25 | 26 | newDomain, err := client.Domains.Create(context.Background(), "example.com") 27 | if err != nil { 28 | panic(err) 29 | } 30 | 31 | fmt.Println(newDomain) 32 | } 33 | ``` 34 | 35 | ```go 36 | package main 37 | 38 | import ( 39 | "context" 40 | 41 | "github.com/nrdcg/desec" 42 | ) 43 | 44 | func main() { 45 | client := desec.NewClient("") 46 | registration := desec.Registration{ 47 | Email: "email@example.com", 48 | Password: "secret", 49 | Captcha: &desec.Captcha{ 50 | ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", 51 | Solution: "12H45", 52 | }, 53 | } 54 | 55 | err := client.Account.Register(context.Background(), registration) 56 | if err != nil { 57 | panic(err) 58 | } 59 | } 60 | ``` 61 | 62 | ```go 63 | package main 64 | 65 | import ( 66 | "context" 67 | "fmt" 68 | 69 | "github.com/nrdcg/desec" 70 | ) 71 | 72 | func main() { 73 | client := desec.NewClient("") 74 | 75 | _, err := client.Account.Login(context.Background(), "email@example.com", "secret") 76 | if err != nil { 77 | panic(err) 78 | } 79 | 80 | domains, err := client.Domains.GetAllPagined(context.Background()) 81 | if err != nil { 82 | panic(err) 83 | } 84 | 85 | fmt.Println(domains) 86 | 87 | err = client.Account.Logout(context.Background()) 88 | if err != nil { 89 | panic(err) 90 | } 91 | } 92 | ``` 93 | 94 | ## API Documentation 95 | 96 | - [API docs](https://desec.readthedocs.io/en/latest/) 97 | - [API endpoint reference](https://desec.readthedocs.io/en/latest/endpoint-reference.html) 98 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= 4 | github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= 5 | github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= 6 | github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= 7 | github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= 8 | github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= 9 | github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= 10 | github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= 11 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= 12 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 13 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 14 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 15 | github.com/peterhellberg/link v1.2.0 h1:UA5pg3Gp/E0F2WdX7GERiNrPQrM1K6CVJUUWfHa4t6c= 16 | github.com/peterhellberg/link v1.2.0/go.mod h1:gYfAh+oJgQu2SrZHg5hROVRQe1ICoK0/HHJTcE0edxc= 17 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 18 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 19 | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= 20 | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= 21 | golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= 22 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 23 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 24 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 25 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 26 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 27 | -------------------------------------------------------------------------------- /account_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestAccountClient_ObtainCaptcha(t *testing.T) { 13 | client, mux := setupTest(t, "") 14 | 15 | mux.HandleFunc("POST /captcha/", fromFixtures("accounts_captcha.json", http.StatusOK)) 16 | 17 | captcha, err := client.Account.ObtainCaptcha(context.Background()) 18 | require.NoError(t, err) 19 | 20 | expected := &Captcha{ 21 | ID: "aaa", 22 | Challenge: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8zxD3EwAFuwJYQcBz5wAAAABJRU5ErkJggg==", 23 | } 24 | assert.Equal(t, expected, captcha) 25 | } 26 | 27 | func TestAccountClient_Register(t *testing.T) { 28 | client, mux := setupTest(t, "") 29 | 30 | mux.HandleFunc("POST /auth/", func(rw http.ResponseWriter, _ *http.Request) { 31 | rw.WriteHeader(http.StatusAccepted) 32 | }) 33 | 34 | registration := Registration{ 35 | Email: "email@example.com", 36 | Password: "secret", 37 | Captcha: &Captcha{ 38 | ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", 39 | Solution: "12H45", 40 | }, 41 | } 42 | 43 | err := client.Account.Register(context.Background(), registration) 44 | require.NoError(t, err) 45 | } 46 | 47 | func TestAccountClient_Login(t *testing.T) { 48 | client, mux := setupTest(t, "") 49 | 50 | mux.HandleFunc("POST /auth/login/", fromFixtures("accounts_login.json", http.StatusOK)) 51 | 52 | token, err := client.Account.Login(context.Background(), "email@example.com", "secret") 53 | require.NoError(t, err) 54 | 55 | expected := &Token{ 56 | ID: "8f9cbae2-c862-48a4-b3f0-2cb1a80df168", 57 | Name: "login", 58 | Value: "f07Q0TRmEb-CRWPe4h64_iV2jbet", 59 | Created: mustParseTime("2018-09-06T09:07:43.762697Z"), 60 | } 61 | assert.Equal(t, expected, token) 62 | 63 | assert.Equal(t, expected.Value, client.token) 64 | } 65 | 66 | func TestAccountClient_Logout(t *testing.T) { 67 | client, mux := setupTest(t, "f07Q0TRmEb-CRWPe4h64_iV2jbet") 68 | 69 | mux.HandleFunc("POST /auth/logout/", func(rw http.ResponseWriter, _ *http.Request) { 70 | rw.WriteHeader(http.StatusNoContent) 71 | }) 72 | 73 | err := client.Account.Logout(context.Background()) 74 | require.NoError(t, err) 75 | 76 | assert.Empty(t, client.token) 77 | } 78 | 79 | func TestAccountClient_RetrieveInformation(t *testing.T) { 80 | client, mux := setupTest(t, "f07Q0TRmEb-CRWPe4h64_iV2jbet") 81 | 82 | mux.HandleFunc("POST /auth/account/", fromFixtures("accounts_retrieve.json", http.StatusOK)) 83 | 84 | account, err := client.Account.RetrieveInformation(context.Background()) 85 | require.NoError(t, err) 86 | 87 | expected := &Account{ 88 | Email: "youremailaddress@example.com", 89 | LimitDomains: 5, 90 | Created: mustParseTime("2019-10-16T18:09:17.715702Z"), 91 | } 92 | assert.Equal(t, expected, account) 93 | } 94 | 95 | func TestAccountClient_PasswordReset(t *testing.T) { 96 | client, mux := setupTest(t, "") 97 | 98 | mux.HandleFunc("POST /", func(rw http.ResponseWriter, _ *http.Request) { 99 | rw.WriteHeader(http.StatusAccepted) 100 | }) 101 | 102 | captcha := Captcha{ 103 | ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", 104 | Solution: "12H45", 105 | } 106 | 107 | err := client.Account.PasswordReset(context.Background(), "email@example.com", captcha) 108 | require.NoError(t, err) 109 | } 110 | 111 | func TestAccountClient_ChangeEmail(t *testing.T) { 112 | client, mux := setupTest(t, "") 113 | 114 | mux.HandleFunc("POST /", func(rw http.ResponseWriter, _ *http.Request) { 115 | rw.WriteHeader(http.StatusAccepted) 116 | }) 117 | 118 | err := client.Account.ChangeEmail(context.Background(), "email@example.com", "secret", "newemail@example.com") 119 | require.NoError(t, err) 120 | } 121 | 122 | func TestAccountClient_Delete(t *testing.T) { 123 | client, mux := setupTest(t, "") 124 | 125 | mux.HandleFunc("POST /auth/account/delete/", func(rw http.ResponseWriter, _ *http.Request) { 126 | rw.WriteHeader(http.StatusAccepted) 127 | }) 128 | 129 | err := client.Account.Delete(context.Background(), "email@example.com", "secret") 130 | require.NoError(t, err) 131 | } 132 | -------------------------------------------------------------------------------- /tokens_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestTokensService_Create(t *testing.T) { 13 | client, mux := setupTest(t, "token") 14 | 15 | mux.HandleFunc("POST /auth/tokens/", fromFixtures("tokens_create.json", http.StatusCreated)) 16 | 17 | newToken, err := client.Tokens.Create(context.Background(), "my new token") 18 | require.NoError(t, err) 19 | 20 | expected := &Token{ 21 | ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 22 | Name: "my new token", 23 | Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", 24 | Created: mustParseTime("2018-09-06T09:08:43.762697Z"), 25 | } 26 | assert.Equal(t, expected, newToken) 27 | } 28 | 29 | func TestTokensService_GetAll(t *testing.T) { 30 | client, mux := setupTest(t, "token") 31 | 32 | mux.HandleFunc("GET /auth/tokens/", fromFixtures("tokens_getall.json", http.StatusOK)) 33 | 34 | tokens, err := client.Tokens.GetAll(context.Background()) 35 | require.NoError(t, err) 36 | 37 | expected := []Token{ 38 | { 39 | ID: "3159e485-5499-46c0-ae2b-aeb84d627a8e", 40 | Name: "login", 41 | Created: mustParseTime("2018-09-06T07:05:54.080564Z"), 42 | }, 43 | { 44 | ID: "76d6e39d-65bc-4ab2-a1b7-6e94eee0a534", 45 | Name: "sample", 46 | Created: mustParseTime("2018-09-06T08:53:26.428396Z"), 47 | }, 48 | { 49 | ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 50 | Created: mustParseTime("2018-09-06T09:08:43.762697Z"), 51 | Owner: "youremailaddress@example.com", 52 | Name: "my new token", 53 | PermCreateDomain: false, 54 | PermDeleteDomain: false, 55 | PermManageTokens: false, 56 | AllowedSubnets: []string{ 57 | "0.0.0.0/0", 58 | "::/0", 59 | }, 60 | AutoPolicy: false, 61 | Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", 62 | }, 63 | } 64 | assert.Equal(t, expected, tokens) 65 | } 66 | 67 | func TestTokensService_Get(t *testing.T) { 68 | client, mux := setupTest(t, "token") 69 | 70 | mux.HandleFunc("GET /auth/tokens/3a6b94b5-d20e-40bd-a7cc-521f5c79fab3/", 71 | fromFixtures("tokens_get.json", http.StatusOK)) 72 | 73 | token, err := client.Tokens.Get(context.Background(), "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3") 74 | require.NoError(t, err) 75 | 76 | expected := &Token{ 77 | ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 78 | Created: mustParseTime("2018-09-06T09:08:43.762697Z"), 79 | Owner: "youremailaddress@example.com", 80 | Name: "my new token", 81 | PermCreateDomain: false, 82 | PermDeleteDomain: false, 83 | PermManageTokens: false, 84 | AllowedSubnets: []string{ 85 | "0.0.0.0/0", 86 | "::/0", 87 | }, 88 | AutoPolicy: false, 89 | Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", 90 | } 91 | assert.Equal(t, expected, token) 92 | } 93 | 94 | func TestTokensService_Update(t *testing.T) { 95 | client, mux := setupTest(t, "token") 96 | 97 | mux.HandleFunc("PATCH /auth/tokens/3a6b94b5-d20e-40bd-a7cc-521f5c79fab3/", 98 | fromFixtures("tokens_update.json", http.StatusOK)) 99 | 100 | token, err := client.Tokens.Update(context.Background(), "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", &Token{ 101 | PermCreateDomain: true, 102 | PermDeleteDomain: false, 103 | PermManageTokens: true, 104 | }) 105 | 106 | require.NoError(t, err) 107 | 108 | expected := &Token{ 109 | ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", 110 | Created: mustParseTime("2018-09-06T09:08:43.762697Z"), 111 | Owner: "youremailaddress@example.com", 112 | Name: "my new token", 113 | PermCreateDomain: true, 114 | PermDeleteDomain: false, 115 | PermManageTokens: true, 116 | AllowedSubnets: []string{ 117 | "0.0.0.0/0", 118 | "::/0", 119 | }, 120 | AutoPolicy: false, 121 | Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", 122 | } 123 | assert.Equal(t, expected, token) 124 | } 125 | 126 | func TestTokensService_Delete(t *testing.T) { 127 | client, mux := setupTest(t, "token") 128 | 129 | mux.HandleFunc("DELETE /auth/tokens/aaa/", func(rw http.ResponseWriter, _ *http.Request) { 130 | rw.WriteHeader(http.StatusNoContent) 131 | }) 132 | 133 | err := client.Tokens.Delete(context.Background(), "aaa") 134 | require.NoError(t, err) 135 | } 136 | -------------------------------------------------------------------------------- /desec.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "io" 9 | "net/http" 10 | "net/url" 11 | "time" 12 | 13 | "github.com/hashicorp/go-retryablehttp" 14 | ) 15 | 16 | const defaultBaseURL = "https://desec.io/api/v1/" 17 | 18 | type httpDoer interface { 19 | Do(req *http.Request) (*http.Response, error) 20 | } 21 | 22 | type service struct { 23 | client *Client 24 | } 25 | 26 | // ClientOptions the options of the Client. 27 | type ClientOptions struct { 28 | // HTTPClient HTTP client used to communicate with the API. 29 | HTTPClient *http.Client 30 | 31 | // Maximum number of retries 32 | RetryMax int 33 | 34 | // Customer logger instance. Can be either Logger or LeveledLogger 35 | Logger any 36 | } 37 | 38 | // NewDefaultClientOptions creates a new ClientOptions with default values. 39 | func NewDefaultClientOptions() ClientOptions { 40 | return ClientOptions{ 41 | HTTPClient: &http.Client{Timeout: 10 * time.Second}, 42 | RetryMax: 5, 43 | Logger: nil, 44 | } 45 | } 46 | 47 | // Client deSEC API client. 48 | type Client struct { 49 | // Base URL for API requests. 50 | BaseURL string 51 | 52 | httpClient httpDoer 53 | 54 | token string 55 | 56 | common service // Reuse a single struct instead of allocating one for each service on the heap. 57 | 58 | // Services used for talking to different parts of the deSEC API. 59 | Account *AccountService 60 | Tokens *TokensService 61 | TokenPolicies *TokenPoliciesService 62 | Records *RecordsService 63 | Domains *DomainsService 64 | } 65 | 66 | // New creates a new Client. 67 | func New(token string, opts ClientOptions) *Client { 68 | // https://github.com/desec-io/desec-stack/blob/main/docs/rate-limits.rst 69 | retryClient := retryablehttp.NewClient() 70 | retryClient.RetryMax = opts.RetryMax 71 | retryClient.HTTPClient = opts.HTTPClient 72 | retryClient.Logger = opts.Logger 73 | 74 | client := &Client{ 75 | httpClient: retryClient.StandardClient(), 76 | BaseURL: defaultBaseURL, 77 | token: token, 78 | } 79 | 80 | client.common.client = client 81 | 82 | client.Account = (*AccountService)(&client.common) 83 | client.Tokens = (*TokensService)(&client.common) 84 | client.TokenPolicies = (*TokenPoliciesService)(&client.common) 85 | client.Records = (*RecordsService)(&client.common) 86 | client.Domains = (*DomainsService)(&client.common) 87 | 88 | return client 89 | } 90 | 91 | func (c *Client) newRequest(ctx context.Context, method string, endpoint fmt.Stringer, reqBody any) (*http.Request, error) { 92 | buf := new(bytes.Buffer) 93 | 94 | if reqBody != nil { 95 | err := json.NewEncoder(buf).Encode(reqBody) 96 | if err != nil { 97 | return nil, fmt.Errorf("failed to marshal request body: %w", err) 98 | } 99 | } 100 | 101 | req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf) 102 | if err != nil { 103 | return nil, fmt.Errorf("failed to create request: %w", err) 104 | } 105 | 106 | req.Header.Set("Content-Type", "application/json") 107 | 108 | if c.token != "" { 109 | req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) 110 | } 111 | 112 | return req, nil 113 | } 114 | 115 | func (c *Client) createEndpoint(parts ...string) (*url.URL, error) { 116 | base, err := url.Parse(c.BaseURL) 117 | if err != nil { 118 | return nil, err 119 | } 120 | 121 | endpoint := base.JoinPath(parts...) 122 | endpoint.Path += "/" 123 | 124 | return endpoint, nil 125 | } 126 | 127 | func handleResponse(resp *http.Response, respData any) error { 128 | body, err := io.ReadAll(resp.Body) 129 | if err != nil { 130 | return &APIError{ 131 | StatusCode: resp.StatusCode, 132 | err: fmt.Errorf("failed to read response body: %w", err), 133 | } 134 | } 135 | 136 | if len(body) == 0 { 137 | return nil 138 | } 139 | 140 | err = json.Unmarshal(body, respData) 141 | if err != nil { 142 | return fmt.Errorf("failed to umarshal response body: %w", err) 143 | } 144 | 145 | return nil 146 | } 147 | 148 | func handleError(resp *http.Response) error { 149 | switch resp.StatusCode { 150 | case http.StatusNotFound: 151 | return readError(resp, &NotFoundError{}) 152 | default: 153 | return readRawError(resp) 154 | } 155 | } 156 | 157 | // Pointer creates pointer of string. 158 | func Pointer[T string](v T) *T { return &v } 159 | -------------------------------------------------------------------------------- /domains_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestDomainsService_Create(t *testing.T) { 13 | client, mux := setupTest(t, "token") 14 | 15 | mux.HandleFunc("POST /domains/", fromFixtures("domains_create.json", http.StatusCreated)) 16 | 17 | newDomain, err := client.Domains.Create(context.Background(), "example.com") 18 | require.NoError(t, err) 19 | 20 | expected := &Domain{ 21 | Name: "example.com", 22 | MinimumTTL: 3600, 23 | Keys: []DomainKey{ 24 | { 25 | DNSKey: "257 3 13 WFRl60...", 26 | DS: []string{ 27 | "6006 13 1 8581e9...", 28 | "6006 13 2 f34b75...", 29 | "6006 13 3 dfb325...", 30 | "6006 13 4 2fdcf8...", 31 | }, 32 | Flags: 257, 33 | KeyType: "csk", 34 | }, 35 | }, 36 | Created: mustParseTime("2018-09-18T16:36:16.510368Z"), 37 | Published: mustParseTime("2018-09-18T17:21:38.348112Z"), 38 | Touched: mustParseTime("2018-09-18T17:21:38.348112Z"), 39 | } 40 | assert.Equal(t, expected, newDomain) 41 | } 42 | 43 | func TestDomainsService_Delete(t *testing.T) { 44 | client, mux := setupTest(t, "token") 45 | 46 | mux.HandleFunc("DELETE /domains/example.com/", func(rw http.ResponseWriter, _ *http.Request) { 47 | rw.WriteHeader(http.StatusNoContent) 48 | }) 49 | 50 | err := client.Domains.Delete(context.Background(), "example.com") 51 | require.NoError(t, err) 52 | } 53 | 54 | func TestDomainsService_Get(t *testing.T) { 55 | client, mux := setupTest(t, "token") 56 | 57 | mux.HandleFunc("GET /domains/example.com/", fromFixtures("domains_get.json", http.StatusOK)) 58 | 59 | domain, err := client.Domains.Get(context.Background(), "example.com") 60 | require.NoError(t, err) 61 | 62 | expected := &Domain{ 63 | Name: "example.com", 64 | MinimumTTL: 3600, 65 | Keys: []DomainKey{ 66 | { 67 | DNSKey: "257 3 13 WFRl60...", 68 | DS: []string{ 69 | "6006 13 1 8581e9...", 70 | "6006 13 2 f34b75...", 71 | "6006 13 3 dfb325...", 72 | "6006 13 4 2fdcf8...", 73 | }, 74 | Flags: 257, 75 | KeyType: "csk", 76 | }, 77 | }, 78 | Created: mustParseTime("2018-09-18T16:36:16.510368Z"), 79 | Published: mustParseTime("2018-09-18T17:21:38.348112Z"), 80 | Touched: mustParseTime("2018-09-18T17:21:38.348112Z"), 81 | } 82 | assert.Equal(t, expected, domain) 83 | } 84 | 85 | func TestDomainsService_GetResponsible(t *testing.T) { 86 | client, mux := setupTest(t, "token") 87 | 88 | mux.HandleFunc("GET /domains/", func(rw http.ResponseWriter, req *http.Request) { 89 | if req.URL.Query().Get("owns_qname") != "git.dev.example.org" { 90 | http.Error(rw, "owns_qname not passed correctly", http.StatusBadRequest) 91 | return 92 | } 93 | 94 | fromFixtures("domains_getresponsible.json", http.StatusOK).ServeHTTP(rw, req) 95 | }) 96 | 97 | domain, err := client.Domains.GetResponsible(context.Background(), "git.dev.example.org") 98 | require.NoError(t, err) 99 | 100 | expected := &Domain{ 101 | Name: "dev.example.org", 102 | MinimumTTL: 3600, 103 | Created: mustParseTime("2022-11-12T18:01:35.454616Z"), 104 | Published: mustParseTime("2022-11-12T18:03:19.516440Z"), 105 | Touched: mustParseTime("2022-11-12T18:03:19.516440Z"), 106 | } 107 | assert.Equal(t, expected, domain) 108 | } 109 | 110 | func TestDomainsService_GetResponsible_error(t *testing.T) { 111 | client, mux := setupTest(t, "token") 112 | 113 | mux.HandleFunc("GET /domains/", func(rw http.ResponseWriter, _ *http.Request) { 114 | _, _ = rw.Write([]byte("[]")) 115 | }) 116 | 117 | _, err := client.Domains.GetResponsible(context.Background(), "git.dev.example.org") 118 | 119 | var notFoundError *NotFoundError 120 | 121 | require.ErrorAs(t, err, ¬FoundError) 122 | } 123 | 124 | func TestDomainsService_GetAll(t *testing.T) { 125 | client, mux := setupTest(t, "token") 126 | 127 | mux.HandleFunc("GET /domains/", fromFixtures("domains_getall.json", http.StatusOK)) 128 | 129 | domains, err := client.Domains.GetAll(context.Background()) 130 | require.NoError(t, err) 131 | 132 | expected := []Domain{ 133 | { 134 | Name: "example.org", 135 | MinimumTTL: 3600, 136 | Created: mustParseTime("2020-05-13T11:35:40.954616Z"), 137 | Published: mustParseTime("2020-05-13T12:25:19.816440Z"), 138 | Touched: mustParseTime("2020-05-13T12:25:19.816440Z"), 139 | }, 140 | { 141 | Name: "example.dedyn.io", 142 | MinimumTTL: 60, 143 | Created: mustParseTime("2020-05-05T23:17:36.101470Z"), 144 | Published: mustParseTime("2020-05-06T12:13:06.138443Z"), 145 | Touched: mustParseTime("2020-05-06T12:13:06.138443Z"), 146 | }, 147 | } 148 | assert.Equal(t, expected, domains) 149 | } 150 | -------------------------------------------------------------------------------- /token_policies_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestTokenPoliciesService_Get(t *testing.T) { 13 | client, mux := setupTest(t, "token") 14 | 15 | mux.HandleFunc("GET /auth/tokens/aaa/policies/rrsets/", 16 | fromFixtures("tokens_policy_get_all.json", http.StatusOK)) 17 | 18 | tokens, err := client.TokenPolicies.Get(context.Background(), "aaa") 19 | require.NoError(t, err) 20 | 21 | expected := []TokenPolicy{ 22 | { 23 | ID: "7aed3f71-bc81-4f7e-90ae-8f0df0d1c211", 24 | Domain: Pointer("example.com"), 25 | SubName: Pointer("testing"), 26 | WritePermission: false, 27 | }, 28 | { 29 | ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", 30 | Domain: Pointer("example.com"), 31 | SubName: Pointer("testing"), 32 | Type: Pointer("A"), 33 | WritePermission: true, 34 | }, 35 | } 36 | assert.Equal(t, expected, tokens) 37 | } 38 | 39 | func TestTokenPoliciesService_GetOne(t *testing.T) { 40 | client, mux := setupTest(t, "token") 41 | 42 | mux.HandleFunc("GET /auth/tokens/aaa/policies/rrsets/fa6fdf60-6546-4cee-9168-5d144fe9339c/", 43 | fromFixtures("tokens_policy_get.json", http.StatusOK)) 44 | 45 | tokens, err := client.TokenPolicies.GetOne(context.Background(), "aaa", "fa6fdf60-6546-4cee-9168-5d144fe9339c") 46 | require.NoError(t, err) 47 | 48 | expected := &TokenPolicy{ 49 | ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", 50 | Domain: Pointer("example.com"), 51 | SubName: Pointer("testing"), 52 | Type: Pointer("A"), 53 | WritePermission: true, 54 | } 55 | assert.Equal(t, expected, tokens) 56 | } 57 | 58 | func TestTokenPoliciesService_Update(t *testing.T) { 59 | client, mux := setupTest(t, "token") 60 | 61 | mux.HandleFunc("PATCH /auth/tokens/aaa/policies/rrsets/fa6fdf60-6546-4cee-9168-5d144fe9339c/", 62 | fromFixtures("tokens_policy_update.json", http.StatusOK)) 63 | 64 | tokens, err := client.TokenPolicies.Update(context.Background(), "aaa", "fa6fdf60-6546-4cee-9168-5d144fe9339c", TokenPolicy{ 65 | WritePermission: false, 66 | }) 67 | require.NoError(t, err) 68 | 69 | expected := &TokenPolicy{ 70 | ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", 71 | Domain: Pointer("example.com"), 72 | SubName: Pointer("testing"), 73 | Type: Pointer("A"), 74 | WritePermission: false, 75 | } 76 | assert.Equal(t, expected, tokens) 77 | } 78 | 79 | func TestTokenPoliciesService_GetAll(t *testing.T) { 80 | client, mux := setupTest(t, "token") 81 | 82 | mux.HandleFunc("GET /auth/tokens/aaa/policies/rrsets/", fromFixtures("tokens_policy_get_all.json", http.StatusOK)) 83 | 84 | tokens, err := client.TokenPolicies.GetAll(context.Background(), "aaa") 85 | require.NoError(t, err) 86 | 87 | expected := []TokenPolicy{ 88 | { 89 | ID: "7aed3f71-bc81-4f7e-90ae-8f0df0d1c211", 90 | Domain: Pointer("example.com"), 91 | SubName: Pointer("testing"), 92 | WritePermission: false, 93 | }, 94 | { 95 | ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", 96 | Domain: Pointer("example.com"), 97 | SubName: Pointer("testing"), 98 | Type: Pointer("A"), 99 | WritePermission: true, 100 | }, 101 | } 102 | assert.Equal(t, expected, tokens) 103 | } 104 | 105 | func TestTokenPoliciesService_Create(t *testing.T) { 106 | client, mux := setupTest(t, "token") 107 | 108 | mux.HandleFunc("POST /auth/tokens/aaa/policies/rrsets/", 109 | fromFixtures("tokens_policy_create.json", http.StatusCreated)) 110 | 111 | mux.HandleFunc("POST /auth/tokens/bbb/policies/rrsets/", 112 | fromFixtures("tokens_policy_create_empty.json", http.StatusCreated)) 113 | 114 | testCases := []struct { 115 | desc string 116 | tokenID string 117 | policy TokenPolicy 118 | expected *TokenPolicy 119 | }{ 120 | { 121 | desc: "all fields", 122 | tokenID: "aaa", 123 | policy: TokenPolicy{ 124 | Domain: Pointer("example.com"), 125 | SubName: Pointer("testing"), 126 | Type: Pointer("A"), 127 | WritePermission: true, 128 | }, 129 | expected: &TokenPolicy{ 130 | ID: "2f133e8e-56a0-4b19-8e7e-f2e29c7ce263", 131 | Domain: Pointer("example.com"), 132 | SubName: Pointer("testing"), 133 | Type: Pointer("A"), 134 | WritePermission: true, 135 | }, 136 | }, 137 | { 138 | desc: "all null JSON policy", 139 | tokenID: "bbb", 140 | policy: TokenPolicy{}, 141 | expected: &TokenPolicy{ 142 | ID: "a563a574-33c9-45d1-9201-e5577b42aaf1", 143 | WritePermission: false, 144 | }, 145 | }, 146 | } 147 | 148 | for _, test := range testCases { 149 | t.Run(test.desc, func(t *testing.T) { 150 | t.Parallel() 151 | 152 | policies, err := client.TokenPolicies.Create(context.Background(), test.tokenID, test.policy) 153 | require.NoError(t, err) 154 | 155 | assert.Equal(t, test.expected, policies) 156 | }) 157 | } 158 | } 159 | 160 | func TestTokenPoliciesService_Delete(t *testing.T) { 161 | client, mux := setupTest(t, "token") 162 | 163 | mux.HandleFunc("DELETE /auth/tokens/aaa/policies/rrsets/bbb/", func(rw http.ResponseWriter, _ *http.Request) { 164 | rw.WriteHeader(http.StatusNoContent) 165 | }) 166 | 167 | err := client.TokenPolicies.Delete(context.Background(), "aaa", "bbb") 168 | require.NoError(t, err) 169 | } 170 | -------------------------------------------------------------------------------- /token_policies.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | ) 8 | 9 | // TokenPolicy represents a policy applied to a token. 10 | type TokenPolicy struct { 11 | ID string `json:"id,omitempty"` 12 | Domain *string `json:"domain"` 13 | SubName *string `json:"subname"` 14 | Type *string `json:"type"` 15 | WritePermission bool `json:"perm_write,omitempty"` 16 | } 17 | 18 | // TokenPoliciesService handles communication with the token policy related methods of the deSEC API. 19 | // 20 | // https://desec.readthedocs.io/en/latest/auth/tokens.html 21 | type TokenPoliciesService struct { 22 | client *Client 23 | } 24 | 25 | // Deprecated: use [TokenPoliciesService.GetAll] instead. 26 | func (s *TokenPoliciesService) Get(ctx context.Context, tokenID string) ([]TokenPolicy, error) { 27 | return s.GetAll(ctx, tokenID) 28 | } 29 | 30 | // GetOne retrieves a specific token rrset policy. 31 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management 32 | func (s *TokenPoliciesService) GetOne(ctx context.Context, tokenID, policyID string) (*TokenPolicy, error) { 33 | endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets", policyID) 34 | if err != nil { 35 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 36 | } 37 | 38 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | resp, err := s.client.httpClient.Do(req) 44 | if err != nil { 45 | return nil, fmt.Errorf("failed to call API: %w", err) 46 | } 47 | 48 | defer func() { _ = resp.Body.Close() }() 49 | 50 | if resp.StatusCode != http.StatusOK { 51 | return nil, handleError(resp) 52 | } 53 | 54 | policy := &TokenPolicy{} 55 | 56 | err = handleResponse(resp, policy) 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | return policy, nil 62 | } 63 | 64 | // GetAll retrieves all rrset policies for a token. 65 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management 66 | func (s *TokenPoliciesService) GetAll(ctx context.Context, tokenID string) ([]TokenPolicy, error) { 67 | endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets") 68 | if err != nil { 69 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 70 | } 71 | 72 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 73 | if err != nil { 74 | return nil, err 75 | } 76 | 77 | resp, err := s.client.httpClient.Do(req) 78 | if err != nil { 79 | return nil, fmt.Errorf("failed to call API: %w", err) 80 | } 81 | 82 | defer func() { _ = resp.Body.Close() }() 83 | 84 | if resp.StatusCode != http.StatusOK { 85 | return nil, handleError(resp) 86 | } 87 | 88 | var policies []TokenPolicy 89 | 90 | err = handleResponse(resp, &policies) 91 | if err != nil { 92 | return nil, err 93 | } 94 | 95 | return policies, nil 96 | } 97 | 98 | // Create creates token policy. 99 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#create-additional-tokens 100 | func (s *TokenPoliciesService) Create(ctx context.Context, tokenID string, policy TokenPolicy) (*TokenPolicy, error) { 101 | endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets") 102 | if err != nil { 103 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 104 | } 105 | 106 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, policy) 107 | if err != nil { 108 | return nil, err 109 | } 110 | 111 | resp, err := s.client.httpClient.Do(req) 112 | if err != nil { 113 | return nil, fmt.Errorf("failed to call API: %w", err) 114 | } 115 | 116 | defer func() { _ = resp.Body.Close() }() 117 | 118 | if resp.StatusCode != http.StatusCreated { 119 | return nil, handleError(resp) 120 | } 121 | 122 | var tokenPolicy TokenPolicy 123 | 124 | err = handleResponse(resp, &tokenPolicy) 125 | if err != nil { 126 | return nil, err 127 | } 128 | 129 | return &tokenPolicy, nil 130 | } 131 | 132 | // Update a token policy 133 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management 134 | func (s *TokenPoliciesService) Update(ctx context.Context, tokenID, policyID string, policy TokenPolicy) (*TokenPolicy, error) { 135 | endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets", policyID) 136 | if err != nil { 137 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 138 | } 139 | 140 | // Copy values, including only fields that can be modified 141 | req, err := s.client.newRequest(ctx, http.MethodPatch, endpoint, TokenPolicy{ 142 | Domain: policy.Domain, 143 | SubName: policy.SubName, 144 | Type: policy.Type, 145 | WritePermission: policy.WritePermission, 146 | }) 147 | if err != nil { 148 | return nil, err 149 | } 150 | 151 | resp, err := s.client.httpClient.Do(req) 152 | if err != nil { 153 | return nil, fmt.Errorf("failed to call API: %w", err) 154 | } 155 | 156 | defer func() { _ = resp.Body.Close() }() 157 | 158 | if resp.StatusCode != http.StatusOK { 159 | return nil, handleError(resp) 160 | } 161 | 162 | result := &TokenPolicy{} 163 | 164 | err = handleResponse(resp, result) 165 | if err != nil { 166 | return nil, err 167 | } 168 | 169 | return result, nil 170 | } 171 | 172 | // Delete deletes a token rrset's policy. 173 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management 174 | func (s *TokenPoliciesService) Delete(ctx context.Context, tokenID, policyID string) error { 175 | endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets", policyID) 176 | if err != nil { 177 | return fmt.Errorf("failed to create endpoint: %w", err) 178 | } 179 | 180 | req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) 181 | if err != nil { 182 | return err 183 | } 184 | 185 | resp, err := s.client.httpClient.Do(req) 186 | if err != nil { 187 | return fmt.Errorf("failed to call API: %w", err) 188 | } 189 | 190 | defer func() { _ = resp.Body.Close() }() 191 | 192 | if resp.StatusCode != http.StatusNoContent { 193 | return handleError(resp) 194 | } 195 | 196 | return nil 197 | } 198 | -------------------------------------------------------------------------------- /domains.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "net/url" 8 | "time" 9 | ) 10 | 11 | // Domain a domain representation. 12 | type Domain struct { 13 | Name string `json:"name,omitempty"` 14 | MinimumTTL int `json:"minimum_ttl,omitempty"` 15 | Keys []DomainKey `json:"keys,omitempty"` 16 | Created *time.Time `json:"created,omitempty"` 17 | Published *time.Time `json:"published,omitempty"` 18 | Touched *time.Time `json:"touched,omitempty"` 19 | } 20 | 21 | // DomainKey a domain key representation. 22 | type DomainKey struct { 23 | DNSKey string `json:"dnskey,omitempty"` 24 | DS []string `json:"ds,omitempty"` 25 | Flags int `json:"flags,omitempty"` 26 | KeyType string `json:"keytype,omitempty"` 27 | } 28 | 29 | // DomainsService handles communication with the domain related methods of the deSEC API. 30 | // 31 | // https://desec.readthedocs.io/en/latest/dns/domains.html 32 | type DomainsService struct { 33 | client *Client 34 | } 35 | 36 | // Create creating a domain. 37 | // https://desec.readthedocs.io/en/latest/dns/domains.html#creating-a-domain 38 | func (s *DomainsService) Create(ctx context.Context, domainName string) (*Domain, error) { 39 | endpoint, err := s.client.createEndpoint("domains") 40 | if err != nil { 41 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 42 | } 43 | 44 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Domain{Name: domainName}) 45 | if err != nil { 46 | return nil, err 47 | } 48 | 49 | resp, err := s.client.httpClient.Do(req) 50 | if err != nil { 51 | return nil, fmt.Errorf("failed to call API: %w", err) 52 | } 53 | 54 | defer func() { _ = resp.Body.Close() }() 55 | 56 | if resp.StatusCode != http.StatusCreated { 57 | return nil, handleError(resp) 58 | } 59 | 60 | var domain Domain 61 | 62 | err = handleResponse(resp, &domain) 63 | if err != nil { 64 | return nil, err 65 | } 66 | 67 | return &domain, nil 68 | } 69 | 70 | // GetAll listing domains. 71 | // https://desec.readthedocs.io/en/latest/dns/domains.html#listing-domains 72 | func (s *DomainsService) GetAll(ctx context.Context) ([]Domain, error) { 73 | domains, _, err := s.GetAllPaginated(ctx, "") 74 | if err != nil { 75 | return nil, err 76 | } 77 | 78 | return domains, nil 79 | } 80 | 81 | // GetAllPaginated listing domains. 82 | // https://desec.readthedocs.io/en/latest/dns/domains.html#listing-domains 83 | func (s *DomainsService) GetAllPaginated(ctx context.Context, cursor string) ([]Domain, *Cursors, error) { 84 | queryValues := url.Values{} 85 | queryValues.Set("cursor", cursor) 86 | 87 | return s.getAll(ctx, queryValues) 88 | } 89 | 90 | // GetResponsible returns the responsible domain for a given DNS query name. 91 | // https://desec.readthedocs.io/en/latest/dns/domains.html#identifying-the-responsible-domain-for-a-dns-name 92 | func (s *DomainsService) GetResponsible(ctx context.Context, domainName string) (*Domain, error) { 93 | queryValues := url.Values{} 94 | queryValues.Set("owns_qname", domainName) 95 | 96 | domains, _, err := s.getAll(ctx, queryValues) 97 | if err != nil { 98 | return nil, err 99 | } 100 | 101 | if len(domains) == 0 { 102 | return nil, &NotFoundError{Detail: "no responsible domain found"} 103 | } 104 | 105 | return &domains[0], nil 106 | } 107 | 108 | // getAll listing domains. 109 | // https://desec.readthedocs.io/en/latest/dns/domains.html#listing-domains 110 | func (s *DomainsService) getAll(ctx context.Context, query url.Values) ([]Domain, *Cursors, error) { 111 | endpoint, err := s.client.createEndpoint("domains") 112 | if err != nil { 113 | return nil, nil, fmt.Errorf("failed to create endpoint: %w", err) 114 | } 115 | 116 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 117 | if err != nil { 118 | return nil, nil, err 119 | } 120 | 121 | if len(query) > 0 { 122 | req.URL.RawQuery = query.Encode() 123 | } 124 | 125 | resp, err := s.client.httpClient.Do(req) 126 | if err != nil { 127 | return nil, nil, fmt.Errorf("failed to call API: %w", err) 128 | } 129 | 130 | defer func() { _ = resp.Body.Close() }() 131 | 132 | if resp.StatusCode != http.StatusOK { 133 | return nil, nil, handleError(resp) 134 | } 135 | 136 | cursors, err := parseCursor(resp.Header) 137 | if err != nil { 138 | return nil, nil, err 139 | } 140 | 141 | var domains []Domain 142 | 143 | err = handleResponse(resp, &domains) 144 | if err != nil { 145 | return nil, nil, err 146 | } 147 | 148 | return domains, cursors, nil 149 | } 150 | 151 | // Get retrieving a specific domain. 152 | // https://desec.readthedocs.io/en/latest/dns/domains.html#retrieving-a-specific-domain 153 | func (s *DomainsService) Get(ctx context.Context, domainName string) (*Domain, error) { 154 | endpoint, err := s.client.createEndpoint("domains", domainName) 155 | if err != nil { 156 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 157 | } 158 | 159 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 160 | if err != nil { 161 | return nil, err 162 | } 163 | 164 | resp, err := s.client.httpClient.Do(req) 165 | if err != nil { 166 | return nil, fmt.Errorf("failed to call API: %w", err) 167 | } 168 | 169 | defer func() { _ = resp.Body.Close() }() 170 | 171 | if resp.StatusCode != http.StatusOK { 172 | return nil, handleError(resp) 173 | } 174 | 175 | var domains Domain 176 | 177 | err = handleResponse(resp, &domains) 178 | if err != nil { 179 | return nil, err 180 | } 181 | 182 | return &domains, nil 183 | } 184 | 185 | // Delete deleting a domain. 186 | // https://desec.readthedocs.io/en/latest/dns/domains.html#deleting-a-domain 187 | func (s *DomainsService) Delete(ctx context.Context, domainName string) error { 188 | endpoint, err := s.client.createEndpoint("domains", domainName) 189 | if err != nil { 190 | return fmt.Errorf("failed to create endpoint: %w", err) 191 | } 192 | 193 | req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) 194 | if err != nil { 195 | return err 196 | } 197 | 198 | resp, err := s.client.httpClient.Do(req) 199 | if err != nil { 200 | return fmt.Errorf("failed to call API: %w", err) 201 | } 202 | 203 | defer func() { _ = resp.Body.Close() }() 204 | 205 | if resp.StatusCode != http.StatusNoContent { 206 | return handleError(resp) 207 | } 208 | 209 | return nil 210 | } 211 | -------------------------------------------------------------------------------- /tokens.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "time" 8 | ) 9 | 10 | // Token a token representation. 11 | // 12 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-field-reference 13 | type Token struct { 14 | ID string `json:"id,omitempty"` 15 | Created *time.Time `json:"created,omitempty"` 16 | LastUsed *time.Time `json:"last_used,omitempty"` 17 | Owner string `json:"owner,omitempty"` 18 | UserOverride string `json:"user_override,omitempty"` 19 | Name string `json:"name,omitempty"` 20 | PermCreateDomain bool `json:"perm_create_domain"` 21 | PermDeleteDomain bool `json:"perm_delete_domain"` 22 | PermManageTokens bool `json:"perm_manage_tokens"` 23 | IsValid bool `json:"is_valid,omitempty"` 24 | AllowedSubnets []string `json:"allowed_subnets,omitempty"` 25 | AutoPolicy bool `json:"auto_policy"` 26 | Value string `json:"token,omitempty"` 27 | // Not currently implemented 28 | // MaxAge *time.Duration `json:"name,omitempty"` 29 | // MaxUnusedPeriod *time.Duration `json:"name,omitempty"` 30 | } 31 | 32 | // TokensService handles communication with the tokens related methods of the deSEC API. 33 | // 34 | // https://desec.readthedocs.io/en/latest/auth/tokens.html 35 | type TokensService struct { 36 | client *Client 37 | } 38 | 39 | // GetAll retrieving all current tokens. 40 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#retrieving-all-current-tokens 41 | func (s *TokensService) GetAll(ctx context.Context) ([]Token, error) { 42 | endpoint, err := s.client.createEndpoint("auth", "tokens") 43 | if err != nil { 44 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 45 | } 46 | 47 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | resp, err := s.client.httpClient.Do(req) 53 | if err != nil { 54 | return nil, fmt.Errorf("failed to call API: %w", err) 55 | } 56 | 57 | defer func() { _ = resp.Body.Close() }() 58 | 59 | if resp.StatusCode != http.StatusOK { 60 | return nil, handleError(resp) 61 | } 62 | 63 | var tokens []Token 64 | 65 | err = handleResponse(resp, &tokens) 66 | if err != nil { 67 | return nil, err 68 | } 69 | 70 | return tokens, nil 71 | } 72 | 73 | // Get retrieves a specific token. 74 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#retrieving-a-specific-token 75 | // NOTE: This method used to retrieve all policies for a token, that is now done by GetAll. 76 | func (s *TokensService) Get(ctx context.Context, id string) (*Token, error) { 77 | endpoint, err := s.client.createEndpoint("auth", "tokens", id) 78 | if err != nil { 79 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 80 | } 81 | 82 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 83 | if err != nil { 84 | return nil, err 85 | } 86 | 87 | resp, err := s.client.httpClient.Do(req) 88 | if err != nil { 89 | return nil, fmt.Errorf("failed to call API: %w", err) 90 | } 91 | 92 | defer func() { _ = resp.Body.Close() }() 93 | 94 | if resp.StatusCode == http.StatusNotFound { 95 | return nil, nil 96 | } 97 | 98 | if resp.StatusCode != http.StatusOK { 99 | return nil, handleError(resp) 100 | } 101 | 102 | token := &Token{} 103 | 104 | err = handleResponse(resp, token) 105 | if err != nil { 106 | return nil, err 107 | } 108 | 109 | return token, nil 110 | } 111 | 112 | // Create creates additional tokens. 113 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#create-additional-tokens 114 | func (s *TokensService) Create(ctx context.Context, name string) (*Token, error) { 115 | endpoint, err := s.client.createEndpoint("auth", "tokens") 116 | if err != nil { 117 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 118 | } 119 | 120 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Token{Name: name}) 121 | if err != nil { 122 | return nil, err 123 | } 124 | 125 | resp, err := s.client.httpClient.Do(req) 126 | if err != nil { 127 | return nil, fmt.Errorf("failed to call API: %w", err) 128 | } 129 | 130 | defer func() { _ = resp.Body.Close() }() 131 | 132 | if resp.StatusCode != http.StatusCreated { 133 | return nil, handleError(resp) 134 | } 135 | 136 | var token Token 137 | 138 | err = handleResponse(resp, &token) 139 | if err != nil { 140 | return nil, err 141 | } 142 | 143 | return &token, nil 144 | } 145 | 146 | // Update a token. 147 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#modifying-a-token 148 | func (s *TokensService) Update(ctx context.Context, id string, token *Token) (*Token, error) { 149 | endpoint, err := s.client.createEndpoint("auth", "tokens", id) 150 | if err != nil { 151 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 152 | } 153 | 154 | // Copy values, including only fields that can be modified 155 | req, err := s.client.newRequest(ctx, http.MethodPatch, endpoint, Token{ 156 | Owner: token.Owner, 157 | UserOverride: token.UserOverride, 158 | Name: token.Name, 159 | PermCreateDomain: token.PermCreateDomain, 160 | PermDeleteDomain: token.PermDeleteDomain, 161 | PermManageTokens: token.PermManageTokens, 162 | AllowedSubnets: token.AllowedSubnets, 163 | AutoPolicy: token.AutoPolicy, 164 | }) 165 | if err != nil { 166 | return nil, err 167 | } 168 | 169 | resp, err := s.client.httpClient.Do(req) 170 | if err != nil { 171 | return nil, fmt.Errorf("failed to call API: %w", err) 172 | } 173 | 174 | defer func() { _ = resp.Body.Close() }() 175 | 176 | if resp.StatusCode != http.StatusOK { 177 | return nil, handleError(resp) 178 | } 179 | 180 | result := &Token{} 181 | 182 | err = handleResponse(resp, result) 183 | if err != nil { 184 | return nil, err 185 | } 186 | 187 | return result, nil 188 | } 189 | 190 | // Delete deletes tokens. 191 | // https://desec.readthedocs.io/en/latest/auth/tokens.html#delete-tokens 192 | func (s *TokensService) Delete(ctx context.Context, tokenID string) error { 193 | endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID) 194 | if err != nil { 195 | return fmt.Errorf("failed to create endpoint: %w", err) 196 | } 197 | 198 | req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) 199 | if err != nil { 200 | return err 201 | } 202 | 203 | resp, err := s.client.httpClient.Do(req) 204 | if err != nil { 205 | return fmt.Errorf("failed to call API: %w", err) 206 | } 207 | 208 | defer func() { _ = resp.Body.Close() }() 209 | 210 | if resp.StatusCode != http.StatusNoContent { 211 | return handleError(resp) 212 | } 213 | 214 | return nil 215 | } 216 | -------------------------------------------------------------------------------- /records_test.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "net/http" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | func TestRecordsService_Create(t *testing.T) { 14 | client, mux := setupTest(t, "token") 15 | 16 | mux.HandleFunc("POST /domains/example.dedyn.io/rrsets/", 17 | fromFixtures("records_create.json", http.StatusCreated)) 18 | 19 | record := RRSet{ 20 | Name: "", 21 | Domain: "example.dedyn.io", 22 | SubName: "_acme-challenge", 23 | Type: "TXT", 24 | Records: []string{`"txt"`}, 25 | TTL: 300, 26 | } 27 | 28 | newRecord, err := client.Records.Create(context.Background(), record) 29 | require.NoError(t, err) 30 | 31 | expected := &RRSet{ 32 | Name: "_acme-challenge.example.dedyn.io.", 33 | Domain: "example.dedyn.io", 34 | SubName: "_acme-challenge", 35 | Type: "TXT", 36 | Records: []string{`"txt"`}, 37 | TTL: 300, 38 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 39 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 40 | } 41 | assert.Equal(t, expected, newRecord) 42 | } 43 | 44 | func TestRecordsService_Delete(t *testing.T) { 45 | client, mux := setupTest(t, "token") 46 | 47 | mux.HandleFunc("DELETE /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, _ *http.Request) { 48 | rw.WriteHeader(http.StatusNoContent) 49 | }) 50 | 51 | err := client.Records.Delete(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT") 52 | require.NoError(t, err) 53 | } 54 | 55 | func TestRecordsService_Get(t *testing.T) { 56 | client, mux := setupTest(t, "token") 57 | 58 | mux.HandleFunc("GET /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", 59 | fromFixtures("records_get.json", http.StatusOK)) 60 | 61 | record, err := client.Records.Get(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT") 62 | require.NoError(t, err) 63 | 64 | expected := &RRSet{ 65 | Name: "_acme-challenge.example.dedyn.io.", 66 | Domain: "example.dedyn.io", 67 | SubName: "_acme-challenge", 68 | Type: "TXT", 69 | Records: []string{`"txt"`}, 70 | TTL: 300, 71 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 72 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 73 | } 74 | assert.Equal(t, expected, record) 75 | } 76 | 77 | func TestRecordsService_Update(t *testing.T) { 78 | client, mux := setupTest(t, "token") 79 | 80 | mux.HandleFunc("PATCH /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", 81 | fromFixtures("records_update.json", http.StatusOK)) 82 | 83 | rrSet := RRSet{ 84 | Records: []string{`"updated"`}, 85 | } 86 | 87 | updatedRecord, err := client.Records.Update(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT", rrSet) 88 | require.NoError(t, err) 89 | 90 | expected := &RRSet{ 91 | Name: "_acme-challenge.example.dedyn.io.", 92 | Domain: "example.dedyn.io", 93 | SubName: "_acme-challenge", 94 | Type: "TXT", 95 | Records: []string{`"updated"`}, 96 | TTL: 300, 97 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 98 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 99 | } 100 | assert.Equal(t, expected, updatedRecord) 101 | } 102 | 103 | func TestRecordsService_Replace(t *testing.T) { 104 | client, mux := setupTest(t, "token") 105 | 106 | mux.HandleFunc("PUT /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", 107 | fromFixtures("records_replace.json", http.StatusOK)) 108 | 109 | rrSet := RRSet{ 110 | Name: "_acme-challenge.example.dedyn.io.", 111 | Domain: "example.dedyn.io", 112 | SubName: "_acme-challenge", 113 | Type: "TXT", 114 | Records: []string{`"updated"`}, 115 | TTL: 0, 116 | Created: nil, 117 | } 118 | 119 | updatedRecord, err := client.Records.Replace(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT", rrSet) 120 | require.NoError(t, err) 121 | 122 | expected := &RRSet{ 123 | Name: "_acme-challenge.example.dedyn.io.", 124 | Domain: "example.dedyn.io", 125 | SubName: "_acme-challenge", 126 | Type: "TXT", 127 | Records: []string{`"updated"`}, 128 | TTL: 300, 129 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 130 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 131 | } 132 | assert.Equal(t, expected, updatedRecord) 133 | } 134 | 135 | func TestRecordsService_GetAll(t *testing.T) { 136 | client, mux := setupTest(t, "token") 137 | 138 | mux.HandleFunc("GET /domains/example.dedyn.io/rrsets/", 139 | fromFixtures("records_getall.json", http.StatusOK)) 140 | 141 | records, err := client.Records.GetAll(context.Background(), "example.dedyn.io", nil) 142 | require.NoError(t, err) 143 | 144 | expected := []RRSet{ 145 | { 146 | Name: "example.dedyn.io.", 147 | Domain: "example.dedyn.io", 148 | SubName: "", 149 | Type: "A", 150 | Records: []string{"10.10.10.10"}, 151 | TTL: 60, 152 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 153 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 154 | }, 155 | { 156 | Name: "example.dedyn.io.", 157 | Domain: "example.dedyn.io", 158 | SubName: "", 159 | Type: "NS", 160 | Records: []string{"ns1.desec.io.", "ns2.desec.org."}, 161 | TTL: 3600, 162 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 163 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 164 | }, 165 | } 166 | assert.Equal(t, expected, records) 167 | } 168 | 169 | func TestRecordsService_BulkCreate(t *testing.T) { 170 | client, mux := setupTest(t, "token") 171 | 172 | mux.HandleFunc("POST /domains/example.dedyn.io/rrsets/", 173 | fromFixtures("records_create_bulk.json", http.StatusCreated)) 174 | 175 | rrSets := []RRSet{{ 176 | Name: "", 177 | SubName: "_acme-challenge", 178 | Type: "TXT", 179 | Records: []string{`"txt"`}, 180 | TTL: 300, 181 | }} 182 | 183 | newRecords, err := client.Records.BulkCreate(context.Background(), "example.dedyn.io", rrSets) 184 | require.NoError(t, err) 185 | 186 | expected := []RRSet{{ 187 | Name: "_acme-challenge.example.dedyn.io.", 188 | Domain: "example.dedyn.io", 189 | SubName: "_acme-challenge", 190 | Type: "TXT", 191 | Records: []string{`"txt"`}, 192 | TTL: 300, 193 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 194 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 195 | }} 196 | assert.Equal(t, expected, newRecords) 197 | } 198 | 199 | func TestRecordsService_BulkDelete(t *testing.T) { 200 | client, mux := setupTest(t, "token") 201 | 202 | mux.HandleFunc("PUT /domains/example.dedyn.io/rrsets/", 203 | func(rw http.ResponseWriter, req *http.Request) { 204 | defer func() { _ = req.Body.Close() }() 205 | 206 | var rrSets []RRSet 207 | if err := json.NewDecoder(req.Body).Decode(&rrSets); err != nil { 208 | http.Error(rw, "cannot unmarshal request body", http.StatusBadRequest) 209 | return 210 | } 211 | 212 | if len(rrSets) != 1 && rrSets[0].SubName != "_acme-challenge" && rrSets[0].Type != "TXT" && len(rrSets[0].Records) != 0 { 213 | http.Error(rw, "incorrect request body", http.StatusBadRequest) 214 | return 215 | } 216 | 217 | rw.WriteHeader(http.StatusOK) 218 | }) 219 | 220 | rrSets := []RRSet{{ 221 | Name: "", 222 | SubName: "_acme-challenge", 223 | Type: "TXT", 224 | Records: []string{`"txt"`}, 225 | TTL: 300, 226 | }} 227 | 228 | err := client.Records.BulkDelete(context.Background(), "example.dedyn.io", rrSets) 229 | require.NoError(t, err) 230 | } 231 | 232 | func TestRecordsService_BulkUpdate(t *testing.T) { 233 | client, mux := setupTest(t, "token") 234 | 235 | mux.HandleFunc("PUT /domains/example.dedyn.io/rrsets/", 236 | fromFixtures("records_update_bulk.json", http.StatusOK)) 237 | 238 | rrSets := []RRSet{{ 239 | SubName: "_acme-challenge", 240 | Type: "TXT", 241 | Records: []string{`"updated"`}, 242 | TTL: 300, 243 | }} 244 | 245 | updatedRecord, err := client.Records.BulkUpdate(context.Background(), FullResource, "example.dedyn.io", rrSets) 246 | require.NoError(t, err) 247 | 248 | expected := []RRSet{{ 249 | Name: "_acme-challenge.example.dedyn.io.", 250 | Domain: "example.dedyn.io", 251 | SubName: "_acme-challenge", 252 | Type: "TXT", 253 | Records: []string{`"updated"`}, 254 | TTL: 300, 255 | Created: mustParseTime("2020-05-06T11:46:07.641885Z"), 256 | Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), 257 | }} 258 | assert.Equal(t, expected, updatedRecord) 259 | } 260 | -------------------------------------------------------------------------------- /account.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "time" 8 | ) 9 | 10 | // Account an account representation. 11 | type Account struct { 12 | Email string `json:"email"` 13 | Password string `json:"password"` 14 | LimitDomains int `json:"limit_domains,omitempty"` 15 | Created *time.Time `json:"created,omitempty"` 16 | } 17 | 18 | // Captcha a captcha representation. 19 | type Captcha struct { 20 | ID string `json:"id,omitempty"` 21 | Challenge string `json:"challenge,omitempty"` 22 | Solution string `json:"solution,omitempty"` 23 | } 24 | 25 | // Registration a registration representation. 26 | type Registration struct { 27 | Email string `json:"email,omitempty"` 28 | Password string `json:"password,omitempty"` 29 | NewEmail string `json:"new_email,omitempty"` 30 | Captcha *Captcha `json:"captcha,omitempty"` 31 | } 32 | 33 | // AccountService handles communication with the account related methods of the deSEC API. 34 | // 35 | // https://desec.readthedocs.io/en/latest/auth/account.html 36 | type AccountService struct { 37 | client *Client 38 | } 39 | 40 | // Login Log in. 41 | // https://desec.readthedocs.io/en/latest/auth/account.html#log-in 42 | func (s *AccountService) Login(ctx context.Context, email, password string) (*Token, error) { 43 | endpoint, err := s.client.createEndpoint("auth", "login") 44 | if err != nil { 45 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 46 | } 47 | 48 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Account{Email: email, Password: password}) 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | resp, err := s.client.httpClient.Do(req) 54 | if err != nil { 55 | return nil, fmt.Errorf("failed to call API: %w", err) 56 | } 57 | 58 | defer func() { _ = resp.Body.Close() }() 59 | 60 | if resp.StatusCode != http.StatusOK { 61 | return nil, handleError(resp) 62 | } 63 | 64 | var token Token 65 | 66 | err = handleResponse(resp, &token) 67 | if err != nil { 68 | return nil, err 69 | } 70 | 71 | s.client.token = token.Value 72 | 73 | return &token, nil 74 | } 75 | 76 | // Logout log out (= delete current token). 77 | // https://desec.readthedocs.io/en/latest/auth/account.html#log-out 78 | func (s *AccountService) Logout(ctx context.Context) error { 79 | endpoint, err := s.client.createEndpoint("auth", "logout") 80 | if err != nil { 81 | return fmt.Errorf("failed to create endpoint: %w", err) 82 | } 83 | 84 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, nil) 85 | if err != nil { 86 | return err 87 | } 88 | 89 | resp, err := s.client.httpClient.Do(req) 90 | if err != nil { 91 | return fmt.Errorf("failed to call API: %w", err) 92 | } 93 | 94 | defer func() { _ = resp.Body.Close() }() 95 | 96 | if resp.StatusCode != http.StatusNoContent { 97 | return handleError(resp) 98 | } 99 | 100 | s.client.token = "" 101 | 102 | return nil 103 | } 104 | 105 | // ObtainCaptcha Obtain a captcha. 106 | // https://desec.readthedocs.io/en/latest/auth/account.html#obtain-a-captcha 107 | func (s *AccountService) ObtainCaptcha(ctx context.Context) (*Captcha, error) { 108 | endpoint, err := s.client.createEndpoint("captcha") 109 | if err != nil { 110 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 111 | } 112 | 113 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, nil) 114 | if err != nil { 115 | return nil, err 116 | } 117 | 118 | resp, err := s.client.httpClient.Do(req) 119 | if err != nil { 120 | return nil, fmt.Errorf("failed to call API: %w", err) 121 | } 122 | 123 | defer func() { _ = resp.Body.Close() }() 124 | 125 | if resp.StatusCode != http.StatusOK { 126 | return nil, handleError(resp) 127 | } 128 | 129 | var captcha Captcha 130 | 131 | err = handleResponse(resp, &captcha) 132 | if err != nil { 133 | return nil, err 134 | } 135 | 136 | return &captcha, nil 137 | } 138 | 139 | // Register register account. 140 | // https://desec.readthedocs.io/en/latest/auth/account.html#register-account 141 | func (s *AccountService) Register(ctx context.Context, registration Registration) error { 142 | endpoint, err := s.client.createEndpoint("auth") 143 | if err != nil { 144 | return fmt.Errorf("failed to create endpoint: %w", err) 145 | } 146 | 147 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, registration) 148 | if err != nil { 149 | return err 150 | } 151 | 152 | resp, err := s.client.httpClient.Do(req) 153 | if err != nil { 154 | return fmt.Errorf("failed to call API: %w", err) 155 | } 156 | 157 | defer func() { _ = resp.Body.Close() }() 158 | 159 | if resp.StatusCode != http.StatusAccepted { 160 | return handleError(resp) 161 | } 162 | 163 | return nil 164 | } 165 | 166 | // RetrieveInformation retrieve account information. 167 | // https://desec.readthedocs.io/en/latest/auth/account.html#retrieve-account-information 168 | func (s *AccountService) RetrieveInformation(ctx context.Context) (*Account, error) { 169 | endpoint, err := s.client.createEndpoint("auth", "account") 170 | if err != nil { 171 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 172 | } 173 | 174 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, nil) 175 | if err != nil { 176 | return nil, err 177 | } 178 | 179 | resp, err := s.client.httpClient.Do(req) 180 | if err != nil { 181 | return nil, fmt.Errorf("failed to call API: %w", err) 182 | } 183 | 184 | defer func() { _ = resp.Body.Close() }() 185 | 186 | if resp.StatusCode != http.StatusOK { 187 | return nil, handleError(resp) 188 | } 189 | 190 | var account Account 191 | 192 | err = handleResponse(resp, &account) 193 | if err != nil { 194 | return nil, err 195 | } 196 | 197 | return &account, nil 198 | } 199 | 200 | // PasswordReset password reset and password change. 201 | // https://desec.readthedocs.io/en/latest/auth/account.html#password-reset 202 | // https://desec.readthedocs.io/en/latest/auth/account.html#password-change 203 | func (s *AccountService) PasswordReset(ctx context.Context, email string, captcha Captcha) error { 204 | endpoint, err := s.client.createEndpoint("auth", "account", "reset-password") 205 | if err != nil { 206 | return fmt.Errorf("failed to create endpoint: %w", err) 207 | } 208 | 209 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Registration{Email: email, Captcha: &captcha}) 210 | if err != nil { 211 | return err 212 | } 213 | 214 | resp, err := s.client.httpClient.Do(req) 215 | if err != nil { 216 | return fmt.Errorf("failed to call API: %w", err) 217 | } 218 | 219 | defer func() { _ = resp.Body.Close() }() 220 | 221 | if resp.StatusCode != http.StatusAccepted { 222 | return handleError(resp) 223 | } 224 | 225 | return nil 226 | } 227 | 228 | // ChangeEmail changes email address. 229 | // https://desec.readthedocs.io/en/latest/auth/account.html#change-email-address 230 | func (s *AccountService) ChangeEmail(ctx context.Context, email, password, newEmail string) error { 231 | endpoint, err := s.client.createEndpoint("auth", "account", "change-email") 232 | if err != nil { 233 | return fmt.Errorf("failed to create endpoint: %w", err) 234 | } 235 | 236 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Registration{Email: email, Password: password, NewEmail: newEmail}) 237 | if err != nil { 238 | return err 239 | } 240 | 241 | resp, err := s.client.httpClient.Do(req) 242 | if err != nil { 243 | return fmt.Errorf("failed to call API: %w", err) 244 | } 245 | 246 | defer func() { _ = resp.Body.Close() }() 247 | 248 | if resp.StatusCode != http.StatusAccepted { 249 | return handleError(resp) 250 | } 251 | 252 | return nil 253 | } 254 | 255 | // Delete deletes account. 256 | // https://desec.readthedocs.io/en/latest/auth/account.html#delete-account 257 | func (s *AccountService) Delete(ctx context.Context, email, password string) error { 258 | endpoint, err := s.client.createEndpoint("auth", "account", "delete") 259 | if err != nil { 260 | return fmt.Errorf("failed to create endpoint: %w", err) 261 | } 262 | 263 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Account{Email: email, Password: password}) 264 | if err != nil { 265 | return err 266 | } 267 | 268 | resp, err := s.client.httpClient.Do(req) 269 | if err != nil { 270 | return fmt.Errorf("failed to call API: %w", err) 271 | } 272 | 273 | defer func() { _ = resp.Body.Close() }() 274 | 275 | if resp.StatusCode != http.StatusAccepted { 276 | return handleError(resp) 277 | } 278 | 279 | return nil 280 | } 281 | -------------------------------------------------------------------------------- /records.go: -------------------------------------------------------------------------------- 1 | package desec 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "net/url" 8 | "time" 9 | ) 10 | 11 | // ApexZone apex zone name. 12 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#accessing-the-zone-apex 13 | const ApexZone = "@" 14 | 15 | // IgnoreFilter is a specific value used to ignore a filter field. 16 | const IgnoreFilter = "#IGNORE#" 17 | 18 | // RRSet DNS Record Set. 19 | type RRSet struct { 20 | Name string `json:"name,omitempty"` 21 | Domain string `json:"domain,omitempty"` 22 | SubName string `json:"subname,omitempty"` 23 | Type string `json:"type,omitempty"` 24 | Records []string `json:"records"` 25 | TTL int `json:"ttl,omitempty"` 26 | Created *time.Time `json:"created,omitempty"` 27 | Touched *time.Time `json:"touched,omitempty"` 28 | } 29 | 30 | // RRSetFilter a RRSets filter. 31 | type RRSetFilter struct { 32 | Type string 33 | SubName string 34 | } 35 | 36 | // FilterRRSetOnlyOnType creates an RRSetFilter that ignore SubName. 37 | func FilterRRSetOnlyOnType(t string) RRSetFilter { 38 | return RRSetFilter{ 39 | Type: t, 40 | SubName: IgnoreFilter, 41 | } 42 | } 43 | 44 | // FilterRRSetOnlyOnSubName creates an RRSetFilter that ignore Type. 45 | func FilterRRSetOnlyOnSubName(n string) RRSetFilter { 46 | return RRSetFilter{ 47 | Type: IgnoreFilter, 48 | SubName: n, 49 | } 50 | } 51 | 52 | // RecordsService handles communication with the records related methods of the deSEC API. 53 | // 54 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html 55 | type RecordsService struct { 56 | client *Client 57 | } 58 | 59 | /* 60 | Domains 61 | */ 62 | 63 | // GetAll retrieving all RRSets in a zone. 64 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-all-rrsets-in-a-zone 65 | func (s *RecordsService) GetAll(ctx context.Context, domainName string, filter *RRSetFilter) ([]RRSet, error) { 66 | rrSets, _, err := s.GetAllPaginated(ctx, domainName, filter, "") 67 | if err != nil { 68 | return nil, err 69 | } 70 | 71 | return rrSets, nil 72 | } 73 | 74 | // GetAllPaginated retrieving all RRSets in a zone. 75 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-all-rrsets-in-a-zone 76 | func (s *RecordsService) GetAllPaginated(ctx context.Context, domainName string, filter *RRSetFilter, cursor string) ([]RRSet, *Cursors, error) { 77 | queryValues := url.Values{} 78 | 79 | if filter != nil { 80 | if filter.Type != IgnoreFilter { 81 | queryValues.Set("type", filter.Type) 82 | } 83 | 84 | if filter.SubName != IgnoreFilter { 85 | queryValues.Set("subname", filter.SubName) 86 | } 87 | } 88 | 89 | queryValues.Set("cursor", cursor) 90 | 91 | rrSets, cursors, err := s.getAll(ctx, domainName, queryValues) 92 | if err != nil { 93 | return nil, nil, err 94 | } 95 | 96 | return rrSets, cursors, nil 97 | } 98 | 99 | func (s *RecordsService) getAll(ctx context.Context, domainName string, query url.Values) ([]RRSet, *Cursors, error) { 100 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") 101 | if err != nil { 102 | return nil, nil, fmt.Errorf("failed to create endpoint: %w", err) 103 | } 104 | 105 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 106 | if err != nil { 107 | return nil, nil, err 108 | } 109 | 110 | if len(query) > 0 { 111 | req.URL.RawQuery = query.Encode() 112 | } 113 | 114 | resp, err := s.client.httpClient.Do(req) 115 | if err != nil { 116 | return nil, nil, fmt.Errorf("failed to call API: %w", err) 117 | } 118 | 119 | defer func() { _ = resp.Body.Close() }() 120 | 121 | if resp.StatusCode != http.StatusOK { 122 | return nil, nil, handleError(resp) 123 | } 124 | 125 | cursors, err := parseCursor(resp.Header) 126 | if err != nil { 127 | return nil, nil, err 128 | } 129 | 130 | var rrSets []RRSet 131 | 132 | err = handleResponse(resp, &rrSets) 133 | if err != nil { 134 | return nil, nil, err 135 | } 136 | 137 | return rrSets, cursors, nil 138 | } 139 | 140 | // Create creates a new RRSet. 141 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#creating-a-tlsa-rrset 142 | func (s *RecordsService) Create(ctx context.Context, rrSet RRSet) (*RRSet, error) { 143 | endpoint, err := s.client.createEndpoint("domains", rrSet.Domain, "rrsets") 144 | if err != nil { 145 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 146 | } 147 | 148 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, rrSet) 149 | if err != nil { 150 | return nil, err 151 | } 152 | 153 | resp, err := s.client.httpClient.Do(req) 154 | if err != nil { 155 | return nil, fmt.Errorf("failed to call API: %w", err) 156 | } 157 | 158 | defer func() { _ = resp.Body.Close() }() 159 | 160 | if resp.StatusCode != http.StatusCreated { 161 | return nil, handleError(resp) 162 | } 163 | 164 | var newRRSet RRSet 165 | 166 | err = handleResponse(resp, &newRRSet) 167 | if err != nil { 168 | return nil, err 169 | } 170 | 171 | return &newRRSet, nil 172 | } 173 | 174 | /* 175 | Domains + subname + type 176 | */ 177 | 178 | // Get gets a RRSet. 179 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-a-specific-rrset 180 | func (s *RecordsService) Get(ctx context.Context, domainName, subName, recordType string) (*RRSet, error) { 181 | if subName == "" { 182 | subName = ApexZone 183 | } 184 | 185 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) 186 | if err != nil { 187 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 188 | } 189 | 190 | req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) 191 | if err != nil { 192 | return nil, err 193 | } 194 | 195 | resp, err := s.client.httpClient.Do(req) 196 | if err != nil { 197 | return nil, fmt.Errorf("failed to call API: %w", err) 198 | } 199 | 200 | defer func() { _ = resp.Body.Close() }() 201 | 202 | if resp.StatusCode != http.StatusOK { 203 | return nil, handleError(resp) 204 | } 205 | 206 | var rrSet RRSet 207 | 208 | err = handleResponse(resp, &rrSet) 209 | if err != nil { 210 | return nil, err 211 | } 212 | 213 | return &rrSet, nil 214 | } 215 | 216 | // Update updates RRSet (PATCH). 217 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset 218 | func (s *RecordsService) Update(ctx context.Context, domainName, subName, recordType string, rrSet RRSet) (*RRSet, error) { 219 | if subName == "" { 220 | subName = ApexZone 221 | } 222 | 223 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) 224 | if err != nil { 225 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 226 | } 227 | 228 | req, err := s.client.newRequest(ctx, http.MethodPatch, endpoint, rrSet) 229 | if err != nil { 230 | return nil, err 231 | } 232 | 233 | resp, err := s.client.httpClient.Do(req) 234 | if err != nil { 235 | return nil, fmt.Errorf("failed to call API: %w", err) 236 | } 237 | 238 | defer func() { _ = resp.Body.Close() }() 239 | 240 | // when a RRSet is deleted (empty records) 241 | if resp.StatusCode == http.StatusNoContent { 242 | return nil, nil 243 | } 244 | 245 | if resp.StatusCode != http.StatusOK { 246 | return nil, handleError(resp) 247 | } 248 | 249 | var updatedRRSet RRSet 250 | 251 | err = handleResponse(resp, &updatedRRSet) 252 | if err != nil { 253 | return nil, err 254 | } 255 | 256 | return &updatedRRSet, nil 257 | } 258 | 259 | // Replace replaces a RRSet (PUT). 260 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset 261 | func (s *RecordsService) Replace(ctx context.Context, domainName, subName, recordType string, rrSet RRSet) (*RRSet, error) { 262 | if subName == "" { 263 | subName = ApexZone 264 | } 265 | 266 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) 267 | if err != nil { 268 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 269 | } 270 | 271 | req, err := s.client.newRequest(ctx, http.MethodPut, endpoint, rrSet) 272 | if err != nil { 273 | return nil, err 274 | } 275 | 276 | resp, err := s.client.httpClient.Do(req) 277 | if err != nil { 278 | return nil, fmt.Errorf("failed to call API: %w", err) 279 | } 280 | 281 | defer func() { _ = resp.Body.Close() }() 282 | 283 | // when a RRSet is deleted (empty records) 284 | if resp.StatusCode == http.StatusNoContent { 285 | return nil, nil 286 | } 287 | 288 | if resp.StatusCode != http.StatusOK { 289 | return nil, handleError(resp) 290 | } 291 | 292 | var updatedRRSet RRSet 293 | 294 | err = handleResponse(resp, &updatedRRSet) 295 | if err != nil { 296 | return nil, err 297 | } 298 | 299 | return &updatedRRSet, nil 300 | } 301 | 302 | // Delete deletes a RRSet. 303 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#deleting-an-rrset 304 | func (s *RecordsService) Delete(ctx context.Context, domainName, subName, recordType string) error { 305 | if subName == "" { 306 | subName = ApexZone 307 | } 308 | 309 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) 310 | if err != nil { 311 | return fmt.Errorf("failed to create endpoint: %w", err) 312 | } 313 | 314 | req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) 315 | if err != nil { 316 | return err 317 | } 318 | 319 | resp, err := s.client.httpClient.Do(req) 320 | if err != nil { 321 | return fmt.Errorf("failed to call API: %w", err) 322 | } 323 | 324 | defer func() { _ = resp.Body.Close() }() 325 | 326 | if resp.StatusCode != http.StatusNoContent { 327 | return handleError(resp) 328 | } 329 | 330 | return nil 331 | } 332 | 333 | /* 334 | Bulk operations 335 | */ 336 | 337 | // UpdateMode the mode used to bulk update operations. 338 | type UpdateMode string 339 | 340 | const ( 341 | // FullResource the full resource must be specified. 342 | FullResource UpdateMode = http.MethodPut 343 | // OnlyFields only fields you would like to modify need to be provided. 344 | OnlyFields UpdateMode = http.MethodPatch 345 | ) 346 | 347 | // BulkCreate creates new RRSets in bulk. 348 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#bulk-creation-of-rrsets 349 | func (s *RecordsService) BulkCreate(ctx context.Context, domainName string, rrSets []RRSet) ([]RRSet, error) { 350 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") 351 | if err != nil { 352 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 353 | } 354 | 355 | req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, rrSets) 356 | if err != nil { 357 | return nil, err 358 | } 359 | 360 | resp, err := s.client.httpClient.Do(req) 361 | if err != nil { 362 | return nil, fmt.Errorf("failed to call API: %w", err) 363 | } 364 | 365 | defer func() { _ = resp.Body.Close() }() 366 | 367 | if resp.StatusCode != http.StatusCreated { 368 | return nil, handleError(resp) 369 | } 370 | 371 | var newRRSets []RRSet 372 | 373 | err = handleResponse(resp, &newRRSets) 374 | if err != nil { 375 | return nil, err 376 | } 377 | 378 | return newRRSets, nil 379 | } 380 | 381 | // BulkUpdate updates RRSets in bulk. 382 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#bulk-modification-of-rrsets 383 | func (s *RecordsService) BulkUpdate(ctx context.Context, mode UpdateMode, domainName string, rrSets []RRSet) ([]RRSet, error) { 384 | endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") 385 | if err != nil { 386 | return nil, fmt.Errorf("failed to create endpoint: %w", err) 387 | } 388 | 389 | req, err := s.client.newRequest(ctx, string(mode), endpoint, rrSets) 390 | if err != nil { 391 | return nil, err 392 | } 393 | 394 | resp, err := s.client.httpClient.Do(req) 395 | if err != nil { 396 | return nil, fmt.Errorf("failed to call API: %w", err) 397 | } 398 | 399 | defer func() { _ = resp.Body.Close() }() 400 | 401 | if resp.StatusCode != http.StatusOK { 402 | return nil, handleError(resp) 403 | } 404 | 405 | var results []RRSet 406 | 407 | err = handleResponse(resp, &results) 408 | if err != nil { 409 | return nil, err 410 | } 411 | 412 | return results, nil 413 | } 414 | 415 | // BulkDelete deletes RRSets in bulk (uses FullResourceUpdateMode). 416 | // https://desec.readthedocs.io/en/latest/dns/rrsets.html#bulk-deletion-of-rrsets 417 | func (s *RecordsService) BulkDelete(ctx context.Context, domainName string, rrSets []RRSet) error { 418 | deleteRRSets := make([]RRSet, len(rrSets)) 419 | 420 | for i, rrSet := range rrSets { 421 | rrSet.Records = []string{} 422 | deleteRRSets[i] = rrSet 423 | } 424 | 425 | _, err := s.BulkUpdate(ctx, FullResource, domainName, deleteRRSets) 426 | if err != nil { 427 | return err 428 | } 429 | 430 | return nil 431 | } 432 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------