pax_global_header00006660000000000000000000000064152071331630014513gustar00rootroot0000000000000052 comment=5ab67d16a6fb756e972859bc89387c67985e2313 golang-github-nrdcg-desec-0.11.2/000077500000000000000000000000001520713316300164775ustar00rootroot00000000000000golang-github-nrdcg-desec-0.11.2/.github/000077500000000000000000000000001520713316300200375ustar00rootroot00000000000000golang-github-nrdcg-desec-0.11.2/.github/dependabot.yml000066400000000000000000000007761520713316300227010ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: gomod directory: "/" schedule: interval: monthly cooldown: default-days: 7 groups: go: patterns: - "*" # Group all updates into a single larger pull request. - package-ecosystem: github-actions directory: "/" schedule: interval: monthly cooldown: default-days: 7 groups: github-actions: patterns: - "*" # Group all updates into a single larger pull request. golang-github-nrdcg-desec-0.11.2/.github/workflows/000077500000000000000000000000001520713316300220745ustar00rootroot00000000000000golang-github-nrdcg-desec-0.11.2/.github/workflows/go-cross.yml000066400000000000000000000012201520713316300243460ustar00rootroot00000000000000name: Go Matrix on: push: branches: - main pull_request: branches: - main permissions: {} jobs: cross: name: Go runs-on: ${{ matrix.os }} env: CGO_ENABLED: 0 strategy: matrix: go-version: [ oldstable, stable] os: [ubuntu-latest, macos-latest, windows-latest] steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: actions/setup-go@v6 with: go-version: ${{ matrix.go-version }} - name: Test run: go test -v -cover ./... - name: Build run: go build -v -ldflags "-s -w" -trimpath golang-github-nrdcg-desec-0.11.2/.github/workflows/main.yml000066400000000000000000000014611520713316300235450ustar00rootroot00000000000000name: Main on: push: branches: - main pull_request: branches: - main permissions: {} jobs: main: name: Main Process runs-on: ubuntu-latest env: GO_VERSION: stable GOLANGCI_LINT_VERSION: v2.11 CGO_ENABLED: 0 steps: - uses: actions/checkout@v6 with: fetch-depth: 0 persist-credentials: false - uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} - name: Check and get dependencies run: | go mod tidy --diff - name: Install golangci-lint ${{ env.GOLANGCI_LINT_VERSION }} uses: golangci/golangci-lint-action@v9 with: version: ${{ env.GOLANGCI_LINT_VERSION }} install-only: true - name: Make run: make golang-github-nrdcg-desec-0.11.2/.gitignore000066400000000000000000000000071520713316300204640ustar00rootroot00000000000000.idea/ golang-github-nrdcg-desec-0.11.2/.golangci.yml000066400000000000000000000034161520713316300210670ustar00rootroot00000000000000version: "2" formatters: enable: - gci - gofumpt settings: gofumpt: extra-rules: true linters: default: all disable: - cyclop # duplicate of gocyclo - dupl - err113 - exhaustive - exhaustruct - forcetypeassert - funcorder - lll - mnd - nilnil - nlreturn - noinlineerr - paralleltest - prealloc - rowserrcheck # not relevant (SQL) - sqlclosecheck # not relevant (SQL) - testpackage - tparallel - varnamelen - wrapcheck - wsl # deprecated settings: depguard: rules: main: deny: - pkg: github.com/instana/testify desc: not allowed - pkg: github.com/pkg/errors desc: Should be replaced by standard lib errors package funlen: lines: -1 statements: 40 goconst: min-len: 5 min-occurrences: 3 gocritic: disabled-checks: - sloppyReassign - rangeValCopy - octalLiteral - paramTypeCombine # already handle by gofumpt.extra-rules enabled-tags: - diagnostic - style - performance settings: hugeParam: sizeThreshold: 120 gocyclo: min-complexity: 15 godox: keywords: - FIXME govet: disable: - fieldalignment enable-all: true misspell: locale: US tagliatelle: case: rules: json: snake perfsprint: err-error: true errorf: true sprintf1: true strconcat: false exclusions: warn-unused: true presets: - comments - std-error-handling rules: - linters: - funlen path: .*_test.go issues: max-issues-per-linter: 0 max-same-issues: 0 golang-github-nrdcg-desec-0.11.2/LICENSE000066400000000000000000000405251520713316300175120ustar00rootroot00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. golang-github-nrdcg-desec-0.11.2/Makefile000066400000000000000000000002561520713316300201420ustar00rootroot00000000000000.PHONY: default clean check test default: clean check test build test: clean go test -v -cover ./... clean: rm -f cover.out build: go build check: golangci-lint run golang-github-nrdcg-desec-0.11.2/account.go000066400000000000000000000160631520713316300204700ustar00rootroot00000000000000package desec import ( "context" "fmt" "net/http" "time" ) // Account an account representation. type Account struct { Email string `json:"email"` Password string `json:"password"` LimitDomains int `json:"limit_domains,omitempty"` Created *time.Time `json:"created,omitempty"` } // Captcha a captcha representation. type Captcha struct { ID string `json:"id,omitempty"` Challenge string `json:"challenge,omitempty"` Solution string `json:"solution,omitempty"` } // Registration a registration representation. type Registration struct { Email string `json:"email,omitempty"` Password string `json:"password,omitempty"` NewEmail string `json:"new_email,omitempty"` Captcha *Captcha `json:"captcha,omitempty"` } // AccountService handles communication with the account related methods of the deSEC API. // // https://desec.readthedocs.io/en/latest/auth/account.html type AccountService struct { client *Client } // Login Log in. // https://desec.readthedocs.io/en/latest/auth/account.html#log-in func (s *AccountService) Login(ctx context.Context, email, password string) (*Token, error) { endpoint, err := s.client.createEndpoint("auth", "login") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Account{Email: email, Password: password}) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var token Token err = handleResponse(resp, &token) if err != nil { return nil, err } s.client.token = token.Value return &token, nil } // Logout log out (= delete current token). // https://desec.readthedocs.io/en/latest/auth/account.html#log-out func (s *AccountService) Logout(ctx context.Context) error { endpoint, err := s.client.createEndpoint("auth", "logout") if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, nil) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusNoContent { return handleError(resp) } s.client.token = "" return nil } // ObtainCaptcha Obtain a captcha. // https://desec.readthedocs.io/en/latest/auth/account.html#obtain-a-captcha func (s *AccountService) ObtainCaptcha(ctx context.Context) (*Captcha, error) { endpoint, err := s.client.createEndpoint("captcha") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var captcha Captcha err = handleResponse(resp, &captcha) if err != nil { return nil, err } return &captcha, nil } // Register register account. // https://desec.readthedocs.io/en/latest/auth/account.html#register-account func (s *AccountService) Register(ctx context.Context, registration Registration) error { endpoint, err := s.client.createEndpoint("auth") if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, registration) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusAccepted { return handleError(resp) } return nil } // RetrieveInformation retrieve account information. // https://desec.readthedocs.io/en/latest/auth/account.html#retrieve-account-information func (s *AccountService) RetrieveInformation(ctx context.Context) (*Account, error) { endpoint, err := s.client.createEndpoint("auth", "account") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var account Account err = handleResponse(resp, &account) if err != nil { return nil, err } return &account, nil } // PasswordReset password reset and password change. // https://desec.readthedocs.io/en/latest/auth/account.html#password-reset // https://desec.readthedocs.io/en/latest/auth/account.html#password-change func (s *AccountService) PasswordReset(ctx context.Context, email string, captcha Captcha) error { endpoint, err := s.client.createEndpoint("auth", "account", "reset-password") if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Registration{Email: email, Captcha: &captcha}) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusAccepted { return handleError(resp) } return nil } // ChangeEmail changes email address. // https://desec.readthedocs.io/en/latest/auth/account.html#change-email-address func (s *AccountService) ChangeEmail(ctx context.Context, email, password, newEmail string) error { endpoint, err := s.client.createEndpoint("auth", "account", "change-email") if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Registration{Email: email, Password: password, NewEmail: newEmail}) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusAccepted { return handleError(resp) } return nil } // Delete deletes account. // https://desec.readthedocs.io/en/latest/auth/account.html#delete-account func (s *AccountService) Delete(ctx context.Context, email, password string) error { endpoint, err := s.client.createEndpoint("auth", "account", "delete") if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Account{Email: email, Password: password}) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusAccepted { return handleError(resp) } return nil } golang-github-nrdcg-desec-0.11.2/account_test.go000066400000000000000000000070321520713316300215230ustar00rootroot00000000000000package desec import ( "context" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAccountClient_ObtainCaptcha(t *testing.T) { client, mux := setupTest(t, "") mux.HandleFunc("POST /captcha/", fromFixtures("accounts_captcha.json", http.StatusOK)) captcha, err := client.Account.ObtainCaptcha(context.Background()) require.NoError(t, err) expected := &Captcha{ ID: "aaa", Challenge: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8zxD3EwAFuwJYQcBz5wAAAABJRU5ErkJggg==", } assert.Equal(t, expected, captcha) } func TestAccountClient_Register(t *testing.T) { client, mux := setupTest(t, "") mux.HandleFunc("POST /auth/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusAccepted) }) registration := Registration{ Email: "email@example.com", Password: "secret", Captcha: &Captcha{ ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", Solution: "12H45", }, } err := client.Account.Register(context.Background(), registration) require.NoError(t, err) } func TestAccountClient_Login(t *testing.T) { client, mux := setupTest(t, "") mux.HandleFunc("POST /auth/login/", fromFixtures("accounts_login.json", http.StatusOK)) token, err := client.Account.Login(context.Background(), "email@example.com", "secret") require.NoError(t, err) expected := &Token{ ID: "8f9cbae2-c862-48a4-b3f0-2cb1a80df168", Name: "login", Value: "f07Q0TRmEb-CRWPe4h64_iV2jbet", Created: mustParseTime("2018-09-06T09:07:43.762697Z"), } assert.Equal(t, expected, token) assert.Equal(t, expected.Value, client.token) } func TestAccountClient_Logout(t *testing.T) { client, mux := setupTest(t, "f07Q0TRmEb-CRWPe4h64_iV2jbet") mux.HandleFunc("POST /auth/logout/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNoContent) }) err := client.Account.Logout(context.Background()) require.NoError(t, err) assert.Empty(t, client.token) } func TestAccountClient_RetrieveInformation(t *testing.T) { client, mux := setupTest(t, "f07Q0TRmEb-CRWPe4h64_iV2jbet") mux.HandleFunc("POST /auth/account/", fromFixtures("accounts_retrieve.json", http.StatusOK)) account, err := client.Account.RetrieveInformation(context.Background()) require.NoError(t, err) expected := &Account{ Email: "youremailaddress@example.com", LimitDomains: 5, Created: mustParseTime("2019-10-16T18:09:17.715702Z"), } assert.Equal(t, expected, account) } func TestAccountClient_PasswordReset(t *testing.T) { client, mux := setupTest(t, "") mux.HandleFunc("POST /", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusAccepted) }) captcha := Captcha{ ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", Solution: "12H45", } err := client.Account.PasswordReset(context.Background(), "email@example.com", captcha) require.NoError(t, err) } func TestAccountClient_ChangeEmail(t *testing.T) { client, mux := setupTest(t, "") mux.HandleFunc("POST /", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusAccepted) }) err := client.Account.ChangeEmail(context.Background(), "email@example.com", "secret", "newemail@example.com") require.NoError(t, err) } func TestAccountClient_Delete(t *testing.T) { client, mux := setupTest(t, "") mux.HandleFunc("POST /auth/account/delete/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusAccepted) }) err := client.Account.Delete(context.Background(), "email@example.com", "secret") require.NoError(t, err) } golang-github-nrdcg-desec-0.11.2/desec.go000066400000000000000000000070451520713316300201170ustar00rootroot00000000000000package desec import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "time" "github.com/hashicorp/go-retryablehttp" ) const defaultBaseURL = "https://desec.io/api/v1/" type httpDoer interface { Do(req *http.Request) (*http.Response, error) } type service struct { client *Client } // ClientOptions the options of the Client. type ClientOptions struct { // HTTPClient HTTP client used to communicate with the API. HTTPClient *http.Client // Maximum number of retries RetryMax int // Customer logger instance. Can be either Logger or LeveledLogger Logger any } // NewDefaultClientOptions creates a new ClientOptions with default values. func NewDefaultClientOptions() ClientOptions { return ClientOptions{ HTTPClient: &http.Client{Timeout: 10 * time.Second}, RetryMax: 5, Logger: nil, } } // Client deSEC API client. type Client struct { // Base URL for API requests. BaseURL string httpClient httpDoer token string common service // Reuse a single struct instead of allocating one for each service on the heap. // Services used for talking to different parts of the deSEC API. Account *AccountService Tokens *TokensService TokenPolicies *TokenPoliciesService Records *RecordsService Domains *DomainsService } // New creates a new Client. func New(token string, opts ClientOptions) *Client { // https://github.com/desec-io/desec-stack/blob/main/docs/rate-limits.rst retryClient := retryablehttp.NewClient() retryClient.RetryMax = opts.RetryMax retryClient.HTTPClient = opts.HTTPClient retryClient.Logger = opts.Logger client := &Client{ httpClient: retryClient.StandardClient(), BaseURL: defaultBaseURL, token: token, } client.common.client = client client.Account = (*AccountService)(&client.common) client.Tokens = (*TokensService)(&client.common) client.TokenPolicies = (*TokenPoliciesService)(&client.common) client.Records = (*RecordsService)(&client.common) client.Domains = (*DomainsService)(&client.common) return client } func (c *Client) newRequest(ctx context.Context, method string, endpoint fmt.Stringer, reqBody any) (*http.Request, error) { buf := new(bytes.Buffer) if reqBody != nil { err := json.NewEncoder(buf).Encode(reqBody) if err != nil { return nil, fmt.Errorf("failed to marshal request body: %w", err) } } req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Set("Content-Type", "application/json") if c.token != "" { req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) } return req, nil } func (c *Client) createEndpoint(parts ...string) (*url.URL, error) { base, err := url.Parse(c.BaseURL) if err != nil { return nil, err } endpoint := base.JoinPath(parts...) endpoint.Path += "/" return endpoint, nil } func handleResponse(resp *http.Response, respData any) error { body, err := io.ReadAll(resp.Body) if err != nil { return &APIError{ StatusCode: resp.StatusCode, err: fmt.Errorf("failed to read response body: %w", err), } } if len(body) == 0 { return nil } err = json.Unmarshal(body, respData) if err != nil { return fmt.Errorf("failed to umarshal response body: %w", err) } return nil } func handleError(resp *http.Response) error { switch resp.StatusCode { case http.StatusNotFound: return readError(resp, &NotFoundError{}) default: return readRawError(resp) } } // Pointer creates pointer of string. func Pointer[T string](v T) *T { return &v } golang-github-nrdcg-desec-0.11.2/desec_test.go000066400000000000000000000021151520713316300211470ustar00rootroot00000000000000package desec import ( "io" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "time" ) func setupTest(t *testing.T, token string) (*Client, *http.ServeMux) { t.Helper() mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) options := NewDefaultClientOptions() options.HTTPClient = server.Client() client := New(token, options) client.BaseURL = server.URL return client, mux } func fromFixtures(filename string, statusCode int) http.HandlerFunc { return func(rw http.ResponseWriter, _ *http.Request) { rw.Header().Set("Content-Type", "application/json") file, err := os.Open(filepath.Clean(filepath.Join("fixtures", filename))) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() rw.WriteHeader(statusCode) _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } } } func mustParseTime(value string) *time.Time { date, _ := time.Parse(time.RFC3339, value) return &date } golang-github-nrdcg-desec-0.11.2/domains.go000066400000000000000000000124121520713316300204600ustar00rootroot00000000000000package desec import ( "context" "fmt" "net/http" "net/url" "time" ) // Domain a domain representation. type Domain struct { Name string `json:"name,omitempty"` MinimumTTL int `json:"minimum_ttl,omitempty"` Keys []DomainKey `json:"keys,omitempty"` Created *time.Time `json:"created,omitempty"` Published *time.Time `json:"published,omitempty"` Touched *time.Time `json:"touched,omitempty"` } // DomainKey a domain key representation. type DomainKey struct { DNSKey string `json:"dnskey,omitempty"` DS []string `json:"ds,omitempty"` Flags int `json:"flags,omitempty"` KeyType string `json:"keytype,omitempty"` } // DomainsService handles communication with the domain related methods of the deSEC API. // // https://desec.readthedocs.io/en/latest/dns/domains.html type DomainsService struct { client *Client } // Create creating a domain. // https://desec.readthedocs.io/en/latest/dns/domains.html#creating-a-domain func (s *DomainsService) Create(ctx context.Context, domainName string) (*Domain, error) { endpoint, err := s.client.createEndpoint("domains") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Domain{Name: domainName}) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { return nil, handleError(resp) } var domain Domain err = handleResponse(resp, &domain) if err != nil { return nil, err } return &domain, nil } // GetAll listing domains. // https://desec.readthedocs.io/en/latest/dns/domains.html#listing-domains func (s *DomainsService) GetAll(ctx context.Context) ([]Domain, error) { domains, _, err := s.GetAllPaginated(ctx, "") if err != nil { return nil, err } return domains, nil } // GetAllPaginated listing domains. // https://desec.readthedocs.io/en/latest/dns/domains.html#listing-domains func (s *DomainsService) GetAllPaginated(ctx context.Context, cursor string) ([]Domain, *Cursors, error) { queryValues := url.Values{} queryValues.Set("cursor", cursor) return s.getAll(ctx, queryValues) } // GetResponsible returns the responsible domain for a given DNS query name. // https://desec.readthedocs.io/en/latest/dns/domains.html#identifying-the-responsible-domain-for-a-dns-name func (s *DomainsService) GetResponsible(ctx context.Context, domainName string) (*Domain, error) { queryValues := url.Values{} queryValues.Set("owns_qname", domainName) domains, _, err := s.getAll(ctx, queryValues) if err != nil { return nil, err } if len(domains) == 0 { return nil, &NotFoundError{Detail: "no responsible domain found"} } return &domains[0], nil } // getAll listing domains. // https://desec.readthedocs.io/en/latest/dns/domains.html#listing-domains func (s *DomainsService) getAll(ctx context.Context, query url.Values) ([]Domain, *Cursors, error) { endpoint, err := s.client.createEndpoint("domains") if err != nil { return nil, nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, nil, err } if len(query) > 0 { req.URL.RawQuery = query.Encode() } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, nil, handleError(resp) } cursors, err := parseCursor(resp.Header) if err != nil { return nil, nil, err } var domains []Domain err = handleResponse(resp, &domains) if err != nil { return nil, nil, err } return domains, cursors, nil } // Get retrieving a specific domain. // https://desec.readthedocs.io/en/latest/dns/domains.html#retrieving-a-specific-domain func (s *DomainsService) Get(ctx context.Context, domainName string) (*Domain, error) { endpoint, err := s.client.createEndpoint("domains", domainName) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var domains Domain err = handleResponse(resp, &domains) if err != nil { return nil, err } return &domains, nil } // Delete deleting a domain. // https://desec.readthedocs.io/en/latest/dns/domains.html#deleting-a-domain func (s *DomainsService) Delete(ctx context.Context, domainName string) error { endpoint, err := s.client.createEndpoint("domains", domainName) if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusNoContent { return handleError(resp) } return nil } golang-github-nrdcg-desec-0.11.2/domains_test.go000066400000000000000000000100271520713316300215170ustar00rootroot00000000000000package desec import ( "context" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDomainsService_Create(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("POST /domains/", fromFixtures("domains_create.json", http.StatusCreated)) newDomain, err := client.Domains.Create(context.Background(), "example.com") require.NoError(t, err) expected := &Domain{ Name: "example.com", MinimumTTL: 3600, Keys: []DomainKey{ { DNSKey: "257 3 13 WFRl60...", DS: []string{ "6006 13 1 8581e9...", "6006 13 2 f34b75...", "6006 13 3 dfb325...", "6006 13 4 2fdcf8...", }, Flags: 257, KeyType: "csk", }, }, Created: mustParseTime("2018-09-18T16:36:16.510368Z"), Published: mustParseTime("2018-09-18T17:21:38.348112Z"), Touched: mustParseTime("2018-09-18T17:21:38.348112Z"), } assert.Equal(t, expected, newDomain) } func TestDomainsService_Delete(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("DELETE /domains/example.com/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNoContent) }) err := client.Domains.Delete(context.Background(), "example.com") require.NoError(t, err) } func TestDomainsService_Get(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /domains/example.com/", fromFixtures("domains_get.json", http.StatusOK)) domain, err := client.Domains.Get(context.Background(), "example.com") require.NoError(t, err) expected := &Domain{ Name: "example.com", MinimumTTL: 3600, Keys: []DomainKey{ { DNSKey: "257 3 13 WFRl60...", DS: []string{ "6006 13 1 8581e9...", "6006 13 2 f34b75...", "6006 13 3 dfb325...", "6006 13 4 2fdcf8...", }, Flags: 257, KeyType: "csk", }, }, Created: mustParseTime("2018-09-18T16:36:16.510368Z"), Published: mustParseTime("2018-09-18T17:21:38.348112Z"), Touched: mustParseTime("2018-09-18T17:21:38.348112Z"), } assert.Equal(t, expected, domain) } func TestDomainsService_GetResponsible(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /domains/", func(rw http.ResponseWriter, req *http.Request) { if req.URL.Query().Get("owns_qname") != "git.dev.example.org" { http.Error(rw, "owns_qname not passed correctly", http.StatusBadRequest) return } fromFixtures("domains_getresponsible.json", http.StatusOK).ServeHTTP(rw, req) }) domain, err := client.Domains.GetResponsible(context.Background(), "git.dev.example.org") require.NoError(t, err) expected := &Domain{ Name: "dev.example.org", MinimumTTL: 3600, Created: mustParseTime("2022-11-12T18:01:35.454616Z"), Published: mustParseTime("2022-11-12T18:03:19.516440Z"), Touched: mustParseTime("2022-11-12T18:03:19.516440Z"), } assert.Equal(t, expected, domain) } func TestDomainsService_GetResponsible_error(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /domains/", func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("[]")) }) _, err := client.Domains.GetResponsible(context.Background(), "git.dev.example.org") var notFoundError *NotFoundError require.ErrorAs(t, err, ¬FoundError) } func TestDomainsService_GetAll(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /domains/", fromFixtures("domains_getall.json", http.StatusOK)) domains, err := client.Domains.GetAll(context.Background()) require.NoError(t, err) expected := []Domain{ { Name: "example.org", MinimumTTL: 3600, Created: mustParseTime("2020-05-13T11:35:40.954616Z"), Published: mustParseTime("2020-05-13T12:25:19.816440Z"), Touched: mustParseTime("2020-05-13T12:25:19.816440Z"), }, { Name: "example.dedyn.io", MinimumTTL: 60, Created: mustParseTime("2020-05-05T23:17:36.101470Z"), Published: mustParseTime("2020-05-06T12:13:06.138443Z"), Touched: mustParseTime("2020-05-06T12:13:06.138443Z"), }, } assert.Equal(t, expected, domains) } golang-github-nrdcg-desec-0.11.2/errors.go000066400000000000000000000024351520713316300203460ustar00rootroot00000000000000package desec import ( "encoding/json" "fmt" "io" "net/http" ) // NotFoundError Not found error. type NotFoundError struct { Detail string `json:"detail"` } func (n NotFoundError) Error() string { return n.Detail } // APIError error from API. type APIError struct { StatusCode int err error } func (e APIError) Error() string { return fmt.Sprintf("%d: %v", e.StatusCode, e.err) } // Unwrap unwraps error. func (e APIError) Unwrap() error { return e.err } func readError(resp *http.Response, er error) error { body, err := io.ReadAll(resp.Body) if err != nil { return &APIError{ StatusCode: resp.StatusCode, err: fmt.Errorf("failed to read response body: %w", err), } } err = json.Unmarshal(body, er) if err != nil { return &APIError{ StatusCode: resp.StatusCode, err: fmt.Errorf("failed to unmarshall response body: %w: %s", err, string(body)), } } return &APIError{ StatusCode: resp.StatusCode, err: er, } } func readRawError(resp *http.Response) error { body, err := io.ReadAll(resp.Body) if err != nil { return &APIError{ StatusCode: resp.StatusCode, err: fmt.Errorf("failed to read response body: %w", err), } } return &APIError{StatusCode: resp.StatusCode, err: fmt.Errorf("body: %s", string(body))} } golang-github-nrdcg-desec-0.11.2/fixtures/000077500000000000000000000000001520713316300203505ustar00rootroot00000000000000golang-github-nrdcg-desec-0.11.2/fixtures/accounts_captcha.json000066400000000000000000000002041520713316300245410ustar00rootroot00000000000000{ "id": "aaa", "challenge": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8zxD3EwAFuwJYQcBz5wAAAABJRU5ErkJggg==" }golang-github-nrdcg-desec-0.11.2/fixtures/accounts_login.json000066400000000000000000000002341520713316300242510ustar00rootroot00000000000000{ "created": "2018-09-06T09:07:43.762697Z", "id": "8f9cbae2-c862-48a4-b3f0-2cb1a80df168", "token": "f07Q0TRmEb-CRWPe4h64_iV2jbet", "name": "login" }golang-github-nrdcg-desec-0.11.2/fixtures/accounts_retrieve.json000066400000000000000000000002371520713316300247710ustar00rootroot00000000000000{ "created": "2019-10-16T18:09:17.715702Z", "email": "youremailaddress@example.com", "id": "9ab16e5c-805d-4ab1-9030-af3f5a541d47", "limit_domains": 5 }golang-github-nrdcg-desec-0.11.2/fixtures/domains_create.json000066400000000000000000000006711520713316300242240ustar00rootroot00000000000000{ "created": "2018-09-18T16:36:16.510368Z", "keys": [ { "dnskey": "257 3 13 WFRl60...", "ds": [ "6006 13 1 8581e9...", "6006 13 2 f34b75...", "6006 13 3 dfb325...", "6006 13 4 2fdcf8..." ], "flags": 257, "keytype": "csk" } ], "minimum_ttl": 3600, "name": "example.com", "published": "2018-09-18T17:21:38.348112Z", "touched": "2018-09-18T17:21:38.348112Z" } golang-github-nrdcg-desec-0.11.2/fixtures/domains_get.json000066400000000000000000000006711520713316300235400ustar00rootroot00000000000000{ "created": "2018-09-18T16:36:16.510368Z", "keys": [ { "dnskey": "257 3 13 WFRl60...", "ds": [ "6006 13 1 8581e9...", "6006 13 2 f34b75...", "6006 13 3 dfb325...", "6006 13 4 2fdcf8..." ], "flags": 257, "keytype": "csk" } ], "minimum_ttl": 3600, "name": "example.com", "published": "2018-09-18T17:21:38.348112Z", "touched": "2018-09-18T17:21:38.348112Z" } golang-github-nrdcg-desec-0.11.2/fixtures/domains_getall.json000066400000000000000000000006261520713316300242310ustar00rootroot00000000000000[ { "created": "2020-05-13T11:35:40.954616Z", "touched": "2020-05-13T12:25:19.816440Z", "published": "2020-05-13T12:25:19.816440Z", "name": "example.org", "minimum_ttl": 3600 }, { "created": "2020-05-05T23:17:36.101470Z", "published": "2020-05-06T12:13:06.138443Z", "touched": "2020-05-06T12:13:06.138443Z", "name": "example.dedyn.io", "minimum_ttl": 60 } ] golang-github-nrdcg-desec-0.11.2/fixtures/domains_getresponsible.json000066400000000000000000000003171520713316300260030ustar00rootroot00000000000000[ { "created": "2022-11-12T18:01:35.454616Z", "published": "2022-11-12T18:03:19.516440Z", "touched": "2022-11-12T18:03:19.516440Z", "name": "dev.example.org", "minimum_ttl": 3600 } ] golang-github-nrdcg-desec-0.11.2/fixtures/records_create.json000066400000000000000000000004131520713316300242250ustar00rootroot00000000000000{ "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "_acme-challenge", "name": "_acme-challenge.example.dedyn.io.", "records": [ "\"txt\"" ], "ttl": 300, "type": "TXT", "touched": "2020-05-06T11:46:07.641885Z" } golang-github-nrdcg-desec-0.11.2/fixtures/records_create_bulk.json000066400000000000000000000004471520713316300252510ustar00rootroot00000000000000[ { "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "_acme-challenge", "name": "_acme-challenge.example.dedyn.io.", "records": [ "\"txt\"" ], "ttl": 300, "type": "TXT", "touched": "2020-05-06T11:46:07.641885Z" } ] golang-github-nrdcg-desec-0.11.2/fixtures/records_get.json000066400000000000000000000004131520713316300235410ustar00rootroot00000000000000{ "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "_acme-challenge", "name": "_acme-challenge.example.dedyn.io.", "records": [ "\"txt\"" ], "ttl": 300, "type": "TXT", "touched": "2020-05-06T11:46:07.641885Z" } golang-github-nrdcg-desec-0.11.2/fixtures/records_getall.json000066400000000000000000000010541520713316300242340ustar00rootroot00000000000000[ { "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "", "name": "example.dedyn.io.", "records": [ "10.10.10.10" ], "ttl": 60, "type": "A", "touched": "2020-05-06T11:46:07.641885Z" }, { "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "", "name": "example.dedyn.io.", "records": [ "ns1.desec.io.", "ns2.desec.org." ], "ttl": 3600, "type": "NS", "touched": "2020-05-06T11:46:07.641885Z" } ] golang-github-nrdcg-desec-0.11.2/fixtures/records_replace.json000066400000000000000000000004171520713316300244010ustar00rootroot00000000000000{ "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "_acme-challenge", "name": "_acme-challenge.example.dedyn.io.", "records": [ "\"updated\"" ], "ttl": 300, "type": "TXT", "touched": "2020-05-06T11:46:07.641885Z" } golang-github-nrdcg-desec-0.11.2/fixtures/records_update.json000066400000000000000000000004171520713316300242500ustar00rootroot00000000000000{ "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "_acme-challenge", "name": "_acme-challenge.example.dedyn.io.", "records": [ "\"updated\"" ], "ttl": 300, "type": "TXT", "touched": "2020-05-06T11:46:07.641885Z" } golang-github-nrdcg-desec-0.11.2/fixtures/records_update_bulk.json000066400000000000000000000004531520713316300252650ustar00rootroot00000000000000[ { "created": "2020-05-06T11:46:07.641885Z", "domain": "example.dedyn.io", "subname": "_acme-challenge", "name": "_acme-challenge.example.dedyn.io.", "records": [ "\"updated\"" ], "ttl": 300, "type": "TXT", "touched": "2020-05-06T11:46:07.641885Z" } ] golang-github-nrdcg-desec-0.11.2/fixtures/tokens_create.json000066400000000000000000000002431520713316300240700ustar00rootroot00000000000000{ "created": "2018-09-06T09:08:43.762697Z", "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", "name": "my new token" }golang-github-nrdcg-desec-0.11.2/fixtures/tokens_get.json000066400000000000000000000007231520713316300234070ustar00rootroot00000000000000{ "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", "created": "2018-09-06T09:08:43.762697Z", "last_used": null, "owner": "youremailaddress@example.com", "user_override": null, "max_age": "365 00:00:00", "max_unused_period": null, "name": "my new token", "perm_create_domain": false, "perm_delete_domain": false, "perm_manage_tokens": false, "allowed_subnets": [ "0.0.0.0/0", "::/0" ], "auto_policy": false, "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S" } golang-github-nrdcg-desec-0.11.2/fixtures/tokens_getall.json000066400000000000000000000013471520713316300241030ustar00rootroot00000000000000[ { "created": "2018-09-06T07:05:54.080564Z", "id": "3159e485-5499-46c0-ae2b-aeb84d627a8e", "name": "login" }, { "created": "2018-09-06T08:53:26.428396Z", "id": "76d6e39d-65bc-4ab2-a1b7-6e94eee0a534", "name": "sample" }, { "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", "created": "2018-09-06T09:08:43.762697Z", "last_used": null, "owner": "youremailaddress@example.com", "user_override": null, "max_age": "365 00:00:00", "max_unused_period": null, "name": "my new token", "perm_create_domain": false, "perm_delete_domain": false, "perm_manage_tokens": false, "allowed_subnets": [ "0.0.0.0/0", "::/0" ], "auto_policy": false, "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S" } ] golang-github-nrdcg-desec-0.11.2/fixtures/tokens_policy_create.json000066400000000000000000000002111520713316300254420ustar00rootroot00000000000000{ "id": "2f133e8e-56a0-4b19-8e7e-f2e29c7ce263", "domain": "example.com", "subname": "testing", "type": "A", "perm_write": true } golang-github-nrdcg-desec-0.11.2/fixtures/tokens_policy_create_empty.json000066400000000000000000000001461520713316300266670ustar00rootroot00000000000000{ "id": "a563a574-33c9-45d1-9201-e5577b42aaf1", "domain": null, "subname": null, "type": null } golang-github-nrdcg-desec-0.11.2/fixtures/tokens_policy_get.json000066400000000000000000000002061520713316300247620ustar00rootroot00000000000000{ "id": "fa6fdf60-6546-4cee-9168-5d144fe9339c", "domain": "example.com", "subname": "testing", "type": "A", "perm_write": true } golang-github-nrdcg-desec-0.11.2/fixtures/tokens_policy_get_all.json000066400000000000000000000004411520713316300256130ustar00rootroot00000000000000[ { "id": "7aed3f71-bc81-4f7e-90ae-8f0df0d1c211", "domain": "example.com", "subname": "testing", "type": null, "perm_write": false }, { "id": "fa6fdf60-6546-4cee-9168-5d144fe9339c", "domain": "example.com", "subname": "testing", "type": "A", "perm_write": true } ] golang-github-nrdcg-desec-0.11.2/fixtures/tokens_policy_update.json000066400000000000000000000002071520713316300254660ustar00rootroot00000000000000{ "id": "fa6fdf60-6546-4cee-9168-5d144fe9339c", "domain": "example.com", "subname": "testing", "type": "A", "perm_write": false } golang-github-nrdcg-desec-0.11.2/fixtures/tokens_update.json000066400000000000000000000007211520713316300241100ustar00rootroot00000000000000{ "id": "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", "created": "2018-09-06T09:08:43.762697Z", "last_used": null, "owner": "youremailaddress@example.com", "user_override": null, "max_age": "365 00:00:00", "max_unused_period": null, "name": "my new token", "perm_create_domain": true, "perm_delete_domain": false, "perm_manage_tokens": true, "allowed_subnets": [ "0.0.0.0/0", "::/0" ], "auto_policy": false, "token": "4pnk7u-NHvrEkFzrhFDRTjGFyX_S" } golang-github-nrdcg-desec-0.11.2/go.mod000066400000000000000000000005661520713316300176140ustar00rootroot00000000000000module github.com/nrdcg/desec go 1.23 require ( github.com/hashicorp/go-retryablehttp v0.7.8 github.com/peterhellberg/link v1.2.0 github.com/stretchr/testify v1.11.1 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) golang-github-nrdcg-desec-0.11.2/go.sum000066400000000000000000000043551520713316300176410ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/peterhellberg/link v1.2.0 h1:UA5pg3Gp/E0F2WdX7GERiNrPQrM1K6CVJUUWfHa4t6c= github.com/peterhellberg/link v1.2.0/go.mod h1:gYfAh+oJgQu2SrZHg5hROVRQe1ICoK0/HHJTcE0edxc= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-github-nrdcg-desec-0.11.2/pagination.go000066400000000000000000000012671520713316300211650ustar00rootroot00000000000000package desec import ( "net/http" "net/url" "github.com/peterhellberg/link" ) // Cursors allows to retrieve the next (or previous) page. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#pagination type Cursors struct { First string Prev string Next string } func parseCursor(h http.Header) (*Cursors, error) { links := link.ParseHeader(h) c := &Cursors{} for s, l := range links { uri, err := url.ParseRequestURI(l.URI) if err != nil { return nil, err } query := uri.Query() switch s { case "first": c.First = query.Get("cursor") case "prev": c.Prev = query.Get("cursor") case "next": c.Next = query.Get("cursor") } } return c, nil } golang-github-nrdcg-desec-0.11.2/pagination_test.go000066400000000000000000000027271520713316300222260ustar00rootroot00000000000000package desec import ( "net/http" "testing" "github.com/stretchr/testify/require" ) func Test_parseCursor(t *testing.T) { testCases := []struct { desc string header string expected *Cursors }{ { desc: "all cursors", header: `; rel="first", ; rel="prev", ; rel="next"`, expected: &Cursors{First: "", Prev: ":prev_cursor", Next: ":next_cursor"}, }, { desc: "first page", header: `; rel="first", ; rel="next"`, expected: &Cursors{First: "", Prev: "", Next: ":next_cursor"}, }, { desc: "last page", header: `; rel="first", ; rel="prev"`, expected: &Cursors{First: "", Prev: ":prev_cursor", Next: ""}, }, { desc: "empty", header: ``, expected: &Cursors{First: "", Prev: "", Next: ""}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() h := http.Header{} h.Set("Link", test.header) cursor, err := parseCursor(h) require.NoError(t, err) require.Equal(t, test.expected, cursor) }) } } golang-github-nrdcg-desec-0.11.2/readme.md000066400000000000000000000034551520713316300202650ustar00rootroot00000000000000# Go library for accessing the deSEC API [![Build Status](https://github.com/nrdcg/desec/workflows/Main/badge.svg?branch=main)](https://github.com/nrdcg/desec/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/nrdcg/desec)](https://pkg.go.dev/github.com/nrdcg/desec) [![Go Report Card](https://goreportcard.com/badge/github.com/nrdcg/desec)](https://goreportcard.com/report/github.com/nrdcg/desec) An deSEC API client written in Go. desec is a Go client library for accessing the deSEC API. ## Examples ```go package main import ( "context" "fmt" "github.com/nrdcg/desec" ) func main() { client := desec.NewClient("token") newDomain, err := client.Domains.Create(context.Background(), "example.com") if err != nil { panic(err) } fmt.Println(newDomain) } ``` ```go package main import ( "context" "github.com/nrdcg/desec" ) func main() { client := desec.NewClient("") registration := desec.Registration{ Email: "email@example.com", Password: "secret", Captcha: &desec.Captcha{ ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", Solution: "12H45", }, } err := client.Account.Register(context.Background(), registration) if err != nil { panic(err) } } ``` ```go package main import ( "context" "fmt" "github.com/nrdcg/desec" ) func main() { client := desec.NewClient("") _, err := client.Account.Login(context.Background(), "email@example.com", "secret") if err != nil { panic(err) } domains, err := client.Domains.GetAllPagined(context.Background()) if err != nil { panic(err) } fmt.Println(domains) err = client.Account.Logout(context.Background()) if err != nil { panic(err) } } ``` ## API Documentation - [API docs](https://desec.readthedocs.io/en/latest/) - [API endpoint reference](https://desec.readthedocs.io/en/latest/endpoint-reference.html) golang-github-nrdcg-desec-0.11.2/records.go000066400000000000000000000245671520713316300205050ustar00rootroot00000000000000package desec import ( "context" "fmt" "net/http" "net/url" "time" ) // ApexZone apex zone name. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#accessing-the-zone-apex const ApexZone = "@" // IgnoreFilter is a specific value used to ignore a filter field. const IgnoreFilter = "#IGNORE#" // RRSet DNS Record Set. type RRSet struct { Name string `json:"name,omitempty"` Domain string `json:"domain,omitempty"` SubName string `json:"subname"` Type string `json:"type,omitempty"` Records []string `json:"records"` TTL int `json:"ttl,omitempty"` Created *time.Time `json:"created,omitempty"` Touched *time.Time `json:"touched,omitempty"` } // RRSetFilter a RRSets filter. type RRSetFilter struct { Type string SubName string } // FilterRRSetOnlyOnType creates an RRSetFilter that ignore SubName. func FilterRRSetOnlyOnType(t string) RRSetFilter { return RRSetFilter{ Type: t, SubName: IgnoreFilter, } } // FilterRRSetOnlyOnSubName creates an RRSetFilter that ignore Type. func FilterRRSetOnlyOnSubName(n string) RRSetFilter { return RRSetFilter{ Type: IgnoreFilter, SubName: n, } } // RecordsService handles communication with the records related methods of the deSEC API. // // https://desec.readthedocs.io/en/latest/dns/rrsets.html type RecordsService struct { client *Client } /* Domains */ // GetAll retrieving all RRSets in a zone. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-all-rrsets-in-a-zone func (s *RecordsService) GetAll(ctx context.Context, domainName string, filter *RRSetFilter) ([]RRSet, error) { rrSets, _, err := s.GetAllPaginated(ctx, domainName, filter, "") if err != nil { return nil, err } return rrSets, nil } // GetAllPaginated retrieving all RRSets in a zone. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-all-rrsets-in-a-zone func (s *RecordsService) GetAllPaginated(ctx context.Context, domainName string, filter *RRSetFilter, cursor string) ([]RRSet, *Cursors, error) { queryValues := url.Values{} if filter != nil { if filter.Type != IgnoreFilter { queryValues.Set("type", filter.Type) } if filter.SubName != IgnoreFilter { queryValues.Set("subname", filter.SubName) } } queryValues.Set("cursor", cursor) rrSets, cursors, err := s.getAll(ctx, domainName, queryValues) if err != nil { return nil, nil, err } return rrSets, cursors, nil } func (s *RecordsService) getAll(ctx context.Context, domainName string, query url.Values) ([]RRSet, *Cursors, error) { endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") if err != nil { return nil, nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, nil, err } if len(query) > 0 { req.URL.RawQuery = query.Encode() } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, nil, handleError(resp) } cursors, err := parseCursor(resp.Header) if err != nil { return nil, nil, err } var rrSets []RRSet err = handleResponse(resp, &rrSets) if err != nil { return nil, nil, err } return rrSets, cursors, nil } // Create creates a new RRSet. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#creating-a-tlsa-rrset func (s *RecordsService) Create(ctx context.Context, rrSet RRSet) (*RRSet, error) { endpoint, err := s.client.createEndpoint("domains", rrSet.Domain, "rrsets") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, rrSet) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { return nil, handleError(resp) } var newRRSet RRSet err = handleResponse(resp, &newRRSet) if err != nil { return nil, err } return &newRRSet, nil } /* Domains + subname + type */ // Get gets a RRSet. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#retrieving-a-specific-rrset func (s *RecordsService) Get(ctx context.Context, domainName, subName, recordType string) (*RRSet, error) { if subName == "" { subName = ApexZone } endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var rrSet RRSet err = handleResponse(resp, &rrSet) if err != nil { return nil, err } return &rrSet, nil } // Update updates RRSet (PATCH). // https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset func (s *RecordsService) Update(ctx context.Context, domainName, subName, recordType string, rrSet RRSet) (*RRSet, error) { if subName == "" { subName = ApexZone } endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPatch, endpoint, rrSet) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() // when a RRSet is deleted (empty records) if resp.StatusCode == http.StatusNoContent { return nil, nil } if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var updatedRRSet RRSet err = handleResponse(resp, &updatedRRSet) if err != nil { return nil, err } return &updatedRRSet, nil } // Replace replaces a RRSet (PUT). // https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset func (s *RecordsService) Replace(ctx context.Context, domainName, subName, recordType string, rrSet RRSet) (*RRSet, error) { if subName == "" { subName = ApexZone } endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPut, endpoint, rrSet) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() // when a RRSet is deleted (empty records) if resp.StatusCode == http.StatusNoContent { return nil, nil } if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var updatedRRSet RRSet err = handleResponse(resp, &updatedRRSet) if err != nil { return nil, err } return &updatedRRSet, nil } // Delete deletes a RRSet. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#deleting-an-rrset func (s *RecordsService) Delete(ctx context.Context, domainName, subName, recordType string) error { if subName == "" { subName = ApexZone } endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets", subName, recordType) if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusNoContent { return handleError(resp) } return nil } /* Bulk operations */ // UpdateMode the mode used to bulk update operations. type UpdateMode string const ( // FullResource the full resource must be specified. FullResource UpdateMode = http.MethodPut // OnlyFields only fields you would like to modify need to be provided. OnlyFields UpdateMode = http.MethodPatch ) // BulkCreate creates new RRSets in bulk. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#bulk-creation-of-rrsets func (s *RecordsService) BulkCreate(ctx context.Context, domainName string, rrSets []RRSet) ([]RRSet, error) { endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, rrSets) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { return nil, handleError(resp) } var newRRSets []RRSet err = handleResponse(resp, &newRRSets) if err != nil { return nil, err } return newRRSets, nil } // BulkUpdate updates RRSets in bulk. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#bulk-modification-of-rrsets func (s *RecordsService) BulkUpdate(ctx context.Context, mode UpdateMode, domainName string, rrSets []RRSet) ([]RRSet, error) { endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, string(mode), endpoint, rrSets) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var results []RRSet err = handleResponse(resp, &results) if err != nil { return nil, err } return results, nil } // BulkDelete deletes RRSets in bulk (uses FullResourceUpdateMode). // https://desec.readthedocs.io/en/latest/dns/rrsets.html#bulk-deletion-of-rrsets func (s *RecordsService) BulkDelete(ctx context.Context, domainName string, rrSets []RRSet) error { deleteRRSets := make([]RRSet, len(rrSets)) for i, rrSet := range rrSets { rrSet.Records = []string{} deleteRRSets[i] = rrSet } _, err := s.BulkUpdate(ctx, FullResource, domainName, deleteRRSets) if err != nil { return err } return nil } golang-github-nrdcg-desec-0.11.2/records_test.go000066400000000000000000000161761520713316300215410ustar00rootroot00000000000000package desec import ( "context" "encoding/json" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRecordsService_Create(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("POST /domains/example.dedyn.io/rrsets/", fromFixtures("records_create.json", http.StatusCreated)) record := RRSet{ Name: "", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, } newRecord, err := client.Records.Create(context.Background(), record) require.NoError(t, err) expected := &RRSet{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), } assert.Equal(t, expected, newRecord) } func TestRecordsService_Delete(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("DELETE /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNoContent) }) err := client.Records.Delete(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT") require.NoError(t, err) } func TestRecordsService_Get(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", fromFixtures("records_get.json", http.StatusOK)) record, err := client.Records.Get(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT") require.NoError(t, err) expected := &RRSet{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), } assert.Equal(t, expected, record) } func TestRecordsService_Update(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("PATCH /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", fromFixtures("records_update.json", http.StatusOK)) rrSet := RRSet{ Records: []string{`"updated"`}, } updatedRecord, err := client.Records.Update(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT", rrSet) require.NoError(t, err) expected := &RRSet{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"updated"`}, TTL: 300, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), } assert.Equal(t, expected, updatedRecord) } func TestRecordsService_Replace(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("PUT /domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", fromFixtures("records_replace.json", http.StatusOK)) rrSet := RRSet{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"updated"`}, TTL: 0, Created: nil, } updatedRecord, err := client.Records.Replace(context.Background(), "example.dedyn.io", "_acme-challenge", "TXT", rrSet) require.NoError(t, err) expected := &RRSet{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"updated"`}, TTL: 300, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), } assert.Equal(t, expected, updatedRecord) } func TestRecordsService_GetAll(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /domains/example.dedyn.io/rrsets/", fromFixtures("records_getall.json", http.StatusOK)) records, err := client.Records.GetAll(context.Background(), "example.dedyn.io", nil) require.NoError(t, err) expected := []RRSet{ { Name: "example.dedyn.io.", Domain: "example.dedyn.io", SubName: "", Type: "A", Records: []string{"10.10.10.10"}, TTL: 60, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), }, { Name: "example.dedyn.io.", Domain: "example.dedyn.io", SubName: "", Type: "NS", Records: []string{"ns1.desec.io.", "ns2.desec.org."}, TTL: 3600, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), }, } assert.Equal(t, expected, records) } func TestRecordsService_BulkCreate(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("POST /domains/example.dedyn.io/rrsets/", fromFixtures("records_create_bulk.json", http.StatusCreated)) rrSets := []RRSet{{ Name: "", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, }} newRecords, err := client.Records.BulkCreate(context.Background(), "example.dedyn.io", rrSets) require.NoError(t, err) expected := []RRSet{{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), }} assert.Equal(t, expected, newRecords) } func TestRecordsService_BulkDelete(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("PUT /domains/example.dedyn.io/rrsets/", func(rw http.ResponseWriter, req *http.Request) { defer func() { _ = req.Body.Close() }() var rrSets []RRSet if err := json.NewDecoder(req.Body).Decode(&rrSets); err != nil { http.Error(rw, "cannot unmarshal request body", http.StatusBadRequest) return } if len(rrSets) != 1 && rrSets[0].SubName != "_acme-challenge" && rrSets[0].Type != "TXT" && len(rrSets[0].Records) != 0 { http.Error(rw, "incorrect request body", http.StatusBadRequest) return } rw.WriteHeader(http.StatusOK) }) rrSets := []RRSet{{ Name: "", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, }} err := client.Records.BulkDelete(context.Background(), "example.dedyn.io", rrSets) require.NoError(t, err) } func TestRecordsService_BulkUpdate(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("PUT /domains/example.dedyn.io/rrsets/", fromFixtures("records_update_bulk.json", http.StatusOK)) rrSets := []RRSet{{ SubName: "_acme-challenge", Type: "TXT", Records: []string{`"updated"`}, TTL: 300, }} updatedRecord, err := client.Records.BulkUpdate(context.Background(), FullResource, "example.dedyn.io", rrSets) require.NoError(t, err) expected := []RRSet{{ Name: "_acme-challenge.example.dedyn.io.", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"updated"`}, TTL: 300, Created: mustParseTime("2020-05-06T11:46:07.641885Z"), Touched: mustParseTime("2020-05-06T11:46:07.641885Z"), }} assert.Equal(t, expected, updatedRecord) } golang-github-nrdcg-desec-0.11.2/token_policies.go000066400000000000000000000123131520713316300220350ustar00rootroot00000000000000package desec import ( "context" "fmt" "net/http" ) // TokenPolicy represents a policy applied to a token. type TokenPolicy struct { ID string `json:"id,omitempty"` Domain *string `json:"domain"` SubName *string `json:"subname"` Type *string `json:"type"` WritePermission bool `json:"perm_write,omitempty"` } // TokenPoliciesService handles communication with the token policy related methods of the deSEC API. // // https://desec.readthedocs.io/en/latest/auth/tokens.html type TokenPoliciesService struct { client *Client } // Deprecated: use [TokenPoliciesService.GetAll] instead. func (s *TokenPoliciesService) Get(ctx context.Context, tokenID string) ([]TokenPolicy, error) { return s.GetAll(ctx, tokenID) } // GetOne retrieves a specific token rrset policy. // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management func (s *TokenPoliciesService) GetOne(ctx context.Context, tokenID, policyID string) (*TokenPolicy, error) { endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets", policyID) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } policy := &TokenPolicy{} err = handleResponse(resp, policy) if err != nil { return nil, err } return policy, nil } // GetAll retrieves all rrset policies for a token. // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management func (s *TokenPoliciesService) GetAll(ctx context.Context, tokenID string) ([]TokenPolicy, error) { endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var policies []TokenPolicy err = handleResponse(resp, &policies) if err != nil { return nil, err } return policies, nil } // Create creates token policy. // https://desec.readthedocs.io/en/latest/auth/tokens.html#create-additional-tokens func (s *TokenPoliciesService) Create(ctx context.Context, tokenID string, policy TokenPolicy) (*TokenPolicy, error) { endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, policy) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { return nil, handleError(resp) } var tokenPolicy TokenPolicy err = handleResponse(resp, &tokenPolicy) if err != nil { return nil, err } return &tokenPolicy, nil } // Update a token policy // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management func (s *TokenPoliciesService) Update(ctx context.Context, tokenID, policyID string, policy TokenPolicy) (*TokenPolicy, error) { endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets", policyID) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } // Copy values, including only fields that can be modified req, err := s.client.newRequest(ctx, http.MethodPatch, endpoint, TokenPolicy{ Domain: policy.Domain, SubName: policy.SubName, Type: policy.Type, WritePermission: policy.WritePermission, }) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } result := &TokenPolicy{} err = handleResponse(resp, result) if err != nil { return nil, err } return result, nil } // Delete deletes a token rrset's policy. // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-policy-management func (s *TokenPoliciesService) Delete(ctx context.Context, tokenID, policyID string) error { endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID, "policies", "rrsets", policyID) if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusNoContent { return handleError(resp) } return nil } golang-github-nrdcg-desec-0.11.2/token_policies_test.go000066400000000000000000000112671520713316300231030ustar00rootroot00000000000000package desec import ( "context" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTokenPoliciesService_Get(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /auth/tokens/aaa/policies/rrsets/", fromFixtures("tokens_policy_get_all.json", http.StatusOK)) tokens, err := client.TokenPolicies.Get(context.Background(), "aaa") require.NoError(t, err) expected := []TokenPolicy{ { ID: "7aed3f71-bc81-4f7e-90ae-8f0df0d1c211", Domain: Pointer("example.com"), SubName: Pointer("testing"), WritePermission: false, }, { ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", Domain: Pointer("example.com"), SubName: Pointer("testing"), Type: Pointer("A"), WritePermission: true, }, } assert.Equal(t, expected, tokens) } func TestTokenPoliciesService_GetOne(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /auth/tokens/aaa/policies/rrsets/fa6fdf60-6546-4cee-9168-5d144fe9339c/", fromFixtures("tokens_policy_get.json", http.StatusOK)) tokens, err := client.TokenPolicies.GetOne(context.Background(), "aaa", "fa6fdf60-6546-4cee-9168-5d144fe9339c") require.NoError(t, err) expected := &TokenPolicy{ ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", Domain: Pointer("example.com"), SubName: Pointer("testing"), Type: Pointer("A"), WritePermission: true, } assert.Equal(t, expected, tokens) } func TestTokenPoliciesService_Update(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("PATCH /auth/tokens/aaa/policies/rrsets/fa6fdf60-6546-4cee-9168-5d144fe9339c/", fromFixtures("tokens_policy_update.json", http.StatusOK)) tokens, err := client.TokenPolicies.Update(context.Background(), "aaa", "fa6fdf60-6546-4cee-9168-5d144fe9339c", TokenPolicy{ WritePermission: false, }) require.NoError(t, err) expected := &TokenPolicy{ ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", Domain: Pointer("example.com"), SubName: Pointer("testing"), Type: Pointer("A"), WritePermission: false, } assert.Equal(t, expected, tokens) } func TestTokenPoliciesService_GetAll(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /auth/tokens/aaa/policies/rrsets/", fromFixtures("tokens_policy_get_all.json", http.StatusOK)) tokens, err := client.TokenPolicies.GetAll(context.Background(), "aaa") require.NoError(t, err) expected := []TokenPolicy{ { ID: "7aed3f71-bc81-4f7e-90ae-8f0df0d1c211", Domain: Pointer("example.com"), SubName: Pointer("testing"), WritePermission: false, }, { ID: "fa6fdf60-6546-4cee-9168-5d144fe9339c", Domain: Pointer("example.com"), SubName: Pointer("testing"), Type: Pointer("A"), WritePermission: true, }, } assert.Equal(t, expected, tokens) } func TestTokenPoliciesService_Create(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("POST /auth/tokens/aaa/policies/rrsets/", fromFixtures("tokens_policy_create.json", http.StatusCreated)) mux.HandleFunc("POST /auth/tokens/bbb/policies/rrsets/", fromFixtures("tokens_policy_create_empty.json", http.StatusCreated)) testCases := []struct { desc string tokenID string policy TokenPolicy expected *TokenPolicy }{ { desc: "all fields", tokenID: "aaa", policy: TokenPolicy{ Domain: Pointer("example.com"), SubName: Pointer("testing"), Type: Pointer("A"), WritePermission: true, }, expected: &TokenPolicy{ ID: "2f133e8e-56a0-4b19-8e7e-f2e29c7ce263", Domain: Pointer("example.com"), SubName: Pointer("testing"), Type: Pointer("A"), WritePermission: true, }, }, { desc: "all null JSON policy", tokenID: "bbb", policy: TokenPolicy{}, expected: &TokenPolicy{ ID: "a563a574-33c9-45d1-9201-e5577b42aaf1", WritePermission: false, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() policies, err := client.TokenPolicies.Create(context.Background(), test.tokenID, test.policy) require.NoError(t, err) assert.Equal(t, test.expected, policies) }) } } func TestTokenPoliciesService_Delete(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("DELETE /auth/tokens/aaa/policies/rrsets/bbb/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNoContent) }) err := client.TokenPolicies.Delete(context.Background(), "aaa", "bbb") require.NoError(t, err) } golang-github-nrdcg-desec-0.11.2/tokens.go000066400000000000000000000131731520713316300203360ustar00rootroot00000000000000package desec import ( "context" "fmt" "net/http" "time" ) // Token a token representation. // // https://desec.readthedocs.io/en/latest/auth/tokens.html#token-field-reference type Token struct { ID string `json:"id,omitempty"` Created *time.Time `json:"created,omitempty"` LastUsed *time.Time `json:"last_used,omitempty"` Owner string `json:"owner,omitempty"` UserOverride string `json:"user_override,omitempty"` Name string `json:"name,omitempty"` PermCreateDomain bool `json:"perm_create_domain"` PermDeleteDomain bool `json:"perm_delete_domain"` PermManageTokens bool `json:"perm_manage_tokens"` IsValid bool `json:"is_valid,omitempty"` AllowedSubnets []string `json:"allowed_subnets,omitempty"` AutoPolicy bool `json:"auto_policy"` Value string `json:"token,omitempty"` // Not currently implemented // MaxAge *time.Duration `json:"name,omitempty"` // MaxUnusedPeriod *time.Duration `json:"name,omitempty"` } // TokensService handles communication with the tokens related methods of the deSEC API. // // https://desec.readthedocs.io/en/latest/auth/tokens.html type TokensService struct { client *Client } // GetAll retrieving all current tokens. // https://desec.readthedocs.io/en/latest/auth/tokens.html#retrieving-all-current-tokens func (s *TokensService) GetAll(ctx context.Context) ([]Token, error) { endpoint, err := s.client.createEndpoint("auth", "tokens") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } var tokens []Token err = handleResponse(resp, &tokens) if err != nil { return nil, err } return tokens, nil } // Get retrieves a specific token. // https://desec.readthedocs.io/en/latest/auth/tokens.html#retrieving-a-specific-token // NOTE: This method used to retrieve all policies for a token, that is now done by GetAll. func (s *TokensService) Get(ctx context.Context, id string) (*Token, error) { endpoint, err := s.client.createEndpoint("auth", "tokens", id) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode == http.StatusNotFound { return nil, nil } if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } token := &Token{} err = handleResponse(resp, token) if err != nil { return nil, err } return token, nil } // Create creates additional tokens. // https://desec.readthedocs.io/en/latest/auth/tokens.html#create-additional-tokens func (s *TokensService) Create(ctx context.Context, name string) (*Token, error) { endpoint, err := s.client.createEndpoint("auth", "tokens") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodPost, endpoint, Token{Name: name}) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { return nil, handleError(resp) } var token Token err = handleResponse(resp, &token) if err != nil { return nil, err } return &token, nil } // Update a token. // https://desec.readthedocs.io/en/latest/auth/tokens.html#modifying-a-token func (s *TokensService) Update(ctx context.Context, id string, token *Token) (*Token, error) { endpoint, err := s.client.createEndpoint("auth", "tokens", id) if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } // Copy values, including only fields that can be modified req, err := s.client.newRequest(ctx, http.MethodPatch, endpoint, Token{ Owner: token.Owner, UserOverride: token.UserOverride, Name: token.Name, PermCreateDomain: token.PermCreateDomain, PermDeleteDomain: token.PermDeleteDomain, PermManageTokens: token.PermManageTokens, AllowedSubnets: token.AllowedSubnets, AutoPolicy: token.AutoPolicy, }) if err != nil { return nil, err } resp, err := s.client.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, handleError(resp) } result := &Token{} err = handleResponse(resp, result) if err != nil { return nil, err } return result, nil } // Delete deletes tokens. // https://desec.readthedocs.io/en/latest/auth/tokens.html#delete-tokens func (s *TokensService) Delete(ctx context.Context, tokenID string) error { endpoint, err := s.client.createEndpoint("auth", "tokens", tokenID) if err != nil { return fmt.Errorf("failed to create endpoint: %w", err) } req, err := s.client.newRequest(ctx, http.MethodDelete, endpoint, nil) if err != nil { return err } resp, err := s.client.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call API: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusNoContent { return handleError(resp) } return nil } golang-github-nrdcg-desec-0.11.2/tokens_test.go000066400000000000000000000072341520713316300213760ustar00rootroot00000000000000package desec import ( "context" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTokensService_Create(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("POST /auth/tokens/", fromFixtures("tokens_create.json", http.StatusCreated)) newToken, err := client.Tokens.Create(context.Background(), "my new token") require.NoError(t, err) expected := &Token{ ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", Name: "my new token", Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", Created: mustParseTime("2018-09-06T09:08:43.762697Z"), } assert.Equal(t, expected, newToken) } func TestTokensService_GetAll(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /auth/tokens/", fromFixtures("tokens_getall.json", http.StatusOK)) tokens, err := client.Tokens.GetAll(context.Background()) require.NoError(t, err) expected := []Token{ { ID: "3159e485-5499-46c0-ae2b-aeb84d627a8e", Name: "login", Created: mustParseTime("2018-09-06T07:05:54.080564Z"), }, { ID: "76d6e39d-65bc-4ab2-a1b7-6e94eee0a534", Name: "sample", Created: mustParseTime("2018-09-06T08:53:26.428396Z"), }, { ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", Created: mustParseTime("2018-09-06T09:08:43.762697Z"), Owner: "youremailaddress@example.com", Name: "my new token", PermCreateDomain: false, PermDeleteDomain: false, PermManageTokens: false, AllowedSubnets: []string{ "0.0.0.0/0", "::/0", }, AutoPolicy: false, Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", }, } assert.Equal(t, expected, tokens) } func TestTokensService_Get(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("GET /auth/tokens/3a6b94b5-d20e-40bd-a7cc-521f5c79fab3/", fromFixtures("tokens_get.json", http.StatusOK)) token, err := client.Tokens.Get(context.Background(), "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3") require.NoError(t, err) expected := &Token{ ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", Created: mustParseTime("2018-09-06T09:08:43.762697Z"), Owner: "youremailaddress@example.com", Name: "my new token", PermCreateDomain: false, PermDeleteDomain: false, PermManageTokens: false, AllowedSubnets: []string{ "0.0.0.0/0", "::/0", }, AutoPolicy: false, Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", } assert.Equal(t, expected, token) } func TestTokensService_Update(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("PATCH /auth/tokens/3a6b94b5-d20e-40bd-a7cc-521f5c79fab3/", fromFixtures("tokens_update.json", http.StatusOK)) token, err := client.Tokens.Update(context.Background(), "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", &Token{ PermCreateDomain: true, PermDeleteDomain: false, PermManageTokens: true, }) require.NoError(t, err) expected := &Token{ ID: "3a6b94b5-d20e-40bd-a7cc-521f5c79fab3", Created: mustParseTime("2018-09-06T09:08:43.762697Z"), Owner: "youremailaddress@example.com", Name: "my new token", PermCreateDomain: true, PermDeleteDomain: false, PermManageTokens: true, AllowedSubnets: []string{ "0.0.0.0/0", "::/0", }, AutoPolicy: false, Value: "4pnk7u-NHvrEkFzrhFDRTjGFyX_S", } assert.Equal(t, expected, token) } func TestTokensService_Delete(t *testing.T) { client, mux := setupTest(t, "token") mux.HandleFunc("DELETE /auth/tokens/aaa/", func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusNoContent) }) err := client.Tokens.Delete(context.Background(), "aaa") require.NoError(t, err) }