pax_global_header00006660000000000000000000000064137557263350014532gustar00rootroot0000000000000052 comment=0d7a8950d32e221edcdd33f816c541ede2de5808 golang-github-nrdcg-desec-0.5.0/000077500000000000000000000000001375572633500164375ustar00rootroot00000000000000golang-github-nrdcg-desec-0.5.0/.github/000077500000000000000000000000001375572633500177775ustar00rootroot00000000000000golang-github-nrdcg-desec-0.5.0/.github/FUNDING.yml000066400000000000000000000000151375572633500216100ustar00rootroot00000000000000github: ldez golang-github-nrdcg-desec-0.5.0/.gitignore000066400000000000000000000000071375572633500204240ustar00rootroot00000000000000.idea/ golang-github-nrdcg-desec-0.5.0/.golangci.toml000066400000000000000000000012451375572633500211770ustar00rootroot00000000000000[run] deadline = "5m" skip-files = [] [linters-settings] [linters-settings.govet] check-shadowing = true [linters-settings.gocyclo] min-complexity = 12.0 [linters-settings.maligned] suggest-new = true [linters-settings.goconst] min-len = 3.0 min-occurrences = 3.0 [linters-settings.misspell] locale = "US" [linters] enable-all = true disable = [ "maligned", "lll", "dupl", "prealloc", "scopelint", "bodyclose", "wsl", "stylecheck", "gomnd", "goerr113", "testpackage", "noctx", "nlreturn", ] [issues] exclude-use-default = false max-per-linter = 0 max-same-issues = 0 golang-github-nrdcg-desec-0.5.0/.travis.yml000066400000000000000000000006721375572633500205550ustar00rootroot00000000000000language: go go: - 1.14.x - 1.x env: - GO111MODULE=on notifications: email: on_success: never on_failure: change before_install: # Install linters - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin ${GOLANGCI_LINT_VERSION} - golangci-lint --version install: - go mod tidy - git diff --exit-code go.mod - git diff --exit-code go.sum - go mod download golang-github-nrdcg-desec-0.5.0/LICENSE000066400000000000000000000405251375572633500174520ustar00rootroot00000000000000Mozilla 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.5.0/Makefile000066400000000000000000000002561375572633500201020ustar00rootroot00000000000000.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.5.0/account.go000066400000000000000000000155331375572633500204310ustar00rootroot00000000000000package desec import ( "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(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(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() 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(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() (*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(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(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(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() (*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(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(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(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(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(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(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(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.5.0/account_test.go000066400000000000000000000143271375572633500214700ustar00rootroot00000000000000package desec import ( "io" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAccountClient_ObtainCaptcha(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/captcha/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/accounts_captcha.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) captcha, err := client.Account.ObtainCaptcha() require.NoError(t, err) expected := &Captcha{ ID: "aaa", Challenge: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8zxD3EwAFuwJYQcBz5wAAAABJRU5ErkJggg==", } assert.Equal(t, expected, captcha) } func TestAccountClient_Register(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } 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(registration) require.NoError(t, err) } func TestAccountClient_Login(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/login/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/accounts_login.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) token, err := client.Account.Login("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) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("f07Q0TRmEb-CRWPe4h64_iV2jbet", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/logout/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusNoContent) }) err := client.Account.Logout() require.NoError(t, err) assert.Empty(t, client.token) } func TestAccountClient_RetrieveInformation(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("f07Q0TRmEb-CRWPe4h64_iV2jbet", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/account/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/accounts_retrieve.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) account, err := client.Account.RetrieveInformation() 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) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusAccepted) }) captcha := Captcha{ ID: "00010203-0405-0607-0809-0a0b0c0d0e0f", Solution: "12H45", } err := client.Account.PasswordReset("email@example.com", captcha) require.NoError(t, err) } func TestAccountClient_ChangeEmail(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusAccepted) }) err := client.Account.ChangeEmail("email@example.com", "secret", "newemail@example.com") require.NoError(t, err) } func TestAccountClient_Delete(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/account/delete/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusAccepted) }) err := client.Account.Delete("email@example.com", "secret") require.NoError(t, err) } golang-github-nrdcg-desec-0.5.0/desec.go000066400000000000000000000066341375572633500200620ustar00rootroot00000000000000package desec import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "path" "github.com/nrdcg/desec/internal" ) 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 // LimitRead number of request per second. LimitRead int // LimitWrite number of request per second. LimitWrite int } // NewDefaultClientOptions creates a new ClientOptions with default values. func NewDefaultClientOptions() ClientOptions { return ClientOptions{ HTTPClient: http.DefaultClient, // 10 requests every 1 second // https://github.com/desec-io/desec-stack/blob/70b9b5aac5e57ef30492d45c99e8648ad03dd0ca/api/api/settings.py#L120 LimitRead: 10, // 6 requests every 1 second // https://github.com/desec-io/desec-stack/blob/70b9b5aac5e57ef30492d45c99e8648ad03dd0ca/api/api/settings.py#L121 LimitWrite: 6, } } // 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 Records *RecordsService Domains *DomainsService } // New creates a new Client. func New(token string, opts ClientOptions) *Client { client := &Client{ httpClient: internal.New(opts.HTTPClient, opts.LimitRead, opts.LimitRead), BaseURL: defaultBaseURL, token: token, } client.common.client = client client.Account = (*AccountService)(&client.common) client.Tokens = (*TokensService)(&client.common) client.Records = (*RecordsService)(&client.common) client.Domains = (*DomainsService)(&client.common) return client } func (c *Client) newRequest(method string, endpoint fmt.Stringer, reqBody interface{}) (*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.NewRequest(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, err := base.Parse(path.Join(base.Path, path.Join(parts...))) if err != nil { return nil, err } endpoint.Path += "/" return endpoint, nil } func handleResponse(resp *http.Response, respData interface{}) error { body, err := ioutil.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, 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, &NotFound{}) default: return readRawError(resp) } } golang-github-nrdcg-desec-0.5.0/domains.go000066400000000000000000000073611375572633500204270ustar00rootroot00000000000000package desec import ( "fmt" "net/http" "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"` } // 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(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(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() ([]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(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 } // Get retrieving a specific domain. // https://desec.readthedocs.io/en/latest/dns/domains.html#retrieving-a-specific-domain func (s *DomainsService) Get(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(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(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(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.5.0/domains_test.go000066400000000000000000000107101375572633500214560ustar00rootroot00000000000000package desec import ( "io" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDomainsService_Create(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusCreated) file, err := os.Open("./fixtures/domains_create.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) newDomain, err := client.Domains.Create("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"), } assert.Equal(t, expected, newDomain) } func TestDomainsService_Delete(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.com/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodDelete { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusNoContent) }) err := client.Domains.Delete("example.com") require.NoError(t, err) } func TestDomainsService_Get(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.com/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/domains_get.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) domain, err := client.Domains.Get("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"), } assert.Equal(t, expected, domain) } func TestDomainsService_GetAll(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/domains_getall.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) domains, err := client.Domains.GetAll() 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"), }, { Name: "example.dedyn.io", MinimumTTL: 60, Created: mustParseTime("2020-05-05T23:17:36.101470Z"), Published: mustParseTime("2020-05-06T12:13:06.138443Z"), }, } assert.Equal(t, expected, domains) } golang-github-nrdcg-desec-0.5.0/errors.go000066400000000000000000000024351375572633500203060ustar00rootroot00000000000000package desec import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) // NotFound Not found error. type NotFound struct { Detail string `json:"detail"` } func (n NotFound) 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 := ioutil.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 := ioutil.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.5.0/fixtures/000077500000000000000000000000001375572633500203105ustar00rootroot00000000000000golang-github-nrdcg-desec-0.5.0/fixtures/accounts_captcha.json000066400000000000000000000002041375572633500245010ustar00rootroot00000000000000{ "id": "aaa", "challenge": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8zxD3EwAFuwJYQcBz5wAAAABJRU5ErkJggg==" }golang-github-nrdcg-desec-0.5.0/fixtures/accounts_login.json000066400000000000000000000002341375572633500242110ustar00rootroot00000000000000{ "created": "2018-09-06T09:07:43.762697Z", "id": "8f9cbae2-c862-48a4-b3f0-2cb1a80df168", "token": "f07Q0TRmEb-CRWPe4h64_iV2jbet", "name": "login" }golang-github-nrdcg-desec-0.5.0/fixtures/accounts_retrieve.json000066400000000000000000000002371375572633500247310ustar00rootroot00000000000000{ "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.5.0/fixtures/domains_create.json000066400000000000000000000006151375572633500241620ustar00rootroot00000000000000{ "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" } golang-github-nrdcg-desec-0.5.0/fixtures/domains_get.json000066400000000000000000000006151375572633500234760ustar00rootroot00000000000000{ "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" } golang-github-nrdcg-desec-0.5.0/fixtures/domains_getall.json000066400000000000000000000004721375572633500241700ustar00rootroot00000000000000[ { "created": "2020-05-13T11:35:40.954616Z", "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", "name": "example.dedyn.io", "minimum_ttl": 60 } ] golang-github-nrdcg-desec-0.5.0/fixtures/records_create.json000066400000000000000000000003371375572633500241720ustar00rootroot00000000000000{ "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" } golang-github-nrdcg-desec-0.5.0/fixtures/records_get.json000066400000000000000000000003371375572633500235060ustar00rootroot00000000000000{ "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" } golang-github-nrdcg-desec-0.5.0/fixtures/records_getall.json000066400000000000000000000007201375572633500241730ustar00rootroot00000000000000[ { "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" }, { "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" } ] golang-github-nrdcg-desec-0.5.0/fixtures/records_replace.json000066400000000000000000000003431375572633500243370ustar00rootroot00000000000000{ "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" } golang-github-nrdcg-desec-0.5.0/fixtures/records_update.json000066400000000000000000000003431375572633500242060ustar00rootroot00000000000000{ "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" } golang-github-nrdcg-desec-0.5.0/fixtures/tokens_create.json000066400000000000000000000002431375572633500240300ustar00rootroot00000000000000{ "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.5.0/fixtures/tokens_getall.json000066400000000000000000000003751375572633500240430ustar00rootroot00000000000000[ { "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" } ]golang-github-nrdcg-desec-0.5.0/go.mod000066400000000000000000000002161375572633500175440ustar00rootroot00000000000000module github.com/nrdcg/desec go 1.14 require ( github.com/stretchr/testify v1.6.1 golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e ) golang-github-nrdcg-desec-0.5.0/go.sum000066400000000000000000000023211375572633500175700ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e h1:EHBhcS0mlXEAVwNyO2dLfjToGsyY4j24pTs2ScHnX7s= golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 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.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-github-nrdcg-desec-0.5.0/internal/000077500000000000000000000000001375572633500202535ustar00rootroot00000000000000golang-github-nrdcg-desec-0.5.0/internal/ratelimit.go000066400000000000000000000024471375572633500226030ustar00rootroot00000000000000package internal import ( "net/http" "time" "golang.org/x/time/rate" ) // SmartClient is an Rate Limited HTTP Client. type SmartClient struct { client *http.Client rlRead *rate.Limiter rlWrite *rate.Limiter } // New Creates a new SmartClient. func New(client *http.Client, nRead, nWrite int) *SmartClient { c := client if client == nil { c = http.DefaultClient } nr := nRead if nr < 1 { nr = 1 } nw := nWrite if nw < 1 { nw = 1 } return &SmartClient{ client: c, rlRead: rate.NewLimiter(rate.Every(time.Second/time.Duration(nr)), 1), rlWrite: rate.NewLimiter(rate.Every(time.Second/time.Duration(nw)), 1), } } // Do sends an HTTP request and returns an HTTP response. func (s *SmartClient) Do(req *http.Request) (*http.Response, error) { switch req.Method { // https://github.com/desec-io/desec-stack/blob/bc0b4de7dcfc53ab17ff7823846d214cfc9e7024/api/desecapi/views.py#L102 // https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions case http.MethodGet, http.MethodOptions, http.MethodHead: return s.do(req, s.rlRead) default: return s.do(req, s.rlWrite) } } func (s *SmartClient) do(req *http.Request, rl *rate.Limiter) (*http.Response, error) { err := rl.Wait(req.Context()) if err != nil { return nil, err } return s.client.Do(req) } golang-github-nrdcg-desec-0.5.0/readme.md000066400000000000000000000032151375572633500202170ustar00rootroot00000000000000# Go library for accessing the deSEC API [![GoDoc](https://godoc.org/github.com/nrdcg/desec?status.svg)](https://godoc.org/github.com/nrdcg/desec) [![Build Status](https://travis-ci.com/nrdcg/desec.svg?branch=master)](https://travis-ci.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 ( "fmt" "github.com/nrdcg/desec" ) func main() { client := desec.NewClient("token") newDomain, err := client.Domains.Create("example.com") if err != nil { panic(err) } fmt.Println(newDomain) } ``` ```go package main import ( "fmt" "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(registration) if err != nil { panic(err) } } ``` ```go package main import ( "fmt" "github.com/nrdcg/desec" ) func main() { client := desec.NewClient("") _, err := client.Account.Login("email@example.com", "secret") if err != nil { panic(err) } domains, err := client.Domains.GetAll() if err != nil { panic(err) } fmt.Println(domains) err = client.Account.Logout() 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.5.0/records.go000066400000000000000000000143551375572633500204370ustar00rootroot00000000000000package desec import ( "fmt" "net/http" "time" ) // ApexZone apex zone name. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#accessing-the-zone-apex const ApexZone = "@" // RRSet DNS Record Set. type RRSet struct { Name string `json:"name,omitempty"` Domain string `json:"domain,omitempty"` SubName string `json:"subname,omitempty"` Type string `json:"type,omitempty"` Records []string `json:"records"` TTL int `json:"ttl,omitempty"` Created *time.Time `json:"created,omitempty"` } // RRSetFilter a RRsets filter. type RRSetFilter struct { Type string SubName string } // 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(domainName string, filter *RRSetFilter) ([]RRSet, error) { endpoint, err := s.client.createEndpoint("domains", domainName, "rrsets") if err != nil { return nil, fmt.Errorf("failed to create endpoint: %w", err) } if filter != nil { query := endpoint.Query() query.Set("type", filter.Type) query.Set("subname", filter.SubName) endpoint.RawQuery = query.Encode() } req, err := s.client.newRequest(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 rrSets []RRSet err = handleResponse(resp, &rrSets) if err != nil { return nil, err } return rrSets, nil } // Create creates a new RRSet. // https://desec.readthedocs.io/en/latest/dns/rrsets.html#creating-a-tlsa-rrset func (s *RecordsService) Create(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(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(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(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(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(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(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(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(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(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.5.0/records_test.go000066400000000000000000000163721375572633500214770ustar00rootroot00000000000000package desec import ( "io" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRecordsService_Create(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.dedyn.io/rrsets/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusCreated) file, err := os.Open("./fixtures/records_create.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) record := RRSet{ Name: "", Domain: "example.dedyn.io", SubName: "_acme-challenge", Type: "TXT", Records: []string{`"txt"`}, TTL: 300, } newRecord, err := client.Records.Create(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"), } assert.Equal(t, expected, newRecord) } func TestRecordsService_Delete(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodDelete { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusNoContent) }) err := client.Records.Delete("example.dedyn.io", "_acme-challenge", "TXT") require.NoError(t, err) } func TestRecordsService_Get(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/records_get.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) record, err := client.Records.Get("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"), } assert.Equal(t, expected, record) } func TestRecordsService_Update(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPatch { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/records_update.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) rrSet := RRSet{ Records: []string{`"updated"`}, } updatedRecord, err := client.Records.Update("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"), } assert.Equal(t, expected, updatedRecord) } func TestRecordsService_Replace(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.dedyn.io/rrsets/_acme-challenge/TXT/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPut { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/records_replace.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) 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("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"), } assert.Equal(t, expected, updatedRecord) } func TestRecordsService_GetAll(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/domains/example.dedyn.io/rrsets/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/records_getall.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) records, err := client.Records.GetAll("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"), }, { 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"), }, } assert.Equal(t, expected, records) } func mustParseTime(value string) *time.Time { date, _ := time.Parse(time.RFC3339, value) return &date } golang-github-nrdcg-desec-0.5.0/tokens.go000066400000000000000000000052441375572633500202760ustar00rootroot00000000000000package desec import ( "fmt" "net/http" "time" ) // Token a token representation. type Token struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Value string `json:"token,omitempty"` Created *time.Time `json:"created,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() ([]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(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 } // Create creates additional tokens. // https://desec.readthedocs.io/en/latest/auth/tokens.html#create-additional-tokens func (s *TokensService) Create(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(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 } // Delete deletes tokens. // https://desec.readthedocs.io/en/latest/auth/tokens.html#delete-tokens func (s *TokensService) Delete(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(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.5.0/tokens_test.go000066400000000000000000000055551375572633500213420ustar00rootroot00000000000000package desec import ( "io" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTokensService_Create(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/tokens/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusCreated) file, err := os.Open("./fixtures/tokens_create.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) newToken, err := client.Tokens.Create("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) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/tokens/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } file, err := os.Open("./fixtures/tokens_getall.json") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer func() { _ = file.Close() }() _, err = io.Copy(rw, file) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }) tokens, err := client.Tokens.GetAll() 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"), }, } assert.Equal(t, expected, tokens) } func TestTokensService_Delete(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) t.Cleanup(server.Close) client := New("token", NewDefaultClientOptions()) client.BaseURL = server.URL mux.HandleFunc("/auth/tokens/aaa/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodDelete { http.Error(rw, "invalid method", http.StatusMethodNotAllowed) return } rw.WriteHeader(http.StatusNoContent) }) err := client.Tokens.Delete("aaa") require.NoError(t, err) }