├── .github ├── CODEOWNER ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── BUG-REPORT.yml │ ├── DESIGN-DOC.yml │ ├── FEATURE-REQUEST.yml │ └── config.yml ├── auto_assign.yml ├── config.yml ├── pull_request_template.md └── workflows │ ├── closed_references.yml │ ├── conventional_commits.yml │ ├── format.yml │ ├── labels.yml │ ├── licenses.yml │ ├── stale.yml │ └── test.yml ├── .gitignore ├── .prettierignore ├── .reference-ignore ├── .reports └── dep-licenses.csv ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── MAINTAINERS ├── Makefile ├── README.md ├── SECURITY.md ├── UPGRADE.md ├── clientclosed.go ├── error_assert.go ├── error_default.go ├── error_default_test.go ├── error_defaults.go ├── error_reporter.go ├── go.mod ├── go.sum ├── grpc_unwrap_interceptors.go ├── grpc_unwrap_interceptors_test.go ├── httputil ├── buster.go ├── buster_test.go ├── header │ ├── header.go │ └── header_test.go ├── httputil.go ├── negotiate.go ├── negotiate_test.go ├── respbuf.go ├── static.go ├── static_test.go ├── transport.go └── transport_test.go ├── internal ├── helloworld.pb.go └── helloworld_grpc.pb.go ├── json.go ├── json_test.go ├── negotiator.go ├── options.go ├── package-lock.json ├── package.json ├── plain.go └── writer.go /.github/CODEOWNER: -------------------------------------------------------------------------------- 1 | * @ory/maintainers 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/FUNDING.yml 3 | 4 | # These are supported funding model platforms 5 | 6 | # github: 7 | patreon: _ory 8 | open_collective: ory 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/BUG-REPORT.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/ISSUE_TEMPLATE/BUG-REPORT.yml 3 | 4 | description: "Create a bug report" 5 | labels: 6 | - bug 7 | name: "Bug Report" 8 | body: 9 | - attributes: 10 | value: "Thank you for taking the time to fill out this bug report!\n" 11 | type: markdown 12 | - attributes: 13 | label: "Preflight checklist" 14 | options: 15 | - label: 16 | "I could not find a solution in the existing issues, docs, nor 17 | discussions." 18 | required: true 19 | - label: 20 | "I agree to follow this project's [Code of 21 | Conduct](https://github.com/ory/herodot/blob/master/CODE_OF_CONDUCT.md)." 22 | required: true 23 | - label: 24 | "I have read and am following this repository's [Contribution 25 | Guidelines](https://github.com/ory/herodot/blob/master/CONTRIBUTING.md)." 26 | required: true 27 | - label: 28 | "I have joined the [Ory Community Slack](https://slack.ory.sh)." 29 | - label: 30 | "I am signed up to the [Ory Security Patch 31 | Newsletter](https://www.ory.sh/l/sign-up-newsletter)." 32 | id: checklist 33 | type: checkboxes 34 | - attributes: 35 | description: 36 | "Enter the slug or API URL of the affected Ory Network project. Leave 37 | empty when you are self-hosting." 38 | label: "Ory Network Project" 39 | placeholder: "https://.projects.oryapis.com" 40 | id: ory-network-project 41 | type: input 42 | - attributes: 43 | description: "A clear and concise description of what the bug is." 44 | label: "Describe the bug" 45 | placeholder: "Tell us what you see!" 46 | id: describe-bug 47 | type: textarea 48 | validations: 49 | required: true 50 | - attributes: 51 | description: | 52 | Clear, formatted, and easy to follow steps to reproduce the behavior: 53 | placeholder: | 54 | Steps to reproduce the behavior: 55 | 56 | 1. Run `docker run ....` 57 | 2. Make API Request to with `curl ...` 58 | 3. Request fails with response: `{"some": "error"}` 59 | label: "Reproducing the bug" 60 | id: reproduce-bug 61 | type: textarea 62 | validations: 63 | required: true 64 | - attributes: 65 | description: 66 | "Please copy and paste any relevant log output. This will be 67 | automatically formatted into code, so no need for backticks. Please 68 | redact any sensitive information" 69 | label: "Relevant log output" 70 | render: shell 71 | placeholder: | 72 | log=error .... 73 | id: logs 74 | type: textarea 75 | - attributes: 76 | description: 77 | "Please copy and paste any relevant configuration. This will be 78 | automatically formatted into code, so no need for backticks. Please 79 | redact any sensitive information!" 80 | label: "Relevant configuration" 81 | render: yml 82 | placeholder: | 83 | server: 84 | admin: 85 | port: 1234 86 | id: config 87 | type: textarea 88 | - attributes: 89 | description: "What version of our software are you running?" 90 | label: Version 91 | id: version 92 | type: input 93 | validations: 94 | required: true 95 | - attributes: 96 | label: "On which operating system are you observing this issue?" 97 | options: 98 | - Ory Network 99 | - macOS 100 | - Linux 101 | - Windows 102 | - FreeBSD 103 | - Other 104 | id: operating-system 105 | type: dropdown 106 | - attributes: 107 | label: "In which environment are you deploying?" 108 | options: 109 | - Ory Network 110 | - Docker 111 | - "Docker Compose" 112 | - "Kubernetes with Helm" 113 | - Kubernetes 114 | - Binary 115 | - Other 116 | id: deployment 117 | type: dropdown 118 | - attributes: 119 | description: "Add any other context about the problem here." 120 | label: Additional Context 121 | id: additional 122 | type: textarea 123 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/DESIGN-DOC.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/ISSUE_TEMPLATE/DESIGN-DOC.yml 3 | 4 | description: 5 | "A design document is needed for non-trivial changes to the code base." 6 | labels: 7 | - rfc 8 | name: "Design Document" 9 | body: 10 | - attributes: 11 | value: | 12 | Thank you for writing this design document. 13 | 14 | One of the key elements of Ory's software engineering culture is the use of defining software designs through design docs. These are relatively informal documents that the primary author or authors of a software system or application create before they embark on the coding project. The design doc documents the high level implementation strategy and key design decisions with emphasis on the trade-offs that were considered during those decisions. 15 | 16 | Ory is leaning heavily on [Google's design docs process](https://www.industrialempathy.com/posts/design-docs-at-google/) 17 | and [Golang Proposals](https://github.com/golang/proposal). 18 | 19 | Writing a design doc before contributing your change ensures that your ideas are checked with 20 | the community and maintainers. It will save you a lot of time developing things that might need to be changed 21 | after code reviews, and your pull requests will be merged faster. 22 | type: markdown 23 | - attributes: 24 | label: "Preflight checklist" 25 | options: 26 | - label: 27 | "I could not find a solution in the existing issues, docs, nor 28 | discussions." 29 | required: true 30 | - label: 31 | "I agree to follow this project's [Code of 32 | Conduct](https://github.com/ory/herodot/blob/master/CODE_OF_CONDUCT.md)." 33 | required: true 34 | - label: 35 | "I have read and am following this repository's [Contribution 36 | Guidelines](https://github.com/ory/herodot/blob/master/CONTRIBUTING.md)." 37 | required: true 38 | - label: 39 | "I have joined the [Ory Community Slack](https://slack.ory.sh)." 40 | - label: 41 | "I am signed up to the [Ory Security Patch 42 | Newsletter](https://www.ory.sh/l/sign-up-newsletter)." 43 | id: checklist 44 | type: checkboxes 45 | - attributes: 46 | description: 47 | "Enter the slug or API URL of the affected Ory Network project. Leave 48 | empty when you are self-hosting." 49 | label: "Ory Network Project" 50 | placeholder: "https://.projects.oryapis.com" 51 | id: ory-network-project 52 | type: input 53 | - attributes: 54 | description: | 55 | This section gives the reader a very rough overview of the landscape in which the new system is being built and what is actually being built. This isn’t a requirements doc. Keep it succinct! The goal is that readers are brought up to speed but some previous knowledge can be assumed and detailed info can be linked to. This section should be entirely focused on objective background facts. 56 | label: "Context and scope" 57 | id: scope 58 | type: textarea 59 | validations: 60 | required: true 61 | 62 | - attributes: 63 | description: | 64 | A short list of bullet points of what the goals of the system are, and, sometimes more importantly, what non-goals are. Note, that non-goals aren’t negated goals like “The system shouldn’t crash”, but rather things that could reasonably be goals, but are explicitly chosen not to be goals. A good example would be “ACID compliance”; when designing a database, you’d certainly want to know whether that is a goal or non-goal. And if it is a non-goal you might still select a solution that provides it, if it doesn’t introduce trade-offs that prevent achieving the goals. 65 | label: "Goals and non-goals" 66 | id: goals 67 | type: textarea 68 | validations: 69 | required: true 70 | 71 | - attributes: 72 | description: | 73 | This section should start with an overview and then go into details. 74 | The design doc is the place to write down the trade-offs you made in designing your software. Focus on those trade-offs to produce a useful document with long-term value. That is, given the context (facts), goals and non-goals (requirements), the design doc is the place to suggest solutions and show why a particular solution best satisfies those goals. 75 | 76 | The point of writing a document over a more formal medium is to provide the flexibility to express the problem at hand in an appropriate manner. Because of this, there is no explicit guidance on how to actually describe the design. 77 | label: "The design" 78 | id: design 79 | type: textarea 80 | validations: 81 | required: true 82 | 83 | - attributes: 84 | description: | 85 | If the system under design exposes an API, then sketching out that API is usually a good idea. In most cases, however, one should withstand the temptation to copy-paste formal interface or data definitions into the doc as these are often verbose, contain unnecessary detail and quickly get out of date. Instead, focus on the parts that are relevant to the design and its trade-offs. 86 | label: "APIs" 87 | id: apis 88 | type: textarea 89 | 90 | - attributes: 91 | description: | 92 | Systems that store data should likely discuss how and in what rough form this happens. Similar to the advice on APIs, and for the same reasons, copy-pasting complete schema definitions should be avoided. Instead, focus on the parts that are relevant to the design and its trade-offs. 93 | label: "Data storage" 94 | id: persistence 95 | type: textarea 96 | 97 | - attributes: 98 | description: | 99 | Design docs should rarely contain code, or pseudo-code except in situations where novel algorithms are described. As appropriate, link to prototypes that show the feasibility of the design. 100 | label: "Code and pseudo-code" 101 | id: pseudocode 102 | type: textarea 103 | 104 | - attributes: 105 | description: | 106 | One of the primary factors that would influence the shape of a software design and hence the design doc, is the degree of constraint of the solution space. 107 | 108 | On one end of the extreme is the “greenfield software project”, where all we know are the goals, and the solution can be whatever makes the most sense. Such a document may be wide-ranging, but it also needs to quickly define a set of rules that allow zooming in on a manageable set of solutions. 109 | 110 | On the other end are systems where the possible solutions are very well defined, but it isn't at all obvious how they could even be combined to achieve the goals. This may be a legacy system that is difficult to change and wasn't designed to do what you want it to do or a library design that needs to operate within the constraints of the host programming language. 111 | 112 | In this situation, you may be able to enumerate all the things you can do relatively easily, but you need to creatively put those things together to achieve the goals. There may be multiple solutions, and none of them are great, and hence such a document should focus on selecting the best way given all identified trade-offs. 113 | label: "Degree of constraint" 114 | id: constrait 115 | type: textarea 116 | 117 | - attributes: 118 | description: | 119 | This section lists alternative designs that would have reasonably achieved similar outcomes. The focus should be on the trade-offs that each respective design makes and how those trade-offs led to the decision to select the design that is the primary topic of the document. 120 | 121 | While it is fine to be succinct about a solution that ended up not being selected, this section is one of the most important ones as it shows very explicitly why the selected solution is the best given the project goals and how other solutions, that the reader may be wondering about, introduce trade-offs that are less desirable given the goals. 122 | 123 | label: Alternatives considered 124 | id: alternatives 125 | type: textarea 126 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE-REQUEST.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/ISSUE_TEMPLATE/FEATURE-REQUEST.yml 3 | 4 | description: 5 | "Suggest an idea for this project without a plan for implementation" 6 | labels: 7 | - feat 8 | name: "Feature Request" 9 | body: 10 | - attributes: 11 | value: | 12 | Thank you for suggesting an idea for this project! 13 | 14 | If you already have a plan to implement a feature or a change, please create a [design document](https://github.com/aeneasr/gh-template-test/issues/new?assignees=&labels=rfc&template=DESIGN-DOC.yml) instead if the change is non-trivial! 15 | type: markdown 16 | - attributes: 17 | label: "Preflight checklist" 18 | options: 19 | - label: 20 | "I could not find a solution in the existing issues, docs, nor 21 | discussions." 22 | required: true 23 | - label: 24 | "I agree to follow this project's [Code of 25 | Conduct](https://github.com/ory/herodot/blob/master/CODE_OF_CONDUCT.md)." 26 | required: true 27 | - label: 28 | "I have read and am following this repository's [Contribution 29 | Guidelines](https://github.com/ory/herodot/blob/master/CONTRIBUTING.md)." 30 | required: true 31 | - label: 32 | "I have joined the [Ory Community Slack](https://slack.ory.sh)." 33 | - label: 34 | "I am signed up to the [Ory Security Patch 35 | Newsletter](https://www.ory.sh/l/sign-up-newsletter)." 36 | id: checklist 37 | type: checkboxes 38 | - attributes: 39 | description: 40 | "Enter the slug or API URL of the affected Ory Network project. Leave 41 | empty when you are self-hosting." 42 | label: "Ory Network Project" 43 | placeholder: "https://.projects.oryapis.com" 44 | id: ory-network-project 45 | type: input 46 | - attributes: 47 | description: 48 | "Is your feature request related to a problem? Please describe." 49 | label: "Describe your problem" 50 | placeholder: 51 | "A clear and concise description of what the problem is. Ex. I'm always 52 | frustrated when [...]" 53 | id: problem 54 | type: textarea 55 | validations: 56 | required: true 57 | - attributes: 58 | description: | 59 | Describe the solution you'd like 60 | placeholder: | 61 | A clear and concise description of what you want to happen. 62 | label: "Describe your ideal solution" 63 | id: solution 64 | type: textarea 65 | validations: 66 | required: true 67 | - attributes: 68 | description: "Describe alternatives you've considered" 69 | label: "Workarounds or alternatives" 70 | id: alternatives 71 | type: textarea 72 | validations: 73 | required: true 74 | - attributes: 75 | description: "What version of our software are you running?" 76 | label: Version 77 | id: version 78 | type: input 79 | validations: 80 | required: true 81 | - attributes: 82 | description: 83 | "Add any other context or screenshots about the feature request here." 84 | label: Additional Context 85 | id: additional 86 | type: textarea 87 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/ISSUE_TEMPLATE/config.yml 3 | 4 | blank_issues_enabled: false 5 | contact_links: 6 | - name: Ory Herodot Forum 7 | url: https://github.com/orgs/ory/discussions 8 | about: 9 | Please ask and answer questions here, show your implementations and 10 | discuss ideas. 11 | - name: Ory Chat 12 | url: https://www.ory.sh/chat 13 | about: 14 | Hang out with other Ory community members to ask and answer questions. 15 | -------------------------------------------------------------------------------- /.github/auto_assign.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/auto_assign.yml 3 | 4 | # Set to true to add reviewers to pull requests 5 | addReviewers: true 6 | 7 | # Set to true to add assignees to pull requests 8 | addAssignees: true 9 | 10 | # A list of reviewers to be added to pull requests (GitHub user name) 11 | assignees: 12 | - ory/maintainers 13 | 14 | # A number of reviewers added to the pull request 15 | # Set 0 to add all the reviewers (default: 0) 16 | numberOfReviewers: 0 17 | -------------------------------------------------------------------------------- /.github/config.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/config.yml 3 | 4 | todo: 5 | keyword: "@todo" 6 | label: todo 7 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 12 | 13 | ## Related Issue or Design Document 14 | 15 | 29 | 30 | ## Checklist 31 | 32 | 36 | 37 | - [ ] I have read the [contributing guidelines](../blob/master/CONTRIBUTING.md) and signed the CLA. 38 | - [ ] I have referenced an issue containing the design document if my change introduces a new feature. 39 | - [ ] I have read the [security policy](../security/policy). 40 | - [ ] I confirm that this pull request does not address a security vulnerability. 41 | If this pull request addresses a security vulnerability, 42 | I confirm that I got approval (please contact [security@ory.sh](mailto:security@ory.sh)) from the maintainers to push the changes. 43 | - [ ] I have added tests that prove my fix is effective or that my feature works. 44 | - [ ] I have added the necessary documentation within the code base (if appropriate). 45 | 46 | ## Further comments 47 | 48 | 52 | -------------------------------------------------------------------------------- /.github/workflows/closed_references.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/workflows/closed_references.yml 3 | 4 | name: Closed Reference Notifier 5 | 6 | on: 7 | schedule: 8 | - cron: "0 0 * * *" 9 | workflow_dispatch: 10 | inputs: 11 | issueLimit: 12 | description: Max. number of issues to create 13 | required: true 14 | default: "5" 15 | 16 | jobs: 17 | find_closed_references: 18 | if: github.repository_owner == 'ory' 19 | runs-on: ubuntu-latest 20 | name: Find closed references 21 | steps: 22 | - uses: actions/checkout@v2 23 | - uses: actions/setup-node@v2-beta 24 | with: 25 | node-version: "14" 26 | - uses: ory/closed-reference-notifier@v1 27 | with: 28 | token: ${{ secrets.GITHUB_TOKEN }} 29 | issueLabels: upstream,good first issue,help wanted 30 | issueLimit: ${{ github.event.inputs.issueLimit || '5' }} 31 | -------------------------------------------------------------------------------- /.github/workflows/conventional_commits.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/workflows/conventional_commits.yml 3 | 4 | name: Conventional commits 5 | 6 | # This GitHub CI Action enforces that pull request titles follow conventional commits. 7 | # More info at https://www.conventionalcommits.org. 8 | # 9 | # The Ory-wide defaults for commit titles and scopes are below. 10 | # Your repository can add/replace elements via a configuration file at the path below. 11 | # More info at https://github.com/ory/ci/blob/master/conventional_commit_config/README.md 12 | 13 | on: 14 | pull_request_target: 15 | types: 16 | - edited 17 | - opened 18 | - ready_for_review 19 | - reopened 20 | # pull_request: # for debugging, uses config in local branch but supports only Pull Requests from this repo 21 | 22 | jobs: 23 | main: 24 | name: Validate PR title 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v3 28 | - id: config 29 | uses: ory/ci/conventional_commit_config@master 30 | with: 31 | config_path: .github/conventional_commits.json 32 | default_types: | 33 | feat 34 | fix 35 | revert 36 | docs 37 | style 38 | refactor 39 | test 40 | build 41 | autogen 42 | security 43 | ci 44 | chore 45 | default_scopes: | 46 | deps 47 | docs 48 | default_require_scope: false 49 | - uses: amannn/action-semantic-pull-request@v4 50 | env: 51 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 52 | with: 53 | types: ${{ steps.config.outputs.types }} 54 | scopes: ${{ steps.config.outputs.scopes }} 55 | requireScope: ${{ steps.config.outputs.requireScope }} 56 | subjectPattern: ^(?![A-Z]).+$ 57 | subjectPatternError: | 58 | The subject should start with a lowercase letter, yours is uppercase: 59 | "{subject}" 60 | -------------------------------------------------------------------------------- /.github/workflows/format.yml: -------------------------------------------------------------------------------- 1 | name: Format 2 | 3 | on: 4 | pull_request: 5 | push: 6 | 7 | jobs: 8 | format: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-go@v3 13 | with: 14 | go-version: "1.24" 15 | - run: make format 16 | - name: Indicate formatting issues 17 | run: git diff HEAD --exit-code --color 18 | -------------------------------------------------------------------------------- /.github/workflows/labels.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/workflows/labels.yml 3 | 4 | name: Synchronize Issue Labels 5 | 6 | on: 7 | workflow_dispatch: 8 | push: 9 | branches: 10 | - master 11 | 12 | jobs: 13 | milestone: 14 | if: github.repository_owner == 'ory' 15 | name: Synchronize Issue Labels 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v2 20 | - name: Synchronize Issue Labels 21 | uses: ory/label-sync-action@v0 22 | with: 23 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 24 | dry: false 25 | forced: true 26 | -------------------------------------------------------------------------------- /.github/workflows/licenses.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/workflows/licenses.yml 3 | 4 | name: Licenses 5 | 6 | on: 7 | pull_request: 8 | push: 9 | branches: 10 | - main 11 | - v3 12 | - master 13 | 14 | jobs: 15 | licenses: 16 | name: License compliance 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Install script 20 | uses: ory/ci/licenses/setup@master 21 | with: 22 | token: ${{ secrets.ORY_BOT_PAT || secrets.GITHUB_TOKEN }} 23 | - name: Check licenses 24 | uses: ory/ci/licenses/check@master 25 | - name: Write, commit, push licenses 26 | uses: ory/ci/licenses/write@master 27 | if: 28 | ${{ github.ref == 'refs/heads/main' || github.ref == 29 | 'refs/heads/master' || github.ref == 'refs/heads/v3' }} 30 | with: 31 | author-email: 32 | ${{ secrets.ORY_BOT_PAT && 33 | '60093411+ory-bot@users.noreply.github.com' || 34 | format('{0}@users.noreply.github.com', github.actor) }} 35 | author-name: ${{ secrets.ORY_BOT_PAT && 'ory-bot' || github.actor }} 36 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED, DO NOT EDIT! 2 | # Please edit the original at https://github.com/ory/meta/blob/master/templates/repository/common/.github/workflows/stale.yml 3 | 4 | name: "Close Stale Issues" 5 | on: 6 | workflow_dispatch: 7 | schedule: 8 | - cron: "0 0 * * *" 9 | 10 | jobs: 11 | stale: 12 | if: github.repository_owner == 'ory' 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/stale@v4 16 | with: 17 | repo-token: ${{ secrets.GITHUB_TOKEN }} 18 | stale-issue-message: | 19 | Hello contributors! 20 | 21 | I am marking this issue as stale as it has not received any engagement from the community or maintainers for a year. That does not imply that the issue has no merit! If you feel strongly about this issue 22 | 23 | - open a PR referencing and resolving the issue; 24 | - leave a comment on it and discuss ideas on how you could contribute towards resolving it; 25 | - leave a comment and describe in detail why this issue is critical for your use case; 26 | - open a new issue with updated details and a plan for resolving the issue. 27 | 28 | Throughout its lifetime, Ory has received over 10.000 issues and PRs. To sustain that growth, we need to prioritize and focus on issues that are important to the community. A good indication of importance, and thus priority, is activity on a topic. 29 | 30 | Unfortunately, [burnout](https://www.jeffgeerling.com/blog/2016/why-i-close-prs-oss-project-maintainer-notes) has become a [topic](https://opensource.guide/best-practices/#its-okay-to-hit-pause) of [concern](https://docs.brew.sh/Maintainers-Avoiding-Burnout) amongst open-source projects. 31 | 32 | It can lead to severe personal and health issues as well as [opening](https://haacked.com/archive/2019/05/28/maintainer-burnout/) catastrophic [attack vectors](https://www.gradiant.org/en/blog/open-source-maintainer-burnout-as-an-attack-surface/). 33 | 34 | The motivation for this automation is to help prioritize issues in the backlog and not ignore, reject, or belittle anyone. 35 | 36 | If this issue was marked as stale erroneously you can exempt it by adding the `backlog` label, assigning someone, or setting a milestone for it. 37 | 38 | Thank you for your understanding and to anyone who participated in the conversation! And as written above, please do participate in the conversation if this topic is important to you! 39 | 40 | Thank you 🙏✌️ 41 | stale-issue-label: "stale" 42 | exempt-issue-labels: "bug,blocking,docs,backlog" 43 | days-before-stale: 365 44 | days-before-close: 30 45 | exempt-milestones: true 46 | exempt-assignees: true 47 | only-pr-labels: "stale" 48 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: "Run Tests and Lint Code" 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | test: 13 | name: Run Tests and Lint Code 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout repository 17 | uses: actions/checkout@v2 18 | - uses: actions/setup-go@v2 19 | with: 20 | go-version: "1.24" 21 | - run: go test -coverprofile=coverage.out -timeout=1m ./... 22 | - run: go tool gcov2lcov -infile=coverage.out -outfile=coverage.lcov 23 | - name: Coveralls 24 | uses: coverallsapp/github-action@master 25 | with: 26 | github-token: ${{ secrets.GITHUB_TOKEN }} 27 | path-to-lcov: coverage.lcov 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bin/ 2 | .idea/ 3 | node_modules/ 4 | *.iml 5 | *.exe 6 | .vagrant 7 | *.log 8 | *.stackdump 9 | .DS_Store 10 | vendor/ 11 | .hydra.yml 12 | cover.out 13 | output/ 14 | _book/ 15 | dist/ 16 | coverage.* 17 | .bin 18 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .github/pull_request_template.md 2 | CONTRIBUTING.md 3 | -------------------------------------------------------------------------------- /.reference-ignore: -------------------------------------------------------------------------------- 1 | **/node_modules 2 | docs 3 | CHANGELOG.md 4 | -------------------------------------------------------------------------------- /.reports/dep-licenses.csv: -------------------------------------------------------------------------------- 1 | 2 | "github.com/stretchr/testify","MIT" 3 | 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Contributor Covenant Code of Conduct 5 | 6 | ## Our Pledge 7 | 8 | We as members, contributors, and leaders pledge to make participation in our 9 | community a harassment-free experience for everyone, regardless of age, body 10 | size, visible or invisible disability, ethnicity, sex characteristics, gender 11 | identity and expression, level of experience, education, socio-economic status, 12 | nationality, personal appearance, race, caste, color, religion, or sexual 13 | identity and orientation. 14 | 15 | We pledge to act and interact in ways that contribute to an open, welcoming, 16 | diverse, inclusive, and healthy community. 17 | 18 | ## Our Standards 19 | 20 | Examples of behavior that contributes to a positive environment for our 21 | community include: 22 | 23 | - Demonstrating empathy and kindness toward other people 24 | - Being respectful of differing opinions, viewpoints, and experiences 25 | - Giving and gracefully accepting constructive feedback 26 | - Accepting responsibility and apologizing to those affected by our mistakes, 27 | and learning from the experience 28 | - Focusing on what is best not just for us as individuals, but for the overall 29 | community 30 | 31 | Examples of unacceptable behavior include: 32 | 33 | - The use of sexualized language or imagery, and sexual attention or advances of 34 | any kind 35 | - Trolling, insulting or derogatory comments, and personal or political attacks 36 | - Public or private harassment 37 | - Publishing others' private information, such as a physical or email address, 38 | without their explicit permission 39 | - Other conduct which could reasonably be considered inappropriate in a 40 | professional setting 41 | 42 | ## Open Source Community Support 43 | 44 | Ory Open source software is collaborative and based on contributions by 45 | developers in the Ory community. There is no obligation from Ory to help with 46 | individual problems. If Ory open source software is used in production in a 47 | for-profit company or enterprise environment, we mandate a paid support contract 48 | where Ory is obligated under their service level agreements (SLAs) to offer a 49 | defined level of availability and responsibility. For more information about 50 | paid support please contact us at sales@ory.sh. 51 | 52 | ## Enforcement Responsibilities 53 | 54 | Community leaders are responsible for clarifying and enforcing our standards of 55 | acceptable behavior and will take appropriate and fair corrective action in 56 | response to any behavior that they deem inappropriate, threatening, offensive, 57 | or harmful. 58 | 59 | Community leaders have the right and responsibility to remove, edit, or reject 60 | comments, commits, code, wiki edits, issues, and other contributions that are 61 | not aligned to this Code of Conduct, and will communicate reasons for moderation 62 | decisions when appropriate. 63 | 64 | ## Scope 65 | 66 | This Code of Conduct applies within all community spaces, and also applies when 67 | an individual is officially representing the community in public spaces. 68 | Examples of representing our community include using an official e-mail address, 69 | posting via an official social media account, or acting as an appointed 70 | representative at an online or offline event. 71 | 72 | ## Enforcement 73 | 74 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 75 | reported to the community leaders responsible for enforcement at 76 | [office@ory.sh](mailto:office@ory.sh). All complaints will be reviewed and 77 | investigated promptly and fairly. 78 | 79 | All community leaders are obligated to respect the privacy and security of the 80 | reporter of any incident. 81 | 82 | ## Enforcement Guidelines 83 | 84 | Community leaders will follow these Community Impact Guidelines in determining 85 | the consequences for any action they deem in violation of this Code of Conduct: 86 | 87 | ### 1. Correction 88 | 89 | **Community Impact**: Use of inappropriate language or other behavior deemed 90 | unprofessional or unwelcome in the community. 91 | 92 | **Consequence**: A private, written warning from community leaders, providing 93 | clarity around the nature of the violation and an explanation of why the 94 | behavior was inappropriate. A public apology may be requested. 95 | 96 | ### 2. Warning 97 | 98 | **Community Impact**: A violation through a single incident or series of 99 | actions. 100 | 101 | **Consequence**: A warning with consequences for continued behavior. No 102 | interaction with the people involved, including unsolicited interaction with 103 | those enforcing the Code of Conduct, for a specified period of time. This 104 | includes avoiding interactions in community spaces as well as external channels 105 | like social media. Violating these terms may lead to a temporary or permanent 106 | ban. 107 | 108 | ### 3. Temporary Ban 109 | 110 | **Community Impact**: A serious violation of community standards, including 111 | sustained inappropriate behavior. 112 | 113 | **Consequence**: A temporary ban from any sort of interaction or public 114 | communication with the community for a specified period of time. No public or 115 | private interaction with the people involved, including unsolicited interaction 116 | with those enforcing the Code of Conduct, is allowed during this period. 117 | Violating these terms may lead to a permanent ban. 118 | 119 | ### 4. Permanent Ban 120 | 121 | **Community Impact**: Demonstrating a pattern of violation of community 122 | standards, including sustained inappropriate behavior, harassment of an 123 | individual, or aggression toward or disparagement of classes of individuals. 124 | 125 | **Consequence**: A permanent ban from any sort of public interaction within the 126 | community. 127 | 128 | ## Attribution 129 | 130 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 131 | version 2.1, available at 132 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 133 | 134 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 135 | enforcement ladder][mozilla coc]. 136 | 137 | For answers to common questions about this code of conduct, see the FAQ at 138 | [https://www.contributor-covenant.org/faq][faq]. Translations are available at 139 | [https://www.contributor-covenant.org/translations][translations]. 140 | 141 | [homepage]: https://www.contributor-covenant.org 142 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 143 | [mozilla coc]: https://github.com/mozilla/diversity 144 | [faq]: https://www.contributor-covenant.org/faq 145 | [translations]: https://www.contributor-covenant.org/translations 146 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Contribute to Ory Herodot 5 | 6 | 7 | 8 | 9 | - [Introduction](#introduction) 10 | - [FAQ](#faq) 11 | - [How can I contribute?](#how-can-i-contribute) 12 | - [Communication](#communication) 13 | - [Contribute examples or community projects](#contribute-examples-or-community-projects) 14 | - [Contribute code](#contribute-code) 15 | - [Contribute documentation](#contribute-documentation) 16 | - [Disclosing vulnerabilities](#disclosing-vulnerabilities) 17 | - [Code style](#code-style) 18 | - [Working with forks](#working-with-forks) 19 | - [Conduct](#conduct) 20 | 21 | 22 | 23 | ## Introduction 24 | 25 | _Please note_: We take Ory Herodot's security and our users' trust very 26 | seriously. If you believe you have found a security issue in Ory Herodot, 27 | please disclose it by contacting us at security@ory.sh. 28 | 29 | There are many ways in which you can contribute. The goal of this document is to 30 | provide a high-level overview of how you can get involved in Ory. 31 | 32 | As a potential contributor, your changes and ideas are welcome at any hour of 33 | the day or night, on weekdays, weekends, and holidays. Please do not ever 34 | hesitate to ask a question or send a pull request. 35 | 36 | If you are unsure, just ask or submit the issue or pull request anyways. You 37 | won't be yelled at for giving it your best effort. The worst that can happen is 38 | that you'll be politely asked to change something. We appreciate any sort of 39 | contributions and don't want a wall of rules to get in the way of that. 40 | 41 | That said, if you want to ensure that a pull request is likely to be merged, 42 | talk to us! You can find out our thoughts and ensure that your contribution 43 | won't clash with Ory 44 | Herodot's direction. A great way to 45 | do this is via 46 | [Ory Herodot Discussions](https://github.com/orgs/ory/discussions) 47 | or the [Ory Chat](https://www.ory.sh/chat). 48 | 49 | ## FAQ 50 | 51 | - I am new to the community. Where can I find the 52 | [Ory Community Code of Conduct?](https://github.com/ory/herodot/blob/master/CODE_OF_CONDUCT.md) 53 | 54 | - I have a question. Where can I get 55 | [answers to questions regarding Ory Herodot?](#communication) 56 | 57 | - I would like to contribute but I am not sure how. Are there 58 | [easy ways to contribute?](#how-can-i-contribute) 59 | [Or good first issues?](https://github.com/search?l=&o=desc&q=label%3A%22help+wanted%22+label%3A%22good+first+issue%22+is%3Aopen+user%3Aory+user%3Aory-corp&s=updated&type=Issues) 60 | 61 | - I want to talk to other Ory Herodot users. 62 | [How can I become a part of the community?](#communication) 63 | 64 | - I would like to know what I am agreeing to when I contribute to Ory 65 | Herodot. 66 | Does Ory have 67 | [a Contributors License Agreement?](https://cla-assistant.io/ory/herodot) 68 | 69 | - I would like updates about new versions of Ory Herodot. 70 | [How are new releases announced?](https://www.ory.sh/l/sign-up-newsletter) 71 | 72 | ## How can I contribute? 73 | 74 | If you want to start to contribute code right away, take a look at the 75 | [list of good first issues](https://github.com/ory/herodot/labels/good%20first%20issue). 76 | 77 | There are many other ways you can contribute. Here are a few things you can do 78 | to help out: 79 | 80 | - **Give us a star.** It may not seem like much, but it really makes a 81 | difference. This is something that everyone can do to help out Ory Herodot. 82 | Github stars help the project gain visibility and stand out. 83 | 84 | - **Join the community.** Sometimes helping people can be as easy as listening 85 | to their problems and offering a different perspective. Join our Slack, have a 86 | look at discussions in the forum and take part in community events. More info 87 | on this in [Communication](#communication). 88 | 89 | - **Answer discussions.** At all times, there are several unanswered discussions 90 | on GitHub. You can see an 91 | [overview here](https://github.com/discussions?discussions_q=is%3Aunanswered+org%3Aory+sort%3Aupdated-desc). 92 | If you think you know an answer or can provide some information that might 93 | help, please share it! Bonus: You get GitHub achievements for answered 94 | discussions. 95 | 96 | - **Help with open issues.** We have a lot of open issues for Ory Herodot and 97 | some of them may lack necessary information, some are duplicates of older 98 | issues. You can help out by guiding people through the process of filling out 99 | the issue template, asking for clarifying information or pointing them to 100 | existing issues that match their description of the problem. 101 | 102 | - **Review documentation changes.** Most documentation just needs a review for 103 | proper spelling and grammar. If you think a document can be improved in any 104 | way, feel free to hit the `edit` button at the top of the page. More info on 105 | contributing to the documentation [here](#contribute-documentation). 106 | 107 | - **Help with tests.** Pull requests may lack proper tests or test plans. These 108 | are needed for the change to be implemented safely. 109 | 110 | ## Communication 111 | 112 | We use [Slack](https://www.ory.sh/chat). You are welcome to drop in and ask 113 | questions, discuss bugs and feature requests, talk to other users of Ory, etc. 114 | 115 | Check out [Ory Herodot Discussions](https://github.com/orgs/ory/discussions). This is a great place for 116 | in-depth discussions and lots of code examples, logs and similar data. 117 | 118 | You can also join our community calls if you want to speak to the Ory team 119 | directly or ask some questions. You can find more info and participate in 120 | [Slack](https://www.ory.sh/chat) in the #community-call channel. 121 | 122 | If you want to receive regular notifications about updates to Ory Herodot, 123 | consider joining the mailing list. We will _only_ send you vital information on 124 | the projects that you are interested in. 125 | 126 | Also, [follow us on Twitter](https://twitter.com/orycorp). 127 | 128 | ## Contribute examples or community projects 129 | 130 | One of the most impactful ways to contribute is by adding code examples or other 131 | Ory-related code. You can find an overview of community code in the 132 | [awesome-ory](https://github.com/ory/awesome-ory) repository. 133 | 134 | _If you would like to contribute a new example, we would love to hear from you!_ 135 | 136 | Please [open a pull request at awesome-ory](https://github.com/ory/awesome-ory/) 137 | to add your example or Ory-related project to the awesome-ory README. 138 | 139 | ## Contribute code 140 | 141 | Unless you are fixing a known bug, we **strongly** recommend discussing it with 142 | the core team via a GitHub issue or [in our chat](https://www.ory.sh/chat) 143 | before getting started to ensure your work is consistent with Ory Herodot's 144 | roadmap and architecture. 145 | 146 | All contributions are made via pull requests. To make a pull request, you will 147 | need a GitHub account; if you are unclear on this process, see GitHub's 148 | documentation on [forking](https://help.github.com/articles/fork-a-repo) and 149 | [pull requests](https://help.github.com/articles/using-pull-requests). Pull 150 | requests should be targeted at the `master` branch. Before creating a pull 151 | request, go through this checklist: 152 | 153 | 1. Create a feature branch off of `master` so that changes do not get mixed up. 154 | 1. [Rebase](http://git-scm.com/book/en/Git-Branching-Rebasing) your local 155 | changes against the `master` branch. 156 | 1. Run the full project test suite with the `go test -tags sqlite ./...` (or 157 | equivalent) command and confirm that it passes. 158 | 1. Run `make format` 159 | 1. Add a descriptive prefix to commits. This ensures a uniform commit history 160 | and helps structure the changelog. Please refer to this 161 | [Convential Commits configuration](https://github.com/ory/herodot/blob/master/.github/workflows/conventional_commits.yml) 162 | for the list of accepted prefixes. You can read more about the Conventional 163 | Commit specification 164 | [at their site](https://www.conventionalcommits.org/en/v1.0.0/). 165 | 166 | If a pull request is not ready to be reviewed yet 167 | [it should be marked as a "Draft"](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request). 168 | 169 | Before your contributions can be reviewed you need to sign our 170 | [Contributor License Agreement](https://cla-assistant.io/ory/herodot). 171 | 172 | This agreement defines the terms under which your code is contributed to Ory. 173 | More specifically it declares that you have the right to, and actually do, grant 174 | us the rights to use your contribution. You can see the Apache 2.0 license under 175 | which our projects are published 176 | [here](https://github.com/ory/meta/blob/master/LICENSE). 177 | 178 | When pull requests fail the automated testing stages (for example unit or E2E 179 | tests), authors are expected to update their pull requests to address the 180 | failures until the tests pass. 181 | 182 | Pull requests eligible for review 183 | 184 | 1. follow the repository's code formatting conventions; 185 | 2. include tests that prove that the change works as intended and does not add 186 | regressions; 187 | 3. document the changes in the code and/or the project's documentation; 188 | 4. pass the CI pipeline; 189 | 5. have signed our 190 | [Contributor License Agreement](https://cla-assistant.io/ory/herodot); 191 | 6. include a proper git commit message following the 192 | [Conventional Commit Specification](https://www.conventionalcommits.org/en/v1.0.0/). 193 | 194 | If all of these items are checked, the pull request is ready to be reviewed and 195 | you should change the status to "Ready for review" and 196 | [request review from a maintainer](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/requesting-a-pull-request-review). 197 | 198 | Reviewers will approve the pull request once they are satisfied with the patch. 199 | 200 | ## Contribute documentation 201 | 202 | Please provide documentation when changing, removing, or adding features. All 203 | Ory Documentation resides in the 204 | [Ory documentation repository](https://github.com/ory/docs/). For further 205 | instructions please head over to the Ory Documentation 206 | [README.md](https://github.com/ory/docs/blob/master/README.md). 207 | 208 | ## Disclosing vulnerabilities 209 | 210 | Please disclose vulnerabilities exclusively to 211 | [security@ory.sh](mailto:security@ory.sh). Do not use GitHub issues. 212 | 213 | ## Code style 214 | 215 | Please run `make format` to format all source code following the Ory standard. 216 | 217 | ### Working with forks 218 | 219 | ```bash 220 | # First you clone the original repository 221 | git clone git@github.com:ory/ory/herodot.git 222 | 223 | # Next you add a git remote that is your fork: 224 | git remote add fork git@github.com:/ory/herodot.git 225 | 226 | # Next you fetch the latest changes from origin for master: 227 | git fetch origin 228 | git checkout master 229 | git pull --rebase 230 | 231 | # Next you create a new feature branch off of master: 232 | git checkout my-feature-branch 233 | 234 | # Now you do your work and commit your changes: 235 | git add -A 236 | git commit -a -m "fix: this is the subject line" -m "This is the body line. Closes #123" 237 | 238 | # And the last step is pushing this to your fork 239 | git push -u fork my-feature-branch 240 | ``` 241 | 242 | Now go to the project's GitHub Pull Request page and click "New pull request" 243 | 244 | ## Conduct 245 | 246 | Whether you are a regular contributor or a newcomer, we care about making this 247 | community a safe place for you and we've got your back. 248 | 249 | [Ory Community Code of Conduct](https://github.com/ory/herodot/blob/master/CODE_OF_CONDUCT.md) 250 | 251 | We welcome discussion about creating a welcoming, safe, and productive 252 | environment for the community. If you have any questions, feedback, or concerns 253 | [please let us know](https://www.ory.sh/chat). 254 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MAINTAINERS: -------------------------------------------------------------------------------- 1 | Aeneas Rekkas (github: arekkas) 2 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | format: .bin/ory node_modules 2 | .bin/ory dev headers copyright --type=open-source --exclude=httputil 3 | go tool goimports -w -local github.com/ory *.go . httputil 4 | npm exec -- prettier --write . 5 | 6 | licenses: .bin/licenses node_modules # checks open-source licenses 7 | .bin/licenses 8 | 9 | .bin/licenses: Makefile 10 | curl https://raw.githubusercontent.com/ory/ci/master/licenses/install | sh 11 | 12 | .bin/ory: Makefile 13 | curl https://raw.githubusercontent.com/ory/meta/master/install.sh | bash -s -- -b .bin ory v0.2.2 14 | touch .bin/ory 15 | 16 | node_modules: package-lock.json 17 | npm ci 18 | touch node_modules 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # herodot 2 | 3 | [![Join the chat at https://slack.ory.sh/](https://img.shields.io/badge/join-chat-00cc99.svg)](https://slack.ory.sh/) 4 | [![Build Status](https://travis-ci.org/ory/herodot.svg?branch=master)](https://travis-ci.org/ory/herodot) 5 | [![Coverage Status](https://coveralls.io/repos/github/ory/herodot/badge.svg?branch=master)](https://coveralls.io/github/ory/herodot?branch=master) 6 | 7 | --- 8 | 9 | Herodot is a lightweight SDK for writing RESTful responses. It is comparable to 10 | [render](https://github.com/unrolled/render) but provides easier error handling. 11 | The error model implements the well established 12 | [Google API Design Guide](https://cloud.google.com/apis/design/errors). Herodot 13 | currently supports only JSON responses but can be extended easily. 14 | 15 | Herodot is used by [ORY Hydra](https://github.com/ory/hydra) and serves millions 16 | of requests already. 17 | 18 | ## Installation 19 | 20 | Herodot is versioned using 21 | [go modules](https://blog.golang.org/using-go-modules) and works best with 22 | [pkg/errors](https://github.com/pkg/errors). To install it, run 23 | 24 | ``` 25 | go get -u github.com/ory/herodot 26 | ``` 27 | 28 | ## Upgrading 29 | 30 | Tips on upgrading can be found in [UPGRADE.md](UPGRADE.md) 31 | 32 | ## Usage 33 | 34 | Using Herodot is straightforward. The examples below will help you get started. 35 | 36 | ### JSON 37 | 38 | Herodot supplies an interface, allowing to return errors in many data formats 39 | like XML and others. Currently, it supports only JSON. 40 | 41 | #### Write responses 42 | 43 | ```go 44 | var hd = herodot.NewJSONWriter(nil) 45 | 46 | func GetHandler(rw http.ResponseWriter, r *http.Request) { 47 | // run your business logic here 48 | hd.Write(rw, r, map[string]interface{}{ 49 | "key": "value" 50 | }) 51 | } 52 | 53 | type MyStruct struct { 54 | Key string `json:"key"` 55 | } 56 | 57 | func GetHandlerWithStruct(rw http.ResponseWriter, r *http.Request) { 58 | // business logic 59 | hd.Write(rw, r, &MyStruct{Key: "value"}) 60 | } 61 | 62 | func PostHandlerWithStruct(rw http.ResponseWriter, r *http.Request) { 63 | // business logic 64 | hd.WriteCreated(rw, r, "/path/to/the/resource/that/was/created", &MyStruct{Key: "value"}) 65 | } 66 | 67 | func SomeHandlerWithArbitraryStatusCode(rw http.ResponseWriter, r *http.Request) { 68 | // business logic 69 | hd.WriteCode(rw, r, http.StatusAccepted, &MyStruct{Key: "value"}) 70 | } 71 | 72 | func SomeHandlerWithArbitraryStatusCode(rw http.ResponseWriter, r *http.Request) { 73 | // business logic 74 | hd.WriteCode(rw, r, http.StatusAccepted, &MyStruct{Key: "value"}) 75 | } 76 | ``` 77 | 78 | #### Dealing with errors 79 | 80 | ```go 81 | var writer = herodot.NewJSONWriter(nil) 82 | 83 | func GetHandlerWithError(rw http.ResponseWriter, r *http.Request) { 84 | if err := someFunctionThatReturnsAnError(); err != nil { 85 | hd.WriteError(w, r, err) 86 | return 87 | } 88 | 89 | // ... 90 | } 91 | 92 | func GetHandlerWithErrorCode(rw http.ResponseWriter, r *http.Request) { 93 | if err := someFunctionThatReturnsAnError(); err != nil { 94 | hd.WriteErrorCode(w, r, http.StatusBadRequest, err) 95 | return 96 | } 97 | 98 | // ... 99 | } 100 | ``` 101 | 102 | ### Errors 103 | 104 | Herodot implements the error model of the well established 105 | [Google API Design Guide](https://cloud.google.com/apis/design/errors). 106 | Additionally, it makes the fields `request` and `reason` available. A complete 107 | Herodot error response looks like this: 108 | 109 | ```json 110 | { 111 | "error": { 112 | "code": 404, 113 | "status": "some-status", 114 | "request": "foo", 115 | "reason": "some-reason", 116 | "details": [{ "foo": "bar" }], 117 | "message": "foo" 118 | } 119 | } 120 | ``` 121 | 122 | To add context to your errors, implement `herodot.ErrorContextCarrier`. If you 123 | only want to set the status code of errors implement 124 | [herodot.StatusCodeCarrier](https://github.com/ory/herodot/blob/master/error.go#L22-L26). 125 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Ory Security Policy 5 | 6 | This policy outlines Ory's security commitments and practices for users across 7 | different licensing and deployment models. 8 | 9 | To learn more about Ory's security service level agreements (SLAs) and 10 | processes, please [contact us](https://www.ory.sh/contact/). 11 | 12 | ## Ory Network Users 13 | 14 | - **Security SLA:** Ory addresses vulnerabilities in the Ory Network according 15 | to the following guidelines: 16 | - Critical: Typically addressed within 14 days. 17 | - High: Typically addressed within 30 days. 18 | - Medium: Typically addressed within 90 days. 19 | - Low: Typically addressed within 180 days. 20 | - Informational: Addressed as necessary. 21 | These timelines are targets and may vary based on specific circumstances. 22 | - **Release Schedule:** Updates are deployed to the Ory Network as 23 | vulnerabilities are resolved. 24 | - **Version Support:** The Ory Network always runs the latest version, ensuring 25 | up-to-date security fixes. 26 | 27 | ## Ory Enterprise License Customers 28 | 29 | - **Security SLA:** Ory addresses vulnerabilities based on their severity: 30 | - Critical: Typically addressed within 14 days. 31 | - High: Typically addressed within 30 days. 32 | - Medium: Typically addressed within 90 days. 33 | - Low: Typically addressed within 180 days. 34 | - Informational: Addressed as necessary. 35 | These timelines are targets and may vary based on specific circumstances. 36 | - **Release Schedule:** Updates are made available as vulnerabilities are 37 | resolved. Ory works closely with enterprise customers to ensure timely updates 38 | that align with their operational needs. 39 | - **Version Support:** Ory may provide security support for multiple versions, 40 | depending on the terms of the enterprise agreement. 41 | 42 | ## Apache 2.0 License Users 43 | 44 | - **Security SLA:** Ory does not provide a formal SLA for security issues under 45 | the Apache 2.0 License. 46 | - **Release Schedule:** Releases prioritize new functionality and include fixes 47 | for known security vulnerabilities at the time of release. While major 48 | releases typically occur one to two times per year, Ory does not guarantee a 49 | fixed release schedule. 50 | - **Version Support:** Security patches are only provided for the latest release 51 | version. 52 | 53 | ## Reporting a Vulnerability 54 | 55 | For details on how to report security vulnerabilities, visit our 56 | [security policy documentation](https://www.ory.sh/docs/ecosystem/security). 57 | -------------------------------------------------------------------------------- /UPGRADE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | **Table of Contents** _generated with 5 | [DocToc](https://github.com/thlorenz/doctoc)_ 6 | 7 | - [Upgrade Guide](#upgrade-guide) 8 | - [0.3.0](#030) 9 | 10 | 11 | 12 | # Upgrade Guide 13 | 14 | ## 0.3.0 15 | 16 | To improve how errors are forwarded to clients, two `Writer` interface methods 17 | changed from: 18 | 19 | - `WriteError(w http.ResponseWriter, r *http.Request, err error)` 20 | - `WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err error)` 21 | 22 | to 23 | 24 | - `WriteError(w http.ResponseWriter, r *http.Request, err interface{})` 25 | - `WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err interface{})` 26 | 27 | This has no functional implications unless you are implementing the writer 28 | interface yourself. 29 | -------------------------------------------------------------------------------- /clientclosed.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | // StatusClientClosedRequest (reported as 499 Client Closed Request) is a faux 7 | // but de-facto standard HTTP status code first used by nginx, indicating the 8 | // client canceled the request. Because the client canceled, it is never 9 | // actually reported back to them. 499 is useful purely in logging, tracing, 10 | // etc. 11 | // 12 | // http://nginx.org/en/docs/dev/development_guide.html 13 | const StatusClientClosedRequest int = 499 14 | -------------------------------------------------------------------------------- /error_assert.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import "github.com/pkg/errors" 7 | 8 | func coalesceError(e error) error { 9 | if e == nil { 10 | return errors.New("Error passed to WriteErrorCode is nil") 11 | } 12 | return e 13 | } 14 | -------------------------------------------------------------------------------- /error_default.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | stderr "errors" 8 | "fmt" 9 | "io" 10 | "net/http" 11 | 12 | "github.com/pkg/errors" 13 | "google.golang.org/genproto/googleapis/rpc/errdetails" 14 | "google.golang.org/grpc/codes" 15 | "google.golang.org/grpc/status" 16 | "google.golang.org/protobuf/protoadapt" 17 | ) 18 | 19 | // swagger:ignore 20 | type DefaultError struct { 21 | // The error ID 22 | // 23 | // Useful when trying to identify various errors in application logic. 24 | IDField string `json:"id,omitempty"` 25 | 26 | // The status code 27 | // 28 | // example: 404 29 | CodeField int `json:"code,omitempty"` 30 | 31 | // The status description 32 | // 33 | // example: Not Found 34 | StatusField string `json:"status,omitempty"` 35 | 36 | // The request ID 37 | // 38 | // The request ID is often exposed internally in order to trace 39 | // errors across service architectures. This is often a UUID. 40 | // 41 | // example: d7ef54b1-ec15-46e6-bccb-524b82c035e6 42 | RIDField string `json:"request,omitempty"` 43 | 44 | // A human-readable reason for the error 45 | // 46 | // example: User with ID 1234 does not exist. 47 | ReasonField string `json:"reason,omitempty"` 48 | 49 | // Debug information 50 | // 51 | // This field is often not exposed to protect against leaking 52 | // sensitive information. 53 | // 54 | // example: SQL field "foo" is not a bool. 55 | DebugField string `json:"debug,omitempty"` 56 | 57 | // Further error details 58 | DetailsField map[string]interface{} `json:"details,omitempty"` 59 | 60 | // Error message 61 | // 62 | // The error's message. 63 | // 64 | // example: The resource could not be found 65 | // required: true 66 | ErrorField string `json:"message"` 67 | 68 | GRPCCodeField codes.Code `json:"-"` 69 | err error 70 | } 71 | 72 | // StackTrace returns the error's stack trace. 73 | func (e *DefaultError) StackTrace() (trace errors.StackTrace) { 74 | if e.err == e { 75 | return 76 | } 77 | 78 | if st := stackTracer(nil); stderr.As(e.err, &st) { 79 | trace = st.StackTrace() 80 | } 81 | 82 | return 83 | } 84 | 85 | func (e DefaultError) Unwrap() error { 86 | return e.err 87 | } 88 | 89 | func (e *DefaultError) Wrap(err error) { 90 | e.err = err 91 | } 92 | 93 | func (e DefaultError) WithWrap(err error) *DefaultError { 94 | e.err = err 95 | return &e 96 | } 97 | 98 | func (e DefaultError) WithID(id string) *DefaultError { 99 | e.IDField = id 100 | return &e 101 | } 102 | 103 | func (e *DefaultError) WithTrace(err error) *DefaultError { 104 | if st := stackTracer(nil); !stderr.As(e.err, &st) { 105 | e.Wrap(errors.WithStack(err)) 106 | } else { 107 | e.Wrap(err) 108 | } 109 | return e 110 | } 111 | 112 | func (e DefaultError) Is(err error) bool { 113 | switch te := err.(type) { 114 | case DefaultError: 115 | return e.ErrorField == te.ErrorField && 116 | e.StatusField == te.StatusField && 117 | e.IDField == te.IDField && 118 | e.CodeField == te.CodeField 119 | case *DefaultError: 120 | return e.ErrorField == te.ErrorField && 121 | e.StatusField == te.StatusField && 122 | e.IDField == te.IDField && 123 | e.CodeField == te.CodeField 124 | default: 125 | return false 126 | } 127 | } 128 | 129 | func (e DefaultError) Status() string { 130 | return e.StatusField 131 | } 132 | 133 | func (e DefaultError) ID() string { 134 | return e.IDField 135 | } 136 | 137 | func (e DefaultError) Error() string { 138 | return e.ErrorField 139 | } 140 | 141 | func (e DefaultError) RequestID() string { 142 | return e.RIDField 143 | } 144 | 145 | func (e DefaultError) Reason() string { 146 | return e.ReasonField 147 | } 148 | 149 | func (e DefaultError) Debug() string { 150 | return e.DebugField 151 | } 152 | 153 | func (e DefaultError) Details() map[string]interface{} { 154 | return e.DetailsField 155 | } 156 | 157 | func (e DefaultError) StatusCode() int { 158 | return e.CodeField 159 | } 160 | 161 | func (e DefaultError) GRPCStatus() *status.Status { 162 | s := status.New(e.GRPCCodeField, e.Error()) 163 | 164 | st := e.StackTrace() 165 | var stackEntries []string 166 | if st != nil { 167 | stackEntries = make([]string, len(st)) 168 | for i, f := range st { 169 | stackEntries[i] = fmt.Sprintf("%+v", f) 170 | } 171 | } 172 | 173 | details := []protoadapt.MessageV1{} 174 | 175 | if e.DebugField != "" || st != nil { 176 | details = append(details, &errdetails.DebugInfo{ 177 | StackEntries: stackEntries, 178 | Detail: e.Debug(), 179 | }) 180 | } 181 | 182 | if e.ReasonField != "" { 183 | details = append(details, &errdetails.ErrorInfo{ 184 | Reason: e.Reason(), 185 | }) 186 | } 187 | 188 | if e.RequestID() != "" { 189 | details = append(details, &errdetails.RequestInfo{ 190 | RequestId: e.RequestID(), 191 | }) 192 | } 193 | 194 | if e.GRPCCodeField == codes.InvalidArgument && e.err != nil { 195 | if fvs := e.fieldViolations(); len(fvs) > 0 { 196 | details = append(details, &errdetails.BadRequest{ 197 | FieldViolations: fvs, 198 | }) 199 | } 200 | } 201 | 202 | s, err := s.WithDetails(details...) 203 | if err != nil { 204 | // this error only occurs if the code is broken AF 205 | panic(err) 206 | } 207 | 208 | return s 209 | } 210 | 211 | // fieldViolationError is an interface implemented by proto-gen-validate. 212 | type fieldViolationError interface { 213 | Field() string 214 | Reason() string 215 | Cause() error 216 | } 217 | type multiError interface { 218 | AllErrors() []error 219 | } 220 | 221 | func rootCauses(err fieldViolationError) []fieldViolationError { 222 | if err == nil { 223 | return []fieldViolationError{} 224 | } 225 | 226 | switch e := err.Cause().(type) { 227 | case fieldViolationError: 228 | return rootCauses(e) 229 | 230 | case multiError: 231 | var causes []fieldViolationError 232 | for _, e := range e.AllErrors() { 233 | if fvErr, ok := e.(fieldViolationError); ok { 234 | causes = append(causes, rootCauses(fvErr)...) 235 | } 236 | } 237 | return causes 238 | } 239 | return []fieldViolationError{err} 240 | } 241 | 242 | func (e DefaultError) fieldViolations() (fv []*errdetails.BadRequest_FieldViolation) { 243 | err, ok := e.err.(multiError) 244 | if !ok { 245 | return 246 | } 247 | for _, e := range err.AllErrors() { 248 | if fvErr, ok := e.(fieldViolationError); ok { 249 | // We only want to show the root cause of the error. 250 | for _, cause := range rootCauses(fvErr) { 251 | fv = append(fv, &errdetails.BadRequest_FieldViolation{ 252 | Field: cause.Field(), 253 | Description: cause.Reason(), 254 | }) 255 | } 256 | } 257 | } 258 | 259 | return 260 | } 261 | 262 | func (e DefaultError) WithReason(reason string) *DefaultError { 263 | e.ReasonField = reason 264 | return &e 265 | } 266 | 267 | func (e DefaultError) WithReasonf(reason string, args ...interface{}) *DefaultError { 268 | return e.WithReason(fmt.Sprintf(reason, args...)) 269 | } 270 | 271 | func (e DefaultError) WithError(message string) *DefaultError { 272 | e.ErrorField = message 273 | return &e 274 | } 275 | 276 | func (e DefaultError) WithErrorf(message string, args ...interface{}) *DefaultError { 277 | return e.WithError(fmt.Sprintf(message, args...)) 278 | } 279 | 280 | func (e DefaultError) WithDebugf(debug string, args ...interface{}) *DefaultError { 281 | return e.WithDebug(fmt.Sprintf(debug, args...)) 282 | } 283 | 284 | func (e DefaultError) WithDebug(debug string) *DefaultError { 285 | e.DebugField = debug 286 | return &e 287 | } 288 | 289 | func (e DefaultError) WithDetail(key string, detail interface{}) *DefaultError { 290 | if e.DetailsField == nil { 291 | e.DetailsField = map[string]interface{}{} 292 | } 293 | e.DetailsField[key] = detail 294 | return &e 295 | } 296 | 297 | func (e DefaultError) WithDetailf(key string, message string, args ...interface{}) *DefaultError { 298 | if e.DetailsField == nil { 299 | e.DetailsField = map[string]interface{}{} 300 | } 301 | e.DetailsField[key] = fmt.Sprintf(message, args...) 302 | return &e 303 | } 304 | 305 | func (e DefaultError) Format(s fmt.State, verb rune) { 306 | switch verb { 307 | case 'v': 308 | if s.Flag('+') { 309 | _, _ = fmt.Fprintf(s, "id=%s\n", e.IDField) 310 | _, _ = fmt.Fprintf(s, "rid=%s\n", e.RIDField) 311 | _, _ = fmt.Fprintf(s, "error=%s\n", e.ErrorField) 312 | _, _ = fmt.Fprintf(s, "reason=%s\n", e.ReasonField) 313 | _, _ = fmt.Fprintf(s, "details=%+v\n", e.DetailsField) 314 | _, _ = fmt.Fprintf(s, "debug=%s\n", e.DebugField) 315 | e.StackTrace().Format(s, verb) 316 | return 317 | } 318 | fallthrough 319 | case 's': 320 | _, _ = io.WriteString(s, e.ErrorField) 321 | case 'q': 322 | _, _ = fmt.Fprintf(s, "%q", e.ErrorField) 323 | } 324 | } 325 | 326 | func ToDefaultError(err error, requestID string) *DefaultError { 327 | de := &DefaultError{ 328 | RIDField: requestID, 329 | CodeField: http.StatusInternalServerError, 330 | DetailsField: map[string]interface{}{}, 331 | ErrorField: err.Error(), 332 | } 333 | de.Wrap(err) 334 | 335 | if c := ReasonCarrier(nil); stderr.As(err, &c) { 336 | de.ReasonField = c.Reason() 337 | } 338 | if c := RequestIDCarrier(nil); stderr.As(err, &c) && c.RequestID() != "" { 339 | de.RIDField = c.RequestID() 340 | } 341 | if c := DetailsCarrier(nil); stderr.As(err, &c) && c.Details() != nil { 342 | de.DetailsField = c.Details() 343 | } 344 | if c := StatusCarrier(nil); stderr.As(err, &c) && c.Status() != "" { 345 | de.StatusField = c.Status() 346 | } 347 | if c := StatusCodeCarrier(nil); stderr.As(err, &c) && c.StatusCode() != 0 { 348 | de.CodeField = c.StatusCode() 349 | } 350 | if c := DebugCarrier(nil); stderr.As(err, &c) { 351 | de.DebugField = c.Debug() 352 | } 353 | if c := IDCarrier(nil); stderr.As(err, &c) { 354 | de.IDField = c.ID() 355 | } 356 | 357 | if de.StatusField == "" { 358 | de.StatusField = http.StatusText(de.StatusCode()) 359 | } 360 | 361 | return de 362 | } 363 | 364 | // StatusCodeCarrier can be implemented by an error to support setting status codes in the error itself. 365 | type StatusCodeCarrier interface { 366 | // StatusCode returns the status code of this error. 367 | StatusCode() int 368 | } 369 | 370 | // RequestIDCarrier can be implemented by an error to support error contexts. 371 | type RequestIDCarrier interface { 372 | // RequestID returns the ID of the request that caused the error, if applicable. 373 | RequestID() string 374 | } 375 | 376 | // ReasonCarrier can be implemented by an error to support error contexts. 377 | type ReasonCarrier interface { 378 | // Reason returns the reason for the error, if applicable. 379 | Reason() string 380 | } 381 | 382 | // DebugCarrier can be implemented by an error to support error contexts. 383 | type DebugCarrier interface { 384 | // Debug returns debugging information for the error, if applicable. 385 | Debug() string 386 | } 387 | 388 | // StatusCarrier can be implemented by an error to support error contexts. 389 | type StatusCarrier interface { 390 | // ID returns the error id, if applicable. 391 | Status() string 392 | } 393 | 394 | // DetailsCarrier can be implemented by an error to support error contexts. 395 | type DetailsCarrier interface { 396 | // Details returns details on the error, if applicable. 397 | Details() map[string]interface{} 398 | } 399 | 400 | // IDCarrier can be implemented by an error to support error contexts. 401 | type IDCarrier interface { 402 | // ID returns application error ID on the error, if applicable. 403 | ID() string 404 | } 405 | -------------------------------------------------------------------------------- /error_default_test.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "io" 8 | "net/http" 9 | "net/http/httptest" 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | "google.golang.org/genproto/googleapis/rpc/errdetails" 14 | "google.golang.org/grpc/codes" 15 | "google.golang.org/grpc/status" 16 | 17 | "github.com/pkg/errors" 18 | "github.com/stretchr/testify/assert" 19 | ) 20 | 21 | func TestToDefaultError(t *testing.T) { 22 | t.Run("case=stack", func(t *testing.T) { 23 | e := errors.New("hi") 24 | assert.EqualValues(t, e.(stackTracer).StackTrace(), ToDefaultError(e, "").StackTrace()) 25 | }) 26 | 27 | t.Run("case=wrap", func(t *testing.T) { 28 | orig := errors.New("hi") 29 | wrap := new(DefaultError) 30 | wrap.Wrap(orig) 31 | 32 | assert.EqualValues(t, orig.(stackTracer).StackTrace(), wrap.StackTrace()) 33 | }) 34 | 35 | t.Run("case=wrap_self", func(t *testing.T) { 36 | wrap := new(DefaultError) 37 | wrap.Wrap(wrap) 38 | 39 | assert.Empty(t, wrap.StackTrace()) 40 | }) 41 | 42 | t.Run("case=status", func(t *testing.T) { 43 | e := &DefaultError{ 44 | StatusField: "foo-status", 45 | } 46 | assert.EqualValues(t, "foo-status", ToDefaultError(e, "").Status()) 47 | }) 48 | 49 | t.Run("case=reason", func(t *testing.T) { 50 | e := &DefaultError{ 51 | ReasonField: "foo-reason", 52 | } 53 | assert.EqualValues(t, "foo-reason", ToDefaultError(e, "").Reason()) 54 | }) 55 | 56 | t.Run("case=debug", func(t *testing.T) { 57 | e := &DefaultError{ 58 | DebugField: "foo-debug", 59 | } 60 | assert.EqualValues(t, "foo-debug", ToDefaultError(e, "").Debug()) 61 | }) 62 | 63 | t.Run("case=details", func(t *testing.T) { 64 | e := &DefaultError{ 65 | DetailsField: map[string]interface{}{"foo-debug": "bar"}, 66 | } 67 | assert.EqualValues(t, map[string]interface{}{"foo-debug": "bar"}, ToDefaultError(e, "").Details()) 68 | }) 69 | 70 | t.Run("case=rid", func(t *testing.T) { 71 | e := &DefaultError{ 72 | RIDField: "foo-rid", 73 | } 74 | assert.EqualValues(t, "foo-rid", ToDefaultError(e, "").RequestID()) 75 | assert.EqualValues(t, "fallback-rid", ToDefaultError(new(DefaultError), "fallback-rid").RequestID()) 76 | }) 77 | 78 | t.Run("case=id", func(t *testing.T) { 79 | e := &DefaultError{ 80 | IDField: "foo-rid", 81 | } 82 | assert.EqualValues(t, "foo-rid", ToDefaultError(e, "").ID()) 83 | }) 84 | 85 | t.Run("case=code", func(t *testing.T) { 86 | e := &DefaultError{CodeField: 501} 87 | assert.EqualValues(t, 501, ToDefaultError(e, "").StatusCode()) 88 | assert.EqualValues(t, http.StatusText(501), ToDefaultError(e, "").Status()) 89 | 90 | e = &DefaultError{CodeField: 501, StatusField: "foobar"} 91 | assert.EqualValues(t, 501, ToDefaultError(e, "").StatusCode()) 92 | assert.EqualValues(t, "foobar", ToDefaultError(e, "").Status()) 93 | 94 | assert.EqualValues(t, 500, ToDefaultError(errors.New(""), "").StatusCode()) 95 | }) 96 | 97 | t.Run("case=GRPCStatus", func(t *testing.T) { 98 | expected, _ := status.New(codes.InvalidArgument, "message").WithDetails( 99 | &errdetails.DebugInfo{Detail: "debug"}, 100 | &errdetails.ErrorInfo{Reason: "reason"}, 101 | &errdetails.RequestInfo{RequestId: "request_id"}, 102 | ) 103 | 104 | status := DefaultError{ 105 | ErrorField: "message", 106 | GRPCCodeField: codes.InvalidArgument, 107 | DebugField: "debug", 108 | ReasonField: "reason", 109 | RIDField: "request_id", 110 | }.GRPCStatus() 111 | 112 | assert.Equal(t, expected, status) 113 | }) 114 | } 115 | 116 | func TestOmitDebug(t *testing.T) { 117 | t.Run("case=without debug (default)", func(t *testing.T) { 118 | e := &DefaultError{ 119 | ErrorField: "Some Error", 120 | DebugField: "whatever", 121 | } 122 | h := NewJSONWriter(nil) 123 | h.ErrorEnhancer = nil 124 | rec := httptest.NewRecorder() 125 | h.WriteError(rec, &http.Request{}, e) 126 | j, err := io.ReadAll(rec.Result().Body) 127 | require.NoError(t, err) 128 | assert.JSONEq(t, `{"message":"Some Error"}`, string(j)) 129 | }) 130 | 131 | t.Run("case=with debug", func(t *testing.T) { 132 | e := &DefaultError{ 133 | ErrorField: "Some Error", 134 | DebugField: "whatever", 135 | } 136 | h := NewJSONWriter(nil) 137 | h.ErrorEnhancer = nil 138 | h.EnableDebug = true 139 | rec := httptest.NewRecorder() 140 | h.WriteError(rec, &http.Request{}, e) 141 | j, err := io.ReadAll(rec.Result().Body) 142 | require.NoError(t, err) 143 | assert.JSONEq(t, `{"message":"Some Error", "debug": "whatever"}`, string(j)) 144 | }) 145 | } 146 | -------------------------------------------------------------------------------- /error_defaults.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "net/http" 8 | 9 | "google.golang.org/grpc/codes" 10 | ) 11 | 12 | var ErrNotFound = DefaultError{ 13 | StatusField: http.StatusText(http.StatusNotFound), 14 | ErrorField: "The requested resource could not be found", 15 | CodeField: http.StatusNotFound, 16 | GRPCCodeField: codes.NotFound, 17 | } 18 | 19 | var ErrUnauthorized = DefaultError{ 20 | StatusField: http.StatusText(http.StatusUnauthorized), 21 | ErrorField: "The request could not be authorized", 22 | CodeField: http.StatusUnauthorized, 23 | GRPCCodeField: codes.Unauthenticated, 24 | } 25 | 26 | var ErrForbidden = DefaultError{ 27 | StatusField: http.StatusText(http.StatusForbidden), 28 | ErrorField: "The requested action was forbidden", 29 | CodeField: http.StatusForbidden, 30 | GRPCCodeField: codes.PermissionDenied, 31 | } 32 | 33 | var ErrInternalServerError = DefaultError{ 34 | StatusField: http.StatusText(http.StatusInternalServerError), 35 | ErrorField: "An internal server error occurred, please contact the system administrator", 36 | CodeField: http.StatusInternalServerError, 37 | GRPCCodeField: codes.Internal, 38 | } 39 | 40 | var ErrBadRequest = DefaultError{ 41 | StatusField: http.StatusText(http.StatusBadRequest), 42 | ErrorField: "The request was malformed or contained invalid parameters", 43 | CodeField: http.StatusBadRequest, 44 | GRPCCodeField: codes.InvalidArgument, 45 | } 46 | 47 | var ErrUnsupportedMediaType = DefaultError{ 48 | StatusField: http.StatusText(http.StatusUnsupportedMediaType), 49 | ErrorField: "The request is using an unknown content type", 50 | CodeField: http.StatusUnsupportedMediaType, 51 | GRPCCodeField: codes.InvalidArgument, 52 | } 53 | 54 | var ErrConflict = DefaultError{ 55 | StatusField: http.StatusText(http.StatusConflict), 56 | ErrorField: "The resource could not be created due to a conflict", 57 | CodeField: http.StatusConflict, 58 | GRPCCodeField: codes.FailedPrecondition, 59 | } 60 | 61 | var ErrMisconfiguration = DefaultError{ 62 | IDField: "invalid_configuration", 63 | StatusField: http.StatusText(http.StatusInternalServerError), 64 | ErrorField: "Invalid configuration", 65 | ReasonField: "One or more configuration values are invalid. Please report this to the system administrator.", 66 | CodeField: http.StatusInternalServerError, 67 | } 68 | -------------------------------------------------------------------------------- /error_reporter.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "fmt" 8 | "net/http" 9 | 10 | "github.com/pkg/errors" 11 | ) 12 | 13 | type stackTracer interface { 14 | StackTrace() errors.StackTrace 15 | } 16 | 17 | type stdReporter struct{} 18 | 19 | var _ ErrorReporter = (*stdReporter)(nil) 20 | 21 | func (s *stdReporter) ReportError(r *http.Request, code int, err error, args ...interface{}) { 22 | fmt.Printf("ERROR: %s\n Request: %v\n Response Code: %d\n Further Info: %v\n", err, r, code, args) 23 | } 24 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ory/herodot 2 | 3 | go 1.24 4 | 5 | require ( 6 | github.com/pkg/errors v0.9.1 7 | github.com/stretchr/testify v1.10.0 8 | golang.org/x/sync v0.12.0 9 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 10 | google.golang.org/grpc v1.71.0 11 | google.golang.org/protobuf v1.36.5 12 | ) 13 | 14 | require ( 15 | github.com/davecgh/go-spew v1.1.1 // indirect 16 | github.com/google/go-cmp v0.7.0 // indirect 17 | github.com/jandelgado/gcov2lcov v1.1.1 // indirect 18 | github.com/kr/pretty v0.3.0 // indirect 19 | github.com/pmezard/go-difflib v1.0.0 // indirect 20 | golang.org/x/mod v0.24.0 // indirect 21 | golang.org/x/net v0.38.0 // indirect 22 | golang.org/x/sys v0.31.0 // indirect 23 | golang.org/x/text v0.23.0 // indirect 24 | golang.org/x/tools v0.31.0 // indirect 25 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 26 | gopkg.in/yaml.v3 v3.0.1 // indirect 27 | ) 28 | 29 | tool ( 30 | github.com/jandelgado/gcov2lcov 31 | golang.org/x/tools/cmd/goimports 32 | ) 33 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= 6 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 7 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= 8 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= 9 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= 10 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 11 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 12 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 13 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 14 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 15 | github.com/jandelgado/gcov2lcov v1.1.1 h1:CHUNoAglvb34DqmMoZchnzDbA3yjpzT8EoUvVqcAY+s= 16 | github.com/jandelgado/gcov2lcov v1.1.1/go.mod h1:tMVUlMVtS1po2SB8UkADWhOT5Y5Q13XOce2AYU69JuI= 17 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 18 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 19 | github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= 20 | github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= 21 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 22 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 23 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 24 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 25 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 26 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 27 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 28 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 29 | github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= 30 | github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= 31 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 32 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 33 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 34 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 35 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 36 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 37 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 38 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 39 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 40 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 41 | go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= 42 | go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= 43 | go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= 44 | go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= 45 | go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= 46 | go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= 47 | go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= 48 | go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= 49 | go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= 50 | go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= 51 | go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= 52 | go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= 53 | golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= 54 | golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= 55 | golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= 56 | golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= 57 | golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= 58 | golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= 59 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= 60 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 61 | golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= 62 | golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= 63 | golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= 64 | golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= 65 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 h1:iK2jbkWL86DXjEx0qiHcRE9dE4/Ahua5k6V8OWFb//c= 66 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= 67 | google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= 68 | google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= 69 | google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= 70 | google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= 71 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 72 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 73 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 74 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 75 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= 76 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 77 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 78 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 79 | -------------------------------------------------------------------------------- /grpc_unwrap_interceptors.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "context" 8 | 9 | "github.com/pkg/errors" 10 | "google.golang.org/grpc" 11 | "google.golang.org/grpc/status" 12 | ) 13 | 14 | type grpcStatusError interface { 15 | error 16 | GRPCStatus() *status.Status 17 | } 18 | 19 | func unwrapGRPCStatusError(err error) error { 20 | if err == nil { 21 | return nil 22 | } 23 | 24 | var innerErr grpcStatusError 25 | if errors.As(err, &innerErr) { 26 | return innerErr 27 | } 28 | return err 29 | } 30 | 31 | // UnaryErrorUnwrapInterceptor is a gRPC server-side interceptor that unwraps herodot errors for Unary RPCs. 32 | // See https://github.com/grpc/grpc-go/issues/2934 for why this is necessary. 33 | func UnaryErrorUnwrapInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 34 | resp, err := handler(ctx, req) 35 | return resp, unwrapGRPCStatusError(err) 36 | } 37 | 38 | // StreamErrorUnwrapInterceptor is a gRPC server-side interceptor that unwraps herodot errors for Streaming RPCs. 39 | // See https://github.com/grpc/grpc-go/issues/2934 for why this is necessary. 40 | func StreamErrorUnwrapInterceptor(srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { 41 | err := handler(srv, ss) 42 | return unwrapGRPCStatusError(err) 43 | } 44 | -------------------------------------------------------------------------------- /grpc_unwrap_interceptors_test.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "context" 8 | "net" 9 | "testing" 10 | 11 | "github.com/pkg/errors" 12 | "github.com/stretchr/testify/assert" 13 | "github.com/stretchr/testify/require" 14 | "golang.org/x/sync/errgroup" 15 | "google.golang.org/grpc" 16 | "google.golang.org/grpc/codes" 17 | "google.golang.org/grpc/status" 18 | 19 | "github.com/ory/herodot/internal" 20 | ) 21 | 22 | type testingGreeter struct { 23 | internal.UnimplementedGreeterServer 24 | shouldErr bool 25 | } 26 | 27 | func (g *testingGreeter) SayHello(context.Context, *internal.HelloRequest) (*internal.HelloReply, error) { 28 | if g.shouldErr { 29 | return nil, errors.WithStack(ErrInternalServerError) 30 | } 31 | return &internal.HelloReply{Message: "see, no error"}, nil 32 | } 33 | 34 | func TestGRPCInterceptors(t *testing.T) { 35 | server := &testingGreeter{} 36 | s := grpc.NewServer(grpc.UnaryInterceptor(UnaryErrorUnwrapInterceptor)) 37 | internal.RegisterGreeterServer(s, server) 38 | l, err := net.Listen("tcp", "127.0.0.1:0") 39 | require.NoError(t, err) 40 | 41 | serveErr := &errgroup.Group{} 42 | serveErr.Go(func() error { 43 | return s.Serve(l) 44 | }) 45 | 46 | conn, err := grpc.Dial(l.Addr().String(), grpc.WithInsecure()) 47 | require.NoError(t, err) 48 | c := internal.NewGreeterClient(conn) 49 | 50 | for _, tc := range []struct { 51 | name string 52 | shouldErr bool 53 | }{ 54 | { 55 | name: "no error", 56 | shouldErr: false, 57 | }, 58 | { 59 | name: "internal error", 60 | shouldErr: true, 61 | }, 62 | } { 63 | t.Run("case="+tc.name, func(t *testing.T) { 64 | server.shouldErr = tc.shouldErr 65 | 66 | resp, err := c.SayHello(context.Background(), &internal.HelloRequest{}) 67 | if tc.shouldErr { 68 | assert.Equal(t, codes.Internal, status.Code(err)) 69 | } else { 70 | assert.NoError(t, err) 71 | assert.Equal(t, "see, no error", resp.Message) 72 | } 73 | }) 74 | } 75 | 76 | s.Stop() 77 | require.NoError(t, serveErr.Wait()) 78 | } 79 | -------------------------------------------------------------------------------- /httputil/buster.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil 8 | 9 | import ( 10 | "io" 11 | "io/ioutil" 12 | "net/http" 13 | "net/url" 14 | "strings" 15 | "sync" 16 | ) 17 | 18 | type busterWriter struct { 19 | headerMap http.Header 20 | status int 21 | io.Writer 22 | } 23 | 24 | func (bw *busterWriter) Header() http.Header { 25 | return bw.headerMap 26 | } 27 | 28 | func (bw *busterWriter) WriteHeader(status int) { 29 | bw.status = status 30 | } 31 | 32 | // CacheBusters maintains a cache of cache busting tokens for static resources served by Handler. 33 | type CacheBusters struct { 34 | Handler http.Handler 35 | 36 | mu sync.Mutex 37 | tokens map[string]string 38 | } 39 | 40 | func sanitizeTokenRune(r rune) rune { 41 | if r <= ' ' || r >= 127 { 42 | return -1 43 | } 44 | // Convert percent encoding reserved characters to '-'. 45 | if strings.ContainsRune("!#$&'()*+,/:;=?@[]", r) { 46 | return '-' 47 | } 48 | return r 49 | } 50 | 51 | // Get returns the cache busting token for path. If the token is not already 52 | // cached, Get issues a HEAD request on handler and uses the response ETag and 53 | // Last-Modified headers to compute a token. 54 | func (cb *CacheBusters) Get(path string) string { 55 | cb.mu.Lock() 56 | if cb.tokens == nil { 57 | cb.tokens = make(map[string]string) 58 | } 59 | token, ok := cb.tokens[path] 60 | cb.mu.Unlock() 61 | if ok { 62 | return token 63 | } 64 | 65 | w := busterWriter{ 66 | Writer: ioutil.Discard, 67 | headerMap: make(http.Header), 68 | } 69 | r := &http.Request{URL: &url.URL{Path: path}, Method: "HEAD"} 70 | cb.Handler.ServeHTTP(&w, r) 71 | 72 | if w.status == 200 { 73 | token = w.headerMap.Get("Etag") 74 | if token == "" { 75 | token = w.headerMap.Get("Last-Modified") 76 | } 77 | token = strings.Trim(token, `" `) 78 | token = strings.Map(sanitizeTokenRune, token) 79 | } 80 | 81 | cb.mu.Lock() 82 | cb.tokens[path] = token 83 | cb.mu.Unlock() 84 | 85 | return token 86 | } 87 | 88 | // AppendQueryParam appends the token as a query parameter to path. 89 | func (cb *CacheBusters) AppendQueryParam(path string, name string) string { 90 | token := cb.Get(path) 91 | if token == "" { 92 | return path 93 | } 94 | return path + "?" + name + "=" + token 95 | } 96 | -------------------------------------------------------------------------------- /httputil/buster_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil 8 | 9 | import ( 10 | "net/http" 11 | "testing" 12 | ) 13 | 14 | func TestCacheBusters(t *testing.T) { 15 | cbs := &CacheBusters{Handler: http.FileServer(http.Dir("."))} 16 | 17 | token := cbs.Get("/buster_test.go") 18 | if token == "" { 19 | t.Errorf("could not extract token from http.FileServer") 20 | } 21 | 22 | var ss StaticServer 23 | cbs = &CacheBusters{Handler: ss.FileHandler("buster_test.go")} 24 | 25 | token = cbs.Get("/xxx") 26 | if token == "" { 27 | t.Errorf("could not extract token from StaticServer FileHandler") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /httputil/header/header.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | // Package header provides functions for parsing HTTP headers. 8 | package header 9 | 10 | import ( 11 | "net/http" 12 | "strings" 13 | "time" 14 | ) 15 | 16 | // Octet types from RFC 2616. 17 | var octetTypes [256]octetType 18 | 19 | type octetType byte 20 | 21 | const ( 22 | isToken octetType = 1 << iota 23 | isSpace 24 | ) 25 | 26 | func init() { 27 | // OCTET = 28 | // CHAR = 29 | // CTL = 30 | // CR = 31 | // LF = 32 | // SP = 33 | // HT = 34 | // <"> = 35 | // CRLF = CR LF 36 | // LWS = [CRLF] 1*( SP | HT ) 37 | // TEXT = 38 | // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> 39 | // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT 40 | // token = 1* 41 | // qdtext = > 42 | 43 | for c := 0; c < 256; c++ { 44 | var t octetType 45 | isCtl := c <= 31 || c == 127 46 | isChar := 0 <= c && c <= 127 47 | isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 48 | if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { 49 | t |= isSpace 50 | } 51 | if isChar && !isCtl && !isSeparator { 52 | t |= isToken 53 | } 54 | octetTypes[c] = t 55 | } 56 | } 57 | 58 | // Copy returns a shallow copy of the header. 59 | func Copy(header http.Header) http.Header { 60 | h := make(http.Header) 61 | for k, vs := range header { 62 | h[k] = vs 63 | } 64 | return h 65 | } 66 | 67 | var timeLayouts = []string{"Mon, 02 Jan 2006 15:04:05 GMT", time.RFC850, time.ANSIC} 68 | 69 | // ParseTime parses the header as time. The zero value is returned if the 70 | // header is not present or there is an error parsing the 71 | // header. 72 | func ParseTime(header http.Header, key string) time.Time { 73 | if s := header.Get(key); s != "" { 74 | for _, layout := range timeLayouts { 75 | if t, err := time.Parse(layout, s); err == nil { 76 | return t.UTC() 77 | } 78 | } 79 | } 80 | return time.Time{} 81 | } 82 | 83 | // ParseList parses a comma separated list of values. Commas are ignored in 84 | // quoted strings. Quoted values are not unescaped or unquoted. Whitespace is 85 | // trimmed. 86 | func ParseList(header http.Header, key string) []string { 87 | var result []string 88 | for _, s := range header[http.CanonicalHeaderKey(key)] { 89 | begin := 0 90 | end := 0 91 | escape := false 92 | quote := false 93 | for i := 0; i < len(s); i++ { 94 | b := s[i] 95 | switch { 96 | case escape: 97 | escape = false 98 | end = i + 1 99 | case quote: 100 | switch b { 101 | case '\\': 102 | escape = true 103 | case '"': 104 | quote = false 105 | } 106 | end = i + 1 107 | case b == '"': 108 | quote = true 109 | end = i + 1 110 | case octetTypes[b]&isSpace != 0: 111 | if begin == end { 112 | begin = i + 1 113 | end = begin 114 | } 115 | case b == ',': 116 | if begin < end { 117 | result = append(result, s[begin:end]) 118 | } 119 | begin = i + 1 120 | end = begin 121 | default: 122 | end = i + 1 123 | } 124 | } 125 | if begin < end { 126 | result = append(result, s[begin:end]) 127 | } 128 | } 129 | return result 130 | } 131 | 132 | // ParseValueAndParams parses a comma separated list of values with optional 133 | // semicolon separated name-value pairs. Content-Type and Content-Disposition 134 | // headers are in this format. 135 | func ParseValueAndParams(header http.Header, key string) (value string, params map[string]string) { 136 | params = make(map[string]string) 137 | s := header.Get(key) 138 | value, s = expectTokenSlash(s) 139 | if value == "" { 140 | return 141 | } 142 | value = strings.ToLower(value) 143 | s = skipSpace(s) 144 | for strings.HasPrefix(s, ";") { 145 | var pkey string 146 | pkey, s = expectToken(skipSpace(s[1:])) 147 | if pkey == "" { 148 | return 149 | } 150 | if !strings.HasPrefix(s, "=") { 151 | return 152 | } 153 | var pvalue string 154 | pvalue, s = expectTokenOrQuoted(s[1:]) 155 | if pvalue == "" { 156 | return 157 | } 158 | pkey = strings.ToLower(pkey) 159 | params[pkey] = pvalue 160 | s = skipSpace(s) 161 | } 162 | return 163 | } 164 | 165 | // AcceptSpec describes an Accept* header. 166 | type AcceptSpec struct { 167 | Value string 168 | Q float64 169 | } 170 | 171 | // ParseAccept parses Accept* headers. 172 | func ParseAccept(header http.Header, key string) (specs []AcceptSpec) { 173 | loop: 174 | for _, s := range header[key] { 175 | for { 176 | var spec AcceptSpec 177 | spec.Value, s = expectTokenSlash(s) 178 | if spec.Value == "" { 179 | continue loop 180 | } 181 | spec.Q = 1.0 182 | s = skipSpace(s) 183 | if strings.HasPrefix(s, ";") { 184 | s = skipSpace(s[1:]) 185 | if !strings.HasPrefix(s, "q=") { 186 | continue loop 187 | } 188 | spec.Q, s = expectQuality(s[2:]) 189 | if spec.Q < 0.0 { 190 | continue loop 191 | } 192 | } 193 | specs = append(specs, spec) 194 | s = skipSpace(s) 195 | if !strings.HasPrefix(s, ",") { 196 | continue loop 197 | } 198 | s = skipSpace(s[1:]) 199 | } 200 | } 201 | return 202 | } 203 | 204 | func skipSpace(s string) (rest string) { 205 | i := 0 206 | for ; i < len(s); i++ { 207 | if octetTypes[s[i]]&isSpace == 0 { 208 | break 209 | } 210 | } 211 | return s[i:] 212 | } 213 | 214 | func expectToken(s string) (string, string) { 215 | i := 0 216 | for ; i < len(s); i++ { 217 | if octetTypes[s[i]]&isToken == 0 { 218 | break 219 | } 220 | } 221 | return s[:i], s[i:] 222 | } 223 | 224 | func expectTokenSlash(s string) (token, rest string) { 225 | i := 0 226 | for ; i < len(s); i++ { 227 | b := s[i] 228 | if (octetTypes[b]&isToken == 0) && b != '/' { 229 | break 230 | } 231 | } 232 | return s[:i], s[i:] 233 | } 234 | 235 | func expectQuality(s string) (q float64, rest string) { 236 | switch { 237 | case len(s) == 0: 238 | return -1, "" 239 | case s[0] == '0': 240 | q = 0 241 | case s[0] == '1': 242 | q = 1 243 | default: 244 | return -1, "" 245 | } 246 | s = s[1:] 247 | if !strings.HasPrefix(s, ".") { 248 | return q, s 249 | } 250 | s = s[1:] 251 | i := 0 252 | n := 0 253 | d := 1 254 | for ; i < len(s); i++ { 255 | b := s[i] 256 | if b < '0' || b > '9' { 257 | break 258 | } 259 | n = n*10 + int(b) - '0' 260 | d *= 10 261 | } 262 | return q + float64(n)/float64(d), s[i:] 263 | } 264 | 265 | func expectTokenOrQuoted(s string) (value string, rest string) { 266 | if !strings.HasPrefix(s, "\"") { 267 | return expectToken(s) 268 | } 269 | s = s[1:] 270 | for i := 0; i < len(s); i++ { 271 | switch s[i] { 272 | case '"': 273 | return s[:i], s[i+1:] 274 | case '\\': 275 | p := make([]byte, len(s)-1) 276 | j := copy(p, s[:i]) 277 | escape := true 278 | for i = i + 1; i < len(s); i++ { 279 | b := s[i] 280 | switch { 281 | case escape: 282 | escape = false 283 | p[j] = b 284 | j++ 285 | case b == '\\': 286 | escape = true 287 | case b == '"': 288 | return string(p[:j]), s[i+1:] 289 | default: 290 | p[j] = b 291 | j++ 292 | } 293 | } 294 | return "", "" 295 | } 296 | } 297 | return "", "" 298 | } 299 | -------------------------------------------------------------------------------- /httputil/header/header_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package header 8 | 9 | import ( 10 | "net/http" 11 | "testing" 12 | "time" 13 | 14 | "github.com/stretchr/testify/assert" 15 | ) 16 | 17 | var getHeaderListTests = []struct { 18 | s string 19 | l []string 20 | }{ 21 | {s: `a`, l: []string{`a`}}, 22 | {s: `a, b , c `, l: []string{`a`, `b`, `c`}}, 23 | {s: `a,, b , , c `, l: []string{`a`, `b`, `c`}}, 24 | {s: `a,b,c`, l: []string{`a`, `b`, `c`}}, 25 | {s: ` a b, c d `, l: []string{`a b`, `c d`}}, 26 | {s: `"a, b, c", d `, l: []string{`"a, b, c"`, "d"}}, 27 | {s: `","`, l: []string{`","`}}, 28 | {s: `"\""`, l: []string{`"\""`}}, 29 | {s: `" "`, l: []string{`" "`}}, 30 | } 31 | 32 | func TestGetHeaderList(t *testing.T) { 33 | for _, tt := range getHeaderListTests { 34 | header := http.Header{"Foo": {tt.s}} 35 | assert.Equal(t, tt.l, ParseList(header, "foo")) 36 | } 37 | } 38 | 39 | var parseValueAndParamsTests = []struct { 40 | s string 41 | value string 42 | params map[string]string 43 | }{ 44 | {`text/html`, "text/html", map[string]string{}}, 45 | {`text/html `, "text/html", map[string]string{}}, 46 | {`text/html ; `, "text/html", map[string]string{}}, 47 | {`tExt/htMl`, "text/html", map[string]string{}}, 48 | {`tExt/htMl; fOO=";"; hellO=world`, "text/html", map[string]string{ 49 | "hello": "world", 50 | "foo": `;`, 51 | }}, 52 | {`text/html; foo=bar, hello=world`, "text/html", map[string]string{"foo": "bar"}}, 53 | {`text/html ; foo=bar `, "text/html", map[string]string{"foo": "bar"}}, 54 | {`text/html ;foo=bar `, "text/html", map[string]string{"foo": "bar"}}, 55 | {`text/html; foo="b\ar"`, "text/html", map[string]string{"foo": "bar"}}, 56 | {`text/html; foo="bar\"baz\"qux"`, "text/html", map[string]string{"foo": `bar"baz"qux`}}, 57 | {`text/html; foo="b,ar"`, "text/html", map[string]string{"foo": "b,ar"}}, 58 | {`text/html; foo="b;ar"`, "text/html", map[string]string{"foo": "b;ar"}}, 59 | {`text/html; FOO="bar"`, "text/html", map[string]string{"foo": "bar"}}, 60 | {`form-data; filename="file.txt"; name=file`, "form-data", map[string]string{"filename": "file.txt", "name": "file"}}, 61 | } 62 | 63 | func TestParseValueAndParams(t *testing.T) { 64 | for _, tt := range parseValueAndParamsTests { 65 | header := http.Header{"Content-Type": {tt.s}} 66 | value, params := ParseValueAndParams(header, "Content-Type") 67 | assert.Equal(t, tt.value, value) 68 | assert.Equal(t, tt.params, params) 69 | } 70 | } 71 | 72 | var parseTimeValidTests = []string{ 73 | "Sun, 06 Nov 1994 08:49:37 GMT", 74 | "Sunday, 06-Nov-94 08:49:37 GMT", 75 | "Sun Nov 6 08:49:37 1994", 76 | } 77 | 78 | var parseTimeInvalidTests = []string{ 79 | "junk", 80 | } 81 | 82 | func TestParseTime(t *testing.T) { 83 | expected := time.Date(1994, 11, 6, 8, 49, 37, 0, time.UTC) 84 | for _, s := range parseTimeValidTests { 85 | header := http.Header{"Date": {s}} 86 | actual := ParseTime(header, "Date") 87 | if actual != expected { 88 | t.Errorf("GetTime(%q)=%v, want %v", s, actual, expected) 89 | } 90 | } 91 | for _, s := range parseTimeInvalidTests { 92 | header := http.Header{"Date": {s}} 93 | actual := ParseTime(header, "Date") 94 | if !actual.IsZero() { 95 | t.Errorf("GetTime(%q) did not return zero", s) 96 | } 97 | } 98 | } 99 | 100 | var parseAcceptTests = []struct { 101 | s string 102 | expected []AcceptSpec 103 | }{ 104 | {"text/html", []AcceptSpec{{"text/html", 1}}}, 105 | {"text/html; q=0", []AcceptSpec{{"text/html", 0}}}, 106 | {"text/html; q=0.0", []AcceptSpec{{"text/html", 0}}}, 107 | {"text/html; q=1", []AcceptSpec{{"text/html", 1}}}, 108 | {"text/html; q=1.0", []AcceptSpec{{"text/html", 1}}}, 109 | {"text/html; q=0.1", []AcceptSpec{{"text/html", 0.1}}}, 110 | {"text/html;q=0.1", []AcceptSpec{{"text/html", 0.1}}}, 111 | {"text/html, text/plain", []AcceptSpec{{"text/html", 1}, {"text/plain", 1}}}, 112 | {"text/html; q=0.1, text/plain", []AcceptSpec{{"text/html", 0.1}, {"text/plain", 1}}}, 113 | {"iso-8859-5, unicode-1-1;q=0.8,iso-8859-1", []AcceptSpec{{"iso-8859-5", 1}, {"unicode-1-1", 0.8}, {"iso-8859-1", 1}}}, 114 | {"iso-8859-1", []AcceptSpec{{"iso-8859-1", 1}}}, 115 | {"*", []AcceptSpec{{"*", 1}}}, 116 | {"da, en-gb;q=0.8, en;q=0.7", []AcceptSpec{{"da", 1}, {"en-gb", 0.8}, {"en", 0.7}}}, 117 | {"da, q, en-gb;q=0.8", []AcceptSpec{{"da", 1}, {"q", 1}, {"en-gb", 0.8}}}, 118 | {"image/png, image/*;q=0.5", []AcceptSpec{{"image/png", 1}, {"image/*", 0.5}}}, 119 | 120 | // bad cases 121 | {"value1; q=0.1.2", []AcceptSpec{{"value1", 0.1}}}, 122 | {"da, en-gb;q=foo", []AcceptSpec{{"da", 1}}}, 123 | } 124 | 125 | func TestParseAccept(t *testing.T) { 126 | for _, tt := range parseAcceptTests { 127 | header := http.Header{"Accept": {tt.s}} 128 | actual := ParseAccept(header, "Accept") 129 | assert.Equal(t, tt.expected, actual) 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /httputil/httputil.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | // Package httputil is a toolkit for the Go net/http package. 8 | package httputil 9 | 10 | import ( 11 | "net" 12 | "net/http" 13 | ) 14 | 15 | // StripPort removes the port specification from an address. 16 | func StripPort(s string) string { 17 | if h, _, err := net.SplitHostPort(s); err == nil { 18 | s = h 19 | } 20 | return s 21 | } 22 | 23 | // Error defines a type for a function that accepts a ResponseWriter for 24 | // a Request with the HTTP status code and error. 25 | type Error func(w http.ResponseWriter, r *http.Request, status int, err error) 26 | -------------------------------------------------------------------------------- /httputil/negotiate.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil 8 | 9 | import ( 10 | "net/http" 11 | "strings" 12 | 13 | "github.com/ory/herodot/httputil/header" 14 | ) 15 | 16 | // NegotiateContentEncoding returns the best offered content encoding for the 17 | // request's Accept-Encoding header. If two offers match with equal weight and 18 | // then the offer earlier in the list is preferred. If no offers are 19 | // acceptable, then "" is returned. 20 | func NegotiateContentEncoding(r *http.Request, offers []string) string { 21 | bestOffer := "identity" 22 | bestQ := -1.0 23 | specs := header.ParseAccept(r.Header, "Accept-Encoding") 24 | for _, offer := range offers { 25 | for _, spec := range specs { 26 | if spec.Q > bestQ && 27 | (spec.Value == "*" || spec.Value == offer) { 28 | bestQ = spec.Q 29 | bestOffer = offer 30 | } 31 | } 32 | } 33 | if bestQ == 0 { 34 | bestOffer = "" 35 | } 36 | return bestOffer 37 | } 38 | 39 | // NegotiateContentType returns the best offered content type for the request's 40 | // Accept header. If two offers match with equal weight, then the more specific 41 | // offer is preferred. For example, text/* trumps */*. If two offers match 42 | // with equal weight and specificity, then the offer earlier in the list is 43 | // preferred. If no offers match, then defaultOffer is returned. 44 | func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string { 45 | bestOffer := defaultOffer 46 | bestQ := -1.0 47 | bestWild := 3 48 | specs := header.ParseAccept(r.Header, "Accept") 49 | for _, offer := range offers { 50 | for _, spec := range specs { 51 | switch { 52 | case spec.Q == 0.0: 53 | // ignore 54 | case spec.Q < bestQ: 55 | // better match found 56 | case spec.Value == "*/*": 57 | if spec.Q > bestQ || bestWild > 2 { 58 | bestQ = spec.Q 59 | bestWild = 2 60 | bestOffer = offer 61 | } 62 | case strings.HasSuffix(spec.Value, "/*"): 63 | if strings.HasPrefix(offer, spec.Value[:len(spec.Value)-1]) && 64 | (spec.Q > bestQ || bestWild > 1) { 65 | bestQ = spec.Q 66 | bestWild = 1 67 | bestOffer = offer 68 | } 69 | default: 70 | if spec.Value == offer && 71 | (spec.Q > bestQ || bestWild > 0) { 72 | bestQ = spec.Q 73 | bestWild = 0 74 | bestOffer = offer 75 | } 76 | } 77 | } 78 | } 79 | return bestOffer 80 | } 81 | -------------------------------------------------------------------------------- /httputil/negotiate_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil_test 8 | 9 | import ( 10 | "net/http" 11 | "testing" 12 | 13 | "github.com/ory/herodot/httputil" 14 | ) 15 | 16 | var negotiateContentEncodingTests = []struct { 17 | s string 18 | offers []string 19 | expect string 20 | }{ 21 | {"", []string{"identity", "gzip"}, "identity"}, 22 | {"*;q=0", []string{"identity", "gzip"}, ""}, 23 | {"gzip", []string{"identity", "gzip"}, "gzip"}, 24 | } 25 | 26 | func TestNegotiateContentEnoding(t *testing.T) { 27 | for _, tt := range negotiateContentEncodingTests { 28 | r := &http.Request{Header: http.Header{"Accept-Encoding": {tt.s}}} 29 | actual := httputil.NegotiateContentEncoding(r, tt.offers) 30 | if actual != tt.expect { 31 | t.Errorf("NegotiateContentEncoding(%q, %#v)=%q, want %q", tt.s, tt.offers, actual, tt.expect) 32 | } 33 | } 34 | } 35 | 36 | var negotiateContentTypeTests = []struct { 37 | s string 38 | offers []string 39 | defaultOffer string 40 | expect string 41 | }{ 42 | {"text/html, */*;q=0", []string{"x/y"}, "", ""}, 43 | {"text/html, */*", []string{"x/y"}, "", "x/y"}, 44 | {"text/html, image/png", []string{"text/html", "image/png"}, "", "text/html"}, 45 | {"text/html, image/png", []string{"image/png", "text/html"}, "", "image/png"}, 46 | {"text/html, image/png; q=0.5", []string{"image/png"}, "", "image/png"}, 47 | {"text/html, image/png; q=0.5", []string{"text/html"}, "", "text/html"}, 48 | {"text/html, image/png; q=0.5", []string{"foo/bar"}, "", ""}, 49 | {"text/html, image/png; q=0.5", []string{"image/png", "text/html"}, "", "text/html"}, 50 | {"text/html, image/png; q=0.5", []string{"text/html", "image/png"}, "", "text/html"}, 51 | {"text/html;q=0.5, image/png", []string{"image/png"}, "", "image/png"}, 52 | {"text/html;q=0.5, image/png", []string{"text/html"}, "", "text/html"}, 53 | {"text/html;q=0.5, image/png", []string{"image/png", "text/html"}, "", "image/png"}, 54 | {"text/html;q=0.5, image/png", []string{"text/html", "image/png"}, "", "image/png"}, 55 | {"image/png, image/*;q=0.5", []string{"image/jpg", "image/png"}, "", "image/png"}, 56 | {"image/png, image/*;q=0.5", []string{"image/jpg"}, "", "image/jpg"}, 57 | {"image/png, image/*;q=0.5", []string{"image/jpg", "image/gif"}, "", "image/jpg"}, 58 | {"image/png, image/*", []string{"image/jpg", "image/gif"}, "", "image/jpg"}, 59 | {"image/png, image/*", []string{"image/gif", "image/jpg"}, "", "image/gif"}, 60 | {"image/png, image/*", []string{"image/gif", "image/png"}, "", "image/png"}, 61 | {"image/png, image/*", []string{"image/png", "image/gif"}, "", "image/png"}, 62 | } 63 | 64 | func TestNegotiateContentType(t *testing.T) { 65 | for _, tt := range negotiateContentTypeTests { 66 | r := &http.Request{Header: http.Header{"Accept": {tt.s}}} 67 | actual := httputil.NegotiateContentType(r, tt.offers, tt.defaultOffer) 68 | if actual != tt.expect { 69 | t.Errorf("NegotiateContentType(%q, %#v, %q)=%q, want %q", tt.s, tt.offers, tt.defaultOffer, actual, tt.expect) 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /httputil/respbuf.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil 8 | 9 | import ( 10 | "bytes" 11 | "net/http" 12 | "strconv" 13 | ) 14 | 15 | // ResponseBuffer is the current response being composed by its owner. 16 | // It implements http.ResponseWriter and io.WriterTo. 17 | type ResponseBuffer struct { 18 | buf bytes.Buffer 19 | status int 20 | header http.Header 21 | } 22 | 23 | // Write implements the http.ResponseWriter interface. 24 | func (rb *ResponseBuffer) Write(p []byte) (int, error) { 25 | return rb.buf.Write(p) 26 | } 27 | 28 | // WriteHeader implements the http.ResponseWriter interface. 29 | func (rb *ResponseBuffer) WriteHeader(status int) { 30 | rb.status = status 31 | } 32 | 33 | // Header implements the http.ResponseWriter interface. 34 | func (rb *ResponseBuffer) Header() http.Header { 35 | if rb.header == nil { 36 | rb.header = make(http.Header) 37 | } 38 | return rb.header 39 | } 40 | 41 | // WriteTo implements the io.WriterTo interface. 42 | func (rb *ResponseBuffer) WriteTo(w http.ResponseWriter) error { 43 | for k, v := range rb.header { 44 | w.Header()[k] = v 45 | } 46 | if rb.buf.Len() > 0 { 47 | w.Header().Set("Content-Length", strconv.Itoa(rb.buf.Len())) 48 | } 49 | if rb.status != 0 { 50 | w.WriteHeader(rb.status) 51 | } 52 | if rb.buf.Len() > 0 { 53 | if _, err := w.Write(rb.buf.Bytes()); err != nil { 54 | return err 55 | } 56 | } 57 | return nil 58 | } 59 | -------------------------------------------------------------------------------- /httputil/static.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil 8 | 9 | import ( 10 | "bytes" 11 | "crypto/sha1" 12 | "errors" 13 | "fmt" 14 | "io" 15 | "io/ioutil" 16 | "mime" 17 | "net/http" 18 | "os" 19 | "path" 20 | "path/filepath" 21 | "strconv" 22 | "strings" 23 | "sync" 24 | "time" 25 | 26 | "github.com/ory/herodot/httputil/header" 27 | ) 28 | 29 | // StaticServer serves static files. 30 | type StaticServer struct { 31 | // Dir specifies the location of the directory containing the files to serve. 32 | Dir string 33 | 34 | // MaxAge specifies the maximum age for the cache control and expiration 35 | // headers. 36 | MaxAge time.Duration 37 | 38 | // Error specifies the function used to generate error responses. If Error 39 | // is nil, then http.Error is used to generate error responses. 40 | Error Error 41 | 42 | // MIMETypes is a map from file extensions to MIME types. 43 | MIMETypes map[string]string 44 | 45 | mu sync.Mutex 46 | etags map[string]string 47 | } 48 | 49 | func (ss *StaticServer) resolve(fname string) string { 50 | if path.IsAbs(fname) { 51 | panic("Absolute path not allowed when creating a StaticServer handler") 52 | } 53 | dir := ss.Dir 54 | if dir == "" { 55 | dir = "." 56 | } 57 | fname = filepath.FromSlash(fname) 58 | return filepath.Join(dir, fname) 59 | } 60 | 61 | func (ss *StaticServer) mimeType(fname string) string { 62 | ext := path.Ext(fname) 63 | var mimeType string 64 | if ss.MIMETypes != nil { 65 | mimeType = ss.MIMETypes[ext] 66 | } 67 | if mimeType == "" { 68 | mimeType = mime.TypeByExtension(ext) 69 | } 70 | if mimeType == "" { 71 | mimeType = "application/octet-stream" 72 | } 73 | return mimeType 74 | } 75 | 76 | func (ss *StaticServer) openFile(fname string) (io.ReadCloser, int64, string, error) { 77 | f, err := os.Open(fname) 78 | if err != nil { 79 | return nil, 0, "", err 80 | } 81 | fi, err := f.Stat() 82 | if err != nil { 83 | f.Close() 84 | return nil, 0, "", err 85 | } 86 | const modeType = os.ModeDir | os.ModeSymlink | os.ModeNamedPipe | os.ModeSocket | os.ModeDevice 87 | if fi.Mode()&modeType != 0 { 88 | f.Close() 89 | return nil, 0, "", errors.New("not a regular file") 90 | } 91 | return f, fi.Size(), ss.mimeType(fname), nil 92 | } 93 | 94 | // FileHandler returns a handler that serves a single file. The file is 95 | // specified by a slash separated path relative to the static server's Dir 96 | // field. 97 | func (ss *StaticServer) FileHandler(fileName string) http.Handler { 98 | id := fileName 99 | fileName = ss.resolve(fileName) 100 | return &staticHandler{ 101 | ss: ss, 102 | id: func(_ string) string { return id }, 103 | open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) }, 104 | } 105 | } 106 | 107 | // DirectoryHandler returns a handler that serves files from a directory tree. 108 | // The directory is specified by a slash separated path relative to the static 109 | // server's Dir field. 110 | func (ss *StaticServer) DirectoryHandler(prefix, dirName string) http.Handler { 111 | if !strings.HasSuffix(prefix, "/") { 112 | prefix += "/" 113 | } 114 | idBase := dirName 115 | dirName = ss.resolve(dirName) 116 | return &staticHandler{ 117 | ss: ss, 118 | id: func(p string) string { 119 | if !strings.HasPrefix(p, prefix) { 120 | return "." 121 | } 122 | return path.Join(idBase, p[len(prefix):]) 123 | }, 124 | open: func(p string) (io.ReadCloser, int64, string, error) { 125 | if !strings.HasPrefix(p, prefix) { 126 | return nil, 0, "", errors.New("request url does not match directory prefix") 127 | } 128 | p = p[len(prefix):] 129 | return ss.openFile(filepath.Join(dirName, filepath.FromSlash(p))) 130 | }, 131 | } 132 | } 133 | 134 | // FilesHandler returns a handler that serves the concatentation of the 135 | // specified files. The files are specified by slash separated paths relative 136 | // to the static server's Dir field. 137 | func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler { 138 | 139 | // todo: cache concatenated files on disk and serve from there. 140 | 141 | mimeType := ss.mimeType(fileNames[0]) 142 | var buf []byte 143 | var openErr error 144 | 145 | for _, fileName := range fileNames { 146 | p, err := ioutil.ReadFile(ss.resolve(fileName)) 147 | if err != nil { 148 | openErr = err 149 | buf = nil 150 | break 151 | } 152 | buf = append(buf, p...) 153 | } 154 | 155 | id := strings.Join(fileNames, " ") 156 | 157 | return &staticHandler{ 158 | ss: ss, 159 | id: func(_ string) string { return id }, 160 | open: func(p string) (io.ReadCloser, int64, string, error) { 161 | return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr 162 | }, 163 | } 164 | } 165 | 166 | type staticHandler struct { 167 | id func(fname string) string 168 | open func(p string) (io.ReadCloser, int64, string, error) 169 | ss *StaticServer 170 | } 171 | 172 | func (h *staticHandler) error(w http.ResponseWriter, r *http.Request, status int, err error) { 173 | http.Error(w, http.StatusText(status), status) 174 | } 175 | 176 | func (h *staticHandler) etag(p string) (string, error) { 177 | id := h.id(p) 178 | 179 | h.ss.mu.Lock() 180 | if h.ss.etags == nil { 181 | h.ss.etags = make(map[string]string) 182 | } 183 | etag := h.ss.etags[id] 184 | h.ss.mu.Unlock() 185 | 186 | if etag != "" { 187 | return etag, nil 188 | } 189 | 190 | // todo: if a concurrent goroutine is calculating the hash, then wait for 191 | // it instead of computing it again here. 192 | 193 | rc, _, _, err := h.open(p) 194 | if err != nil { 195 | return "", err 196 | } 197 | 198 | defer rc.Close() 199 | 200 | w := sha1.New() 201 | _, err = io.Copy(w, rc) 202 | if err != nil { 203 | return "", err 204 | } 205 | 206 | etag = fmt.Sprintf(`"%x"`, w.Sum(nil)) 207 | 208 | h.ss.mu.Lock() 209 | h.ss.etags[id] = etag 210 | h.ss.mu.Unlock() 211 | 212 | return etag, nil 213 | } 214 | 215 | func (h *staticHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 216 | p := path.Clean(r.URL.Path) 217 | if p != r.URL.Path { 218 | http.Redirect(w, r, p, 301) 219 | return 220 | } 221 | 222 | etag, err := h.etag(p) 223 | if err != nil { 224 | h.error(w, r, http.StatusNotFound, err) 225 | return 226 | } 227 | 228 | maxAge := h.ss.MaxAge 229 | if maxAge == 0 { 230 | maxAge = 24 * time.Hour 231 | } 232 | if r.FormValue("v") != "" { 233 | maxAge = 365 * 24 * time.Hour 234 | } 235 | 236 | cacheControl := fmt.Sprintf("public, max-age=%d", maxAge/time.Second) 237 | 238 | for _, e := range header.ParseList(r.Header, "If-None-Match") { 239 | if e == etag { 240 | w.Header().Set("Cache-Control", cacheControl) 241 | w.Header().Set("Etag", etag) 242 | w.WriteHeader(http.StatusNotModified) 243 | return 244 | } 245 | } 246 | 247 | rc, cl, ct, err := h.open(p) 248 | if err != nil { 249 | h.error(w, r, http.StatusNotFound, err) 250 | return 251 | } 252 | defer rc.Close() 253 | 254 | w.Header().Set("Cache-Control", cacheControl) 255 | w.Header().Set("Etag", etag) 256 | if ct != "" { 257 | w.Header().Set("Content-Type", ct) 258 | } 259 | if cl != 0 { 260 | w.Header().Set("Content-Length", strconv.FormatInt(cl, 10)) 261 | } 262 | w.WriteHeader(http.StatusOK) 263 | if r.Method != "HEAD" { 264 | io.Copy(w, rc) 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /httputil/static_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil_test 8 | 9 | import ( 10 | "crypto/sha1" 11 | "encoding/hex" 12 | "net/http" 13 | "net/http/httptest" 14 | "net/url" 15 | "os" 16 | "strconv" 17 | "testing" 18 | "time" 19 | 20 | "github.com/stretchr/testify/assert" 21 | "github.com/stretchr/testify/require" 22 | 23 | "github.com/ory/herodot/httputil" 24 | ) 25 | 26 | var ( 27 | testHash = computeTestHash() 28 | testEtag = `"` + testHash + `"` 29 | testContentLength = computeTestContentLength() 30 | ) 31 | 32 | func mustParseURL(urlStr string) *url.URL { 33 | u, err := url.Parse(urlStr) 34 | if err != nil { 35 | panic(err) 36 | } 37 | return u 38 | } 39 | 40 | func computeTestHash() string { 41 | p, err := os.ReadFile("static_test.go") 42 | if err != nil { 43 | panic(err) 44 | } 45 | w := sha1.New() 46 | w.Write(p) 47 | return hex.EncodeToString(w.Sum(nil)) 48 | } 49 | 50 | func computeTestContentLength() string { 51 | info, err := os.Stat("static_test.go") 52 | if err != nil { 53 | panic(err) 54 | } 55 | return strconv.FormatInt(info.Size(), 10) 56 | } 57 | 58 | var fileServerTests = []*struct { 59 | name string // test name for log 60 | ss *httputil.StaticServer 61 | r *http.Request 62 | header http.Header // expected response headers 63 | status int // expected response status 64 | empty bool // true if response body not expected. 65 | }{ 66 | { 67 | name: "get", 68 | ss: &httputil.StaticServer{MaxAge: 3 * time.Second}, 69 | r: &http.Request{ 70 | URL: mustParseURL("/dir/static_test.go"), 71 | Method: "GET", 72 | }, 73 | status: http.StatusOK, 74 | header: http.Header{ 75 | "Etag": {testEtag}, 76 | "Cache-Control": {"public, max-age=3"}, 77 | "Content-Length": {testContentLength}, 78 | }, 79 | }, 80 | { 81 | name: "get .", 82 | ss: &httputil.StaticServer{Dir: ".", MaxAge: 3 * time.Second}, 83 | r: &http.Request{ 84 | URL: mustParseURL("/dir/static_test.go"), 85 | Method: "GET", 86 | }, 87 | status: http.StatusOK, 88 | header: http.Header{ 89 | "Etag": {testEtag}, 90 | "Cache-Control": {"public, max-age=3"}, 91 | "Content-Length": {testContentLength}, 92 | }, 93 | }, 94 | { 95 | name: "get with ?v=", 96 | ss: &httputil.StaticServer{MaxAge: 3 * time.Second}, 97 | r: &http.Request{ 98 | URL: mustParseURL("/dir/static_test.go?v=xxxxx"), 99 | Method: "GET", 100 | }, 101 | status: http.StatusOK, 102 | header: http.Header{ 103 | "Etag": {testEtag}, 104 | "Cache-Control": {"public, max-age=31536000"}, 105 | "Content-Length": {testContentLength}, 106 | }, 107 | }, 108 | { 109 | name: "head", 110 | ss: &httputil.StaticServer{MaxAge: 3 * time.Second}, 111 | r: &http.Request{ 112 | URL: mustParseURL("/dir/static_test.go"), 113 | Method: "HEAD", 114 | }, 115 | status: http.StatusOK, 116 | header: http.Header{ 117 | "Etag": {testEtag}, 118 | "Cache-Control": {"public, max-age=3"}, 119 | "Content-Length": {testContentLength}, 120 | }, 121 | empty: true, 122 | }, 123 | { 124 | name: "if-none-match", 125 | ss: &httputil.StaticServer{MaxAge: 3 * time.Second}, 126 | r: &http.Request{ 127 | URL: mustParseURL("/dir/static_test.go"), 128 | Method: "GET", 129 | Header: http.Header{"If-None-Match": {testEtag}}, 130 | }, 131 | status: http.StatusNotModified, 132 | header: http.Header{ 133 | "Cache-Control": {"public, max-age=3"}, 134 | "Etag": {testEtag}, 135 | }, 136 | empty: true, 137 | }, 138 | } 139 | 140 | func testStaticServer(t *testing.T, f func(*httputil.StaticServer) http.Handler) { 141 | for _, tt := range fileServerTests { 142 | t.Run(tt.name, func(t *testing.T) { 143 | w := httptest.NewRecorder() 144 | 145 | h := f(tt.ss) 146 | h.ServeHTTP(w, tt.r) 147 | 148 | require.Equal(t, tt.status, w.Code) 149 | if w.Code != tt.status { 150 | t.Errorf("%s, status=%d, want %d", tt.name, w.Code, tt.status) 151 | } 152 | 153 | // The content-type header depends on the MIME database installed on the 154 | // host system and hence not portable. 155 | actualHeader := w.Header() 156 | actualHeader.Del("Content-Type") 157 | assert.Equal(t, actualHeader, tt.header) 158 | 159 | assert.Equal(t, tt.empty, w.Body.Len() == 0) 160 | }) 161 | } 162 | } 163 | 164 | func TestFileHandler(t *testing.T) { 165 | testStaticServer(t, func(ss *httputil.StaticServer) http.Handler { return ss.FileHandler("static_test.go") }) 166 | } 167 | 168 | func TestDirectoryHandler(t *testing.T) { 169 | testStaticServer(t, func(ss *httputil.StaticServer) http.Handler { return ss.DirectoryHandler("/dir", ".") }) 170 | } 171 | 172 | func TestFilesHandler(t *testing.T) { 173 | testStaticServer(t, func(ss *httputil.StaticServer) http.Handler { return ss.FilesHandler("static_test.go") }) 174 | } 175 | -------------------------------------------------------------------------------- /httputil/transport.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | // This file implements a http.RoundTripper that authenticates 8 | // requests issued against api.github.com endpoint. 9 | 10 | package httputil 11 | 12 | import ( 13 | "net/http" 14 | "net/url" 15 | ) 16 | 17 | // AuthTransport is an implementation of http.RoundTripper that authenticates 18 | // with the GitHub API. 19 | // 20 | // When both a token and client credentials are set, the latter is preferred. 21 | type AuthTransport struct { 22 | UserAgent string 23 | GithubToken string 24 | GithubClientID string 25 | GithubClientSecret string 26 | Base http.RoundTripper 27 | } 28 | 29 | // RoundTrip implements the http.RoundTripper interface. 30 | func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { 31 | var reqCopy *http.Request 32 | if t.UserAgent != "" { 33 | reqCopy = copyRequest(req) 34 | reqCopy.Header.Set("User-Agent", t.UserAgent) 35 | } 36 | if req.URL.Host == "api.github.com" && req.URL.Scheme == "https" { 37 | switch { 38 | case t.GithubClientID != "" && t.GithubClientSecret != "": 39 | if reqCopy == nil { 40 | reqCopy = copyRequest(req) 41 | } 42 | if reqCopy.URL.RawQuery == "" { 43 | reqCopy.URL.RawQuery = "client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret 44 | } else { 45 | reqCopy.URL.RawQuery += "&client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret 46 | } 47 | case t.GithubToken != "": 48 | if reqCopy == nil { 49 | reqCopy = copyRequest(req) 50 | } 51 | reqCopy.Header.Set("Authorization", "token "+t.GithubToken) 52 | } 53 | } 54 | if reqCopy != nil { 55 | return t.base().RoundTrip(reqCopy) 56 | } 57 | return t.base().RoundTrip(req) 58 | } 59 | 60 | // CancelRequest cancels an in-flight request by closing its connection. 61 | func (t *AuthTransport) CancelRequest(req *http.Request) { 62 | type canceler interface { 63 | CancelRequest(req *http.Request) 64 | } 65 | if cr, ok := t.base().(canceler); ok { 66 | cr.CancelRequest(req) 67 | } 68 | } 69 | 70 | func (t *AuthTransport) base() http.RoundTripper { 71 | if t.Base != nil { 72 | return t.Base 73 | } 74 | return http.DefaultTransport 75 | } 76 | 77 | func copyRequest(req *http.Request) *http.Request { 78 | req2 := new(http.Request) 79 | *req2 = *req 80 | req2.URL = new(url.URL) 81 | *req2.URL = *req.URL 82 | req2.Header = make(http.Header, len(req.Header)) 83 | for k, s := range req.Header { 84 | req2.Header[k] = append([]string(nil), s...) 85 | } 86 | return req2 87 | } 88 | -------------------------------------------------------------------------------- /httputil/transport_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file or at 5 | // https://developers.google.com/open-source/licenses/bsd. 6 | 7 | package httputil 8 | 9 | import ( 10 | "bytes" 11 | "io/ioutil" 12 | "net/http" 13 | "net/url" 14 | "testing" 15 | ) 16 | 17 | func TestTransportGithubAuth(t *testing.T) { 18 | tests := []struct { 19 | name string 20 | 21 | url string 22 | token string 23 | clientID string 24 | clientSecret string 25 | 26 | queryClientID string 27 | queryClientSecret string 28 | authorization string 29 | }{ 30 | { 31 | name: "Github token", 32 | url: "https://api.github.com/", 33 | token: "xyzzy", 34 | authorization: "token xyzzy", 35 | }, 36 | { 37 | name: "Github client ID/secret", 38 | url: "https://api.github.com/", 39 | clientID: "12345", 40 | clientSecret: "xyzzy", 41 | queryClientID: "12345", 42 | queryClientSecret: "xyzzy", 43 | }, 44 | { 45 | name: "non-Github site does not have token headers", 46 | url: "http://www.example.com/", 47 | token: "xyzzy", 48 | }, 49 | { 50 | name: "non-Github site does not have client ID/secret headers", 51 | url: "http://www.example.com/", 52 | clientID: "12345", 53 | clientSecret: "xyzzy", 54 | }, 55 | { 56 | name: "Github token not sent over HTTP", 57 | url: "http://api.github.com/", 58 | token: "xyzzy", 59 | }, 60 | { 61 | name: "Github client ID/secret not sent over HTTP", 62 | url: "http://api.github.com/", 63 | clientID: "12345", 64 | clientSecret: "xyzzy", 65 | }, 66 | { 67 | name: "Github token not sent over schemeless", 68 | url: "//api.github.com/", 69 | token: "xyzzy", 70 | }, 71 | { 72 | name: "Github client ID/secret not sent over schemeless", 73 | url: "//api.github.com/", 74 | clientID: "12345", 75 | clientSecret: "xyzzy", 76 | }, 77 | } 78 | for _, test := range tests { 79 | t.Run(test.name, func(t *testing.T) { 80 | var ( 81 | query url.Values 82 | authHeader string 83 | ) 84 | client := &http.Client{ 85 | Transport: &AuthTransport{ 86 | Base: roundTripFunc(func(r *http.Request) { 87 | query = r.URL.Query() 88 | authHeader = r.Header.Get("Authorization") 89 | }), 90 | GithubToken: test.token, 91 | GithubClientID: test.clientID, 92 | GithubClientSecret: test.clientSecret, 93 | }, 94 | } 95 | _, err := client.Get(test.url) 96 | if err != nil { 97 | t.Fatal(err) 98 | } 99 | if got := query.Get("client_id"); got != test.queryClientID { 100 | t.Errorf("url query client_id = %q; want %q", got, test.queryClientID) 101 | } 102 | if got := query.Get("client_secret"); got != test.queryClientSecret { 103 | t.Errorf("url query client_secret = %q; want %q", got, test.queryClientSecret) 104 | } 105 | if authHeader != test.authorization { 106 | t.Errorf("header Authorization = %q; want %q", authHeader, test.authorization) 107 | } 108 | }) 109 | } 110 | } 111 | 112 | type roundTripFunc func(r *http.Request) 113 | 114 | func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { 115 | f(r) 116 | return &http.Response{ 117 | Status: "200 OK", 118 | StatusCode: http.StatusOK, 119 | Proto: "HTTP/1.1", 120 | ProtoMajor: 1, 121 | ProtoMinor: 1, 122 | Body: ioutil.NopCloser(bytes.NewReader(nil)), 123 | ContentLength: 0, 124 | Request: r, 125 | }, nil 126 | } 127 | -------------------------------------------------------------------------------- /internal/helloworld.pb.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2025 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package internal 5 | 6 | // Copy from https://github.com/grpc/grpc-go/blob/1703656ba59e9ceeaa79d03b06ec171ae0e2f33f/examples/helloworld/helloworld/helloworld.pb.go to fix import issues 7 | 8 | // Copyright 2015 gRPC authors. 9 | // 10 | // Licensed under the Apache License, Version 2.0 (the "License"); 11 | // you may not use this file except in compliance with the License. 12 | // You may obtain a copy of the License at 13 | // 14 | // http://www.apache.org/licenses/LICENSE-2.0 15 | // 16 | // Unless required by applicable law or agreed to in writing, software 17 | // distributed under the License is distributed on an "AS IS" BASIS, 18 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | // See the License for the specific language governing permissions and 20 | // limitations under the License. 21 | 22 | // Code generated by protoc-gen-go. DO NOT EDIT. 23 | // versions: 24 | // protoc-gen-go v1.36.5 25 | // protoc v5.27.1 26 | // source: examples/helloworld/helloworld/helloworld.proto 27 | 28 | import ( 29 | reflect "reflect" 30 | sync "sync" 31 | unsafe "unsafe" 32 | 33 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 34 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 35 | ) 36 | 37 | const ( 38 | // Verify that this generated code is sufficiently up-to-date. 39 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 40 | // Verify that runtime/protoimpl is sufficiently up-to-date. 41 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 42 | ) 43 | 44 | // The request message containing the user's name. 45 | type HelloRequest struct { 46 | state protoimpl.MessageState `protogen:"open.v1"` 47 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 48 | unknownFields protoimpl.UnknownFields 49 | sizeCache protoimpl.SizeCache 50 | } 51 | 52 | func (x *HelloRequest) Reset() { 53 | *x = HelloRequest{} 54 | mi := &file_examples_helloworld_helloworld_helloworld_proto_msgTypes[0] 55 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 56 | ms.StoreMessageInfo(mi) 57 | } 58 | 59 | func (x *HelloRequest) String() string { 60 | return protoimpl.X.MessageStringOf(x) 61 | } 62 | 63 | func (*HelloRequest) ProtoMessage() {} 64 | 65 | func (x *HelloRequest) ProtoReflect() protoreflect.Message { 66 | mi := &file_examples_helloworld_helloworld_helloworld_proto_msgTypes[0] 67 | if x != nil { 68 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 69 | if ms.LoadMessageInfo() == nil { 70 | ms.StoreMessageInfo(mi) 71 | } 72 | return ms 73 | } 74 | return mi.MessageOf(x) 75 | } 76 | 77 | // Deprecated: Use HelloRequest.ProtoReflect.Descriptor instead. 78 | func (*HelloRequest) Descriptor() ([]byte, []int) { 79 | return file_examples_helloworld_helloworld_helloworld_proto_rawDescGZIP(), []int{0} 80 | } 81 | 82 | func (x *HelloRequest) GetName() string { 83 | if x != nil { 84 | return x.Name 85 | } 86 | return "" 87 | } 88 | 89 | // The response message containing the greetings 90 | type HelloReply struct { 91 | state protoimpl.MessageState `protogen:"open.v1"` 92 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 93 | unknownFields protoimpl.UnknownFields 94 | sizeCache protoimpl.SizeCache 95 | } 96 | 97 | func (x *HelloReply) Reset() { 98 | *x = HelloReply{} 99 | mi := &file_examples_helloworld_helloworld_helloworld_proto_msgTypes[1] 100 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 101 | ms.StoreMessageInfo(mi) 102 | } 103 | 104 | func (x *HelloReply) String() string { 105 | return protoimpl.X.MessageStringOf(x) 106 | } 107 | 108 | func (*HelloReply) ProtoMessage() {} 109 | 110 | func (x *HelloReply) ProtoReflect() protoreflect.Message { 111 | mi := &file_examples_helloworld_helloworld_helloworld_proto_msgTypes[1] 112 | if x != nil { 113 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 114 | if ms.LoadMessageInfo() == nil { 115 | ms.StoreMessageInfo(mi) 116 | } 117 | return ms 118 | } 119 | return mi.MessageOf(x) 120 | } 121 | 122 | // Deprecated: Use HelloReply.ProtoReflect.Descriptor instead. 123 | func (*HelloReply) Descriptor() ([]byte, []int) { 124 | return file_examples_helloworld_helloworld_helloworld_proto_rawDescGZIP(), []int{1} 125 | } 126 | 127 | func (x *HelloReply) GetMessage() string { 128 | if x != nil { 129 | return x.Message 130 | } 131 | return "" 132 | } 133 | 134 | var File_examples_helloworld_helloworld_helloworld_proto protoreflect.FileDescriptor 135 | 136 | var file_examples_helloworld_helloworld_helloworld_proto_rawDesc = string([]byte{ 137 | 0x0a, 0x2f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x73, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 138 | 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64, 139 | 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 140 | 0x6f, 0x12, 0x0a, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x22, 0x22, 0x0a, 141 | 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 142 | 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 143 | 0x65, 0x22, 0x26, 0x0a, 0x0a, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 144 | 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 145 | 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x49, 0x0a, 0x07, 0x47, 0x72, 0x65, 146 | 0x65, 0x74, 0x65, 0x72, 0x12, 0x3e, 0x0a, 0x08, 0x53, 0x61, 0x79, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 147 | 0x12, 0x18, 0x2e, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x2e, 0x48, 0x65, 148 | 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x68, 0x65, 0x6c, 149 | 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x70, 150 | 0x6c, 0x79, 0x22, 0x00, 0x42, 0x67, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 151 | 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x73, 0x2e, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 152 | 0x72, 0x6c, 0x64, 0x42, 0x0f, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x50, 153 | 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x35, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 154 | 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x65, 155 | 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x73, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 156 | 0x6c, 0x64, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x62, 0x06, 0x70, 157 | 0x72, 0x6f, 0x74, 0x6f, 0x33, 158 | }) 159 | 160 | var ( 161 | file_examples_helloworld_helloworld_helloworld_proto_rawDescOnce sync.Once 162 | file_examples_helloworld_helloworld_helloworld_proto_rawDescData []byte 163 | ) 164 | 165 | func file_examples_helloworld_helloworld_helloworld_proto_rawDescGZIP() []byte { 166 | file_examples_helloworld_helloworld_helloworld_proto_rawDescOnce.Do(func() { 167 | file_examples_helloworld_helloworld_helloworld_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_examples_helloworld_helloworld_helloworld_proto_rawDesc), len(file_examples_helloworld_helloworld_helloworld_proto_rawDesc))) 168 | }) 169 | return file_examples_helloworld_helloworld_helloworld_proto_rawDescData 170 | } 171 | 172 | var file_examples_helloworld_helloworld_helloworld_proto_msgTypes = make([]protoimpl.MessageInfo, 2) 173 | var file_examples_helloworld_helloworld_helloworld_proto_goTypes = []any{ 174 | (*HelloRequest)(nil), // 0: helloworld.HelloRequest 175 | (*HelloReply)(nil), // 1: helloworld.HelloReply 176 | } 177 | var file_examples_helloworld_helloworld_helloworld_proto_depIdxs = []int32{ 178 | 0, // 0: helloworld.Greeter.SayHello:input_type -> helloworld.HelloRequest 179 | 1, // 1: helloworld.Greeter.SayHello:output_type -> helloworld.HelloReply 180 | 1, // [1:2] is the sub-list for method output_type 181 | 0, // [0:1] is the sub-list for method input_type 182 | 0, // [0:0] is the sub-list for extension type_name 183 | 0, // [0:0] is the sub-list for extension extendee 184 | 0, // [0:0] is the sub-list for field type_name 185 | } 186 | 187 | func init() { file_examples_helloworld_helloworld_helloworld_proto_init() } 188 | func file_examples_helloworld_helloworld_helloworld_proto_init() { 189 | if File_examples_helloworld_helloworld_helloworld_proto != nil { 190 | return 191 | } 192 | type x struct{} 193 | out := protoimpl.TypeBuilder{ 194 | File: protoimpl.DescBuilder{ 195 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 196 | RawDescriptor: unsafe.Slice(unsafe.StringData(file_examples_helloworld_helloworld_helloworld_proto_rawDesc), len(file_examples_helloworld_helloworld_helloworld_proto_rawDesc)), 197 | NumEnums: 0, 198 | NumMessages: 2, 199 | NumExtensions: 0, 200 | NumServices: 1, 201 | }, 202 | GoTypes: file_examples_helloworld_helloworld_helloworld_proto_goTypes, 203 | DependencyIndexes: file_examples_helloworld_helloworld_helloworld_proto_depIdxs, 204 | MessageInfos: file_examples_helloworld_helloworld_helloworld_proto_msgTypes, 205 | }.Build() 206 | File_examples_helloworld_helloworld_helloworld_proto = out.File 207 | file_examples_helloworld_helloworld_helloworld_proto_goTypes = nil 208 | file_examples_helloworld_helloworld_helloworld_proto_depIdxs = nil 209 | } 210 | -------------------------------------------------------------------------------- /internal/helloworld_grpc.pb.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2025 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package internal 5 | 6 | // Copy from https://github.com/grpc/grpc-go/blob/1703656ba59e9ceeaa79d03b06ec171ae0e2f33f/examples/helloworld/helloworld/helloworld_grpc.pb.go to fix import issues 7 | 8 | // Copyright 2015 gRPC authors. 9 | // 10 | // Licensed under the Apache License, Version 2.0 (the "License"); 11 | // you may not use this file except in compliance with the License. 12 | // You may obtain a copy of the License at 13 | // 14 | // http://www.apache.org/licenses/LICENSE-2.0 15 | // 16 | // Unless required by applicable law or agreed to in writing, software 17 | // distributed under the License is distributed on an "AS IS" BASIS, 18 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | // See the License for the specific language governing permissions and 20 | // limitations under the License. 21 | 22 | // Code generated by protoc-gen-go-grpc. DO NOT EDIT. 23 | // versions: 24 | // - protoc-gen-go-grpc v1.5.1 25 | // - protoc v5.27.1 26 | // source: examples/helloworld/helloworld/helloworld.proto 27 | 28 | import ( 29 | context "context" 30 | 31 | grpc "google.golang.org/grpc" 32 | codes "google.golang.org/grpc/codes" 33 | status "google.golang.org/grpc/status" 34 | ) 35 | 36 | // This is a compile-time assertion to ensure that this generated file 37 | // is compatible with the grpc package it is being compiled against. 38 | // Requires gRPC-Go v1.64.0 or later. 39 | const _ = grpc.SupportPackageIsVersion9 40 | 41 | const ( 42 | Greeter_SayHello_FullMethodName = "/helloworld.Greeter/SayHello" 43 | ) 44 | 45 | // GreeterClient is the client API for Greeter service. 46 | // 47 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. 48 | // 49 | // The greeting service definition. 50 | type GreeterClient interface { 51 | // Sends a greeting 52 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 53 | } 54 | 55 | type greeterClient struct { 56 | cc grpc.ClientConnInterface 57 | } 58 | 59 | func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { 60 | return &greeterClient{cc} 61 | } 62 | 63 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 64 | cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) 65 | out := new(HelloReply) 66 | err := c.cc.Invoke(ctx, Greeter_SayHello_FullMethodName, in, out, cOpts...) 67 | if err != nil { 68 | return nil, err 69 | } 70 | return out, nil 71 | } 72 | 73 | // GreeterServer is the server API for Greeter service. 74 | // All implementations must embed UnimplementedGreeterServer 75 | // for forward compatibility. 76 | // 77 | // The greeting service definition. 78 | type GreeterServer interface { 79 | // Sends a greeting 80 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 81 | mustEmbedUnimplementedGreeterServer() 82 | } 83 | 84 | // UnimplementedGreeterServer must be embedded to have 85 | // forward compatible implementations. 86 | // 87 | // NOTE: this should be embedded by value instead of pointer to avoid a nil 88 | // pointer dereference when methods are called. 89 | type UnimplementedGreeterServer struct{} 90 | 91 | func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) { 92 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 93 | } 94 | func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} 95 | func (UnimplementedGreeterServer) testEmbeddedByValue() {} 96 | 97 | // UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service. 98 | // Use of this interface is not recommended, as added methods to GreeterServer will 99 | // result in compilation errors. 100 | type UnsafeGreeterServer interface { 101 | mustEmbedUnimplementedGreeterServer() 102 | } 103 | 104 | func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { 105 | // If the following call panics, it indicates UnimplementedGreeterServer was 106 | // embedded by pointer and is nil. This will cause panics if an 107 | // unimplemented method is ever invoked, so we test this at initialization 108 | // time to prevent it from happening at runtime later due to I/O. 109 | if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { 110 | t.testEmbeddedByValue() 111 | } 112 | s.RegisterService(&Greeter_ServiceDesc, srv) 113 | } 114 | 115 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 116 | in := new(HelloRequest) 117 | if err := dec(in); err != nil { 118 | return nil, err 119 | } 120 | if interceptor == nil { 121 | return srv.(GreeterServer).SayHello(ctx, in) 122 | } 123 | info := &grpc.UnaryServerInfo{ 124 | Server: srv, 125 | FullMethod: Greeter_SayHello_FullMethodName, 126 | } 127 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 128 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 129 | } 130 | return interceptor(ctx, in, info, handler) 131 | } 132 | 133 | // Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service. 134 | // It's only intended for direct use with grpc.RegisterService, 135 | // and not to be introspected or modified (even as a copy) 136 | var Greeter_ServiceDesc = grpc.ServiceDesc{ 137 | ServiceName: "helloworld.Greeter", 138 | HandlerType: (*GreeterServer)(nil), 139 | Methods: []grpc.MethodDesc{ 140 | { 141 | MethodName: "SayHello", 142 | Handler: _Greeter_SayHello_Handler, 143 | }, 144 | }, 145 | Streams: []grpc.StreamDesc{}, 146 | Metadata: "examples/helloworld/helloworld/helloworld.proto", 147 | } 148 | -------------------------------------------------------------------------------- /json.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "bytes" 8 | "context" 9 | "encoding/json" 10 | stderr "errors" 11 | "net/http" 12 | 13 | "github.com/pkg/errors" 14 | ) 15 | 16 | type ErrorContainer struct { 17 | Error *DefaultError `json:"error"` 18 | } 19 | 20 | type ErrorReporter interface { 21 | ReportError(r *http.Request, code int, err error, args ...interface{}) 22 | } 23 | 24 | type EncoderOptions func(*json.Encoder) 25 | 26 | // UnescapedHTML prevents HTML entities &, <, > from being unicode-escaped. 27 | func UnescapedHTML(enc *json.Encoder) { 28 | enc.SetEscapeHTML(false) 29 | } 30 | 31 | // JSONWriter writes JSON responses (obviously). 32 | type JSONWriter struct { 33 | Reporter ErrorReporter 34 | ErrorEnhancer func(r *http.Request, err error) interface{} 35 | EnableDebug bool 36 | } 37 | 38 | var _ Writer = (*JSONWriter)(nil) 39 | 40 | func NewJSONWriter(reporter ErrorReporter) *JSONWriter { 41 | writer := &JSONWriter{ 42 | Reporter: reporter, 43 | ErrorEnhancer: defaultJSONErrorEnhancer, 44 | } 45 | if writer.Reporter == nil { 46 | writer.Reporter = &stdReporter{} 47 | } 48 | 49 | writer.ErrorEnhancer = defaultJSONErrorEnhancer 50 | return writer 51 | } 52 | 53 | type ErrorEnhancer interface { 54 | EnhanceJSONError() interface{} 55 | } 56 | 57 | func defaultJSONErrorEnhancer(r *http.Request, err error) interface{} { 58 | if e, ok := err.(ErrorEnhancer); ok { 59 | return e.EnhanceJSONError() 60 | } 61 | return &ErrorContainer{Error: ToDefaultError(err, r.Header.Get("X-Request-ID"))} 62 | } 63 | 64 | func Scrub5xxJSONErrorEnhancer(r *http.Request, err error) interface{} { 65 | payload := defaultJSONErrorEnhancer(r, err) 66 | 67 | if de, ok := payload.(DefaultError); ok { 68 | if de.StatusCode() >= 500 { 69 | return scrub5xxError(&de) 70 | } 71 | return payload 72 | } 73 | if ec, ok := payload.(*ErrorContainer); ok { 74 | if ec.Error.CodeField >= 500 { 75 | return scrub5xxError(ec.Error) 76 | } 77 | return payload 78 | } 79 | 80 | // We have some other error, which we always want to scrub. 81 | return &ErrorContainer{Error: ToDefaultError(&ErrInternalServerError, r.Header.Get("X-Request-ID"))} 82 | } 83 | 84 | func scrub5xxError(err *DefaultError) *ErrorContainer { 85 | return &ErrorContainer{Error: &DefaultError{ 86 | IDField: err.IDField, 87 | CodeField: err.CodeField, 88 | StatusField: err.StatusField, 89 | RIDField: err.RIDField, 90 | GRPCCodeField: err.GRPCCodeField, 91 | }} 92 | } 93 | 94 | // Write a response object to the ResponseWriter with status code 200. 95 | func (h *JSONWriter) Write(w http.ResponseWriter, r *http.Request, e interface{}, opts ...EncoderOptions) { 96 | h.WriteCode(w, r, http.StatusOK, e, opts...) 97 | } 98 | 99 | // WriteCode writes a response object to the ResponseWriter and sets a response code. 100 | func (h *JSONWriter) WriteCode(w http.ResponseWriter, r *http.Request, code int, e interface{}, opts ...EncoderOptions) { 101 | bs := new(bytes.Buffer) 102 | enc := json.NewEncoder(bs) 103 | for _, opt := range opts { 104 | opt(enc) 105 | } 106 | 107 | err := enc.Encode(e) 108 | if err != nil { 109 | h.WriteError(w, r, errors.WithStack(err)) 110 | return 111 | } 112 | 113 | if code == 0 { 114 | code = http.StatusOK 115 | } 116 | 117 | if errors.Is(r.Context().Err(), context.Canceled) { 118 | code = StatusClientClosedRequest 119 | } 120 | 121 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 122 | w.WriteHeader(code) 123 | _, _ = w.Write(bs.Bytes()) 124 | } 125 | 126 | // WriteCreated writes a response object to the ResponseWriter with status code 201 and 127 | // the Location header set to location. 128 | func (h *JSONWriter) WriteCreated(w http.ResponseWriter, r *http.Request, location string, e interface{}) { 129 | w.Header().Set("Location", location) 130 | h.WriteCode(w, r, http.StatusCreated, e) 131 | } 132 | 133 | // WriteError writes an error to ResponseWriter and tries to extract the error's status code by 134 | // asserting statusCodeCarrier. If the error does not implement statusCodeCarrier, the status code 135 | // is set to 500. 136 | func (h *JSONWriter) WriteError(w http.ResponseWriter, r *http.Request, err error, opts ...Option) { 137 | if c := StatusCodeCarrier(nil); stderr.As(err, &c) { 138 | h.WriteErrorCode(w, r, c.StatusCode(), err) 139 | } else { 140 | h.WriteErrorCode(w, r, http.StatusInternalServerError, err, opts...) 141 | } 142 | } 143 | 144 | // WriteErrorCode writes an error to ResponseWriter and forces an error code. 145 | func (h *JSONWriter) WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err error, opts ...Option) { 146 | o := newOptions(opts) 147 | 148 | if code == 0 { 149 | code = http.StatusInternalServerError 150 | } 151 | 152 | if errors.Is(r.Context().Err(), context.Canceled) { 153 | code = StatusClientClosedRequest 154 | } 155 | 156 | if !o.noLog { 157 | // All errors land here, so it's a really good idea to do the logging here as well! 158 | h.Reporter.ReportError(r, code, coalesceError(err), "An error occurred while handling a request") 159 | } 160 | 161 | w.Header().Set("Content-Type", "application/json") 162 | w.WriteHeader(code) 163 | 164 | // Enhancing must happen after logging or context will be lost. 165 | var payload interface{} = err 166 | if h.ErrorEnhancer != nil { 167 | payload = h.ErrorEnhancer(r, err) 168 | } 169 | if de, ok := payload.(*DefaultError); ok && !h.EnableDebug { 170 | de2 := *de 171 | de2.DebugField = "" 172 | payload = &de2 173 | } 174 | if ec, ok := payload.(*ErrorContainer); ok && !h.EnableDebug { 175 | de2 := *ec.Error 176 | de2.DebugField = "" 177 | ec2 := *ec 178 | ec2.Error = &de2 179 | payload = ec2 180 | } 181 | 182 | if err := json.NewEncoder(w).Encode(payload); err != nil { 183 | // There was an error, but there's actually not a lot we can do except log that this happened. 184 | h.Reporter.ReportError(r, code, errors.WithStack(err), "Could not write ErrorContainer to response writer") 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /json_test.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "bytes" 8 | "context" 9 | "encoding/json" 10 | stderr "errors" 11 | "fmt" 12 | "io" 13 | "net/http" 14 | "net/http/httptest" 15 | "testing" 16 | "time" 17 | 18 | "github.com/pkg/errors" 19 | "github.com/stretchr/testify/assert" 20 | "github.com/stretchr/testify/require" 21 | ) 22 | 23 | var ( 24 | exampleError = &DefaultError{ 25 | CodeField: http.StatusNotFound, 26 | ErrorField: "foo", 27 | ReasonField: "some-reason", 28 | StatusField: "some-status", 29 | DetailsField: map[string]interface{}{ 30 | "foo": "bar", 31 | }, 32 | } 33 | onlyStatusCodeError = &statusCodeError{statusCode: http.StatusNotFound, error: errors.New("foo")} 34 | ) 35 | 36 | type statusCodeError struct { 37 | statusCode int 38 | error 39 | } 40 | 41 | func (s *statusCodeError) StatusCode() int { 42 | return s.statusCode 43 | } 44 | 45 | func TestWriteError(t *testing.T) { 46 | tracedErr := errors.New("err") 47 | for k, tc := range []struct { 48 | err error 49 | expect *DefaultError 50 | }{ 51 | { 52 | err: exampleError, 53 | expect: exampleError, 54 | }, 55 | { 56 | err: errors.WithStack(exampleError), 57 | expect: exampleError, 58 | }, 59 | { 60 | err: onlyStatusCodeError, 61 | expect: &DefaultError{ 62 | StatusField: http.StatusText(http.StatusNotFound), 63 | CodeField: http.StatusNotFound, 64 | ErrorField: "foo", 65 | }, 66 | }, 67 | { 68 | err: errors.WithStack(onlyStatusCodeError), 69 | expect: &DefaultError{ 70 | StatusField: http.StatusText(http.StatusNotFound), 71 | CodeField: http.StatusNotFound, 72 | ErrorField: "foo", 73 | }, 74 | }, 75 | { 76 | err: errors.New("foo"), 77 | expect: &DefaultError{ 78 | StatusField: http.StatusText(http.StatusInternalServerError), 79 | CodeField: http.StatusInternalServerError, 80 | ErrorField: "foo", 81 | }, 82 | }, 83 | { 84 | err: errors.WithStack(errors.New("foo1")), 85 | expect: &DefaultError{ 86 | StatusField: http.StatusText(http.StatusInternalServerError), 87 | CodeField: http.StatusInternalServerError, 88 | ErrorField: "foo1", 89 | }, 90 | }, 91 | { 92 | err: stderr.New("foo1"), 93 | expect: &DefaultError{ 94 | StatusField: http.StatusText(http.StatusInternalServerError), 95 | CodeField: http.StatusInternalServerError, 96 | ErrorField: "foo1", 97 | }, 98 | }, 99 | { 100 | err: ErrInternalServerError.WithTrace(tracedErr).WithReasonf("Unable to prepare JSON Schema for HTTP Post Body Form parsing: %s", tracedErr).WithDebugf("%+v", tracedErr), 101 | expect: &DefaultError{ 102 | ReasonField: fmt.Sprintf("Unable to prepare JSON Schema for HTTP Post Body Form parsing: %s", tracedErr), 103 | StatusField: http.StatusText(http.StatusInternalServerError), 104 | CodeField: http.StatusInternalServerError, 105 | ErrorField: "An internal server error occurred, please contact the system administrator", 106 | DebugField: fmt.Sprintf("%+v", tracedErr), 107 | }, 108 | }, 109 | } { 110 | t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { 111 | var j ErrorContainer 112 | 113 | h := NewJSONWriter(nil) 114 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 115 | r.Header.Set("X-Request-ID", "foo") 116 | h.WriteError(w, r, tc.err) 117 | })) 118 | defer ts.Close() 119 | 120 | resp, err := http.Get(ts.URL + "/do") 121 | require.Nil(t, err) 122 | defer resp.Body.Close() 123 | body, _ := io.ReadAll(resp.Body) 124 | 125 | require.Nil(t, json.NewDecoder(bytes.NewBuffer(body)).Decode(&j), "%s", body) 126 | assert.Equal(t, tc.expect.StatusCode(), resp.StatusCode, "%s", body) 127 | assert.Equal(t, "foo", j.Error.RequestID(), "%s", body) 128 | assert.Equal(t, tc.expect.Status(), j.Error.Status(), "%s", body) 129 | assert.Equal(t, tc.expect.StatusCode(), j.Error.StatusCode(), "%s", body) 130 | assert.Equal(t, tc.expect.Reason(), j.Error.Reason(), "%s", body) 131 | assert.Equal(t, tc.expect.Error(), j.Error.Error(), "%s", body) 132 | }) 133 | } 134 | 135 | t.Run("suite=5xxScrubber", func(t *testing.T) { 136 | 137 | for k, tc := range []struct { 138 | err error 139 | expect *DefaultError 140 | }{ 141 | { 142 | err: exampleError, 143 | expect: exampleError, 144 | }, 145 | { 146 | err: errors.WithStack(exampleError), 147 | expect: exampleError, 148 | }, 149 | { 150 | err: onlyStatusCodeError, 151 | expect: &DefaultError{ 152 | StatusField: http.StatusText(http.StatusNotFound), 153 | CodeField: http.StatusNotFound, 154 | ErrorField: "foo", 155 | }, 156 | }, 157 | { 158 | err: errors.WithStack(onlyStatusCodeError), 159 | expect: &DefaultError{ 160 | StatusField: http.StatusText(http.StatusNotFound), 161 | CodeField: http.StatusNotFound, 162 | ErrorField: "foo", 163 | }, 164 | }, 165 | { 166 | err: errors.New("foo"), 167 | expect: &DefaultError{ 168 | StatusField: http.StatusText(http.StatusInternalServerError), 169 | CodeField: http.StatusInternalServerError, 170 | ErrorField: "", // scrubbed 171 | }, 172 | }, 173 | { 174 | err: errors.WithStack(errors.New("foo1")), 175 | expect: &DefaultError{ 176 | StatusField: http.StatusText(http.StatusInternalServerError), 177 | CodeField: http.StatusInternalServerError, 178 | ErrorField: "", // scrubbed 179 | }, 180 | }, 181 | { 182 | err: stderr.New("foo1"), 183 | expect: &DefaultError{ 184 | StatusField: http.StatusText(http.StatusInternalServerError), 185 | CodeField: http.StatusInternalServerError, 186 | ErrorField: "", // scrubbed 187 | }, 188 | }, 189 | { 190 | err: ErrInternalServerError.WithTrace(tracedErr).WithReasonf("Unable to prepare JSON Schema for HTTP Post Body Form parsing: %s", tracedErr).WithDebugf("%+v", tracedErr), 191 | expect: &DefaultError{ 192 | ReasonField: "", // scrubbed 193 | StatusField: http.StatusText(http.StatusInternalServerError), 194 | CodeField: http.StatusInternalServerError, 195 | ErrorField: "", // scrubbed 196 | DebugField: "", // scrubbed 197 | }, 198 | }, 199 | } { 200 | t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { 201 | var j ErrorContainer 202 | 203 | h := NewJSONWriter(nil) 204 | h.ErrorEnhancer = Scrub5xxJSONErrorEnhancer 205 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 206 | r.Header.Set("X-Request-ID", "foo") 207 | h.WriteError(w, r, tc.err) 208 | })) 209 | defer ts.Close() 210 | 211 | resp, err := http.Get(ts.URL + "/do") 212 | require.Nil(t, err) 213 | defer resp.Body.Close() 214 | body, _ := io.ReadAll(resp.Body) 215 | 216 | require.NoError(t, json.NewDecoder(bytes.NewBuffer(body)).Decode(&j), "%s", body) 217 | assert.Equal(t, tc.expect.StatusCode(), resp.StatusCode, "%s", body) 218 | assert.Equal(t, "foo", j.Error.RequestID(), "%s", body) 219 | assert.Equal(t, tc.expect.Status(), j.Error.Status(), "%s", body) 220 | assert.Equal(t, tc.expect.StatusCode(), j.Error.StatusCode(), "%s", body) 221 | assert.Equal(t, tc.expect.Reason(), j.Error.Reason(), "%s", body) 222 | assert.Equal(t, tc.expect.Error(), j.Error.Error(), "%s", body) 223 | }) 224 | } 225 | }) 226 | 227 | t.Run("case=debug flag", func(t *testing.T) { 228 | for _, tc := range []struct { 229 | isDebug bool 230 | desc string 231 | }{ 232 | { 233 | isDebug: true, 234 | desc: "should be set", 235 | }, 236 | { 237 | isDebug: false, 238 | desc: "should not be set", 239 | }, 240 | } { 241 | t.Run(tc.desc, func(t *testing.T) { 242 | h := NewJSONWriter(nil) 243 | h.EnableDebug = tc.isDebug 244 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 245 | h.WriteError(w, r, &DefaultError{DebugField: "foo"}) 246 | })) 247 | defer ts.Close() 248 | 249 | resp, err := http.Get(ts.URL + "/do") 250 | require.NoError(t, err) 251 | defer resp.Body.Close() 252 | body, _ := io.ReadAll(resp.Body) 253 | 254 | var j ErrorContainer 255 | require.NoError(t, json.NewDecoder(bytes.NewBuffer(body)).Decode(&j), "%s", body) 256 | assert.Equal(t, tc.isDebug, j.Error.Debug() != "", "%s", body) 257 | }) 258 | } 259 | }) 260 | } 261 | 262 | type testError struct { 263 | Foo string `json:"foo"` 264 | Bar string `json:"bar"` 265 | } 266 | 267 | func (e *testError) Error() string { 268 | return e.Foo 269 | } 270 | 271 | func TestWriteErrorNoEnrichment(t *testing.T) { 272 | h := NewJSONWriter(nil) 273 | h.ErrorEnhancer = nil 274 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 275 | r.Header.Set("X-Request-ID", "foo") 276 | h.WriteErrorCode(w, r, 0, &testError{ 277 | Foo: "foo", Bar: "bar", 278 | }) 279 | })) 280 | defer ts.Close() 281 | 282 | resp, err := http.Get(ts.URL + "/do") 283 | require.NoError(t, err) 284 | body, err := io.ReadAll(resp.Body) 285 | require.NoError(t, err) 286 | 287 | assert.EqualValues(t, `{"foo":"foo","bar":"bar"} 288 | `, string(body)) 289 | } 290 | 291 | func TestWriteErrorCode(t *testing.T) { 292 | var j ErrorContainer 293 | 294 | h := NewJSONWriter(nil) 295 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 296 | r.Header.Set("X-Request-ID", "foo") 297 | h.WriteErrorCode(w, r, 0, errors.Wrap(exampleError, "")) 298 | })) 299 | defer ts.Close() 300 | 301 | resp, err := http.Get(ts.URL + "/do") 302 | require.Nil(t, err) 303 | 304 | require.Nil(t, json.NewDecoder(resp.Body).Decode(&j)) 305 | assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) 306 | assert.Equal(t, "foo", j.Error.RequestID()) 307 | } 308 | 309 | func TestWriteJSON(t *testing.T) { 310 | foo := map[string]string{"foo": "bar"} 311 | 312 | h := NewJSONWriter(nil) 313 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 314 | h.Write(w, r, &foo) 315 | })) 316 | defer ts.Close() 317 | 318 | resp, err := http.Get(ts.URL + "/do") 319 | require.Nil(t, err) 320 | 321 | result := map[string]string{} 322 | require.Nil(t, json.NewDecoder(resp.Body).Decode(&result)) 323 | assert.Equal(t, foo["foo"], result["foo"]) 324 | } 325 | 326 | func TestWriteCreatedJSON(t *testing.T) { 327 | foo := map[string]string{"foo": "bar"} 328 | 329 | h := NewJSONWriter(nil) 330 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 331 | h.WriteCreated(w, r, "/new", &foo) 332 | })) 333 | defer ts.Close() 334 | 335 | resp, err := http.Get(ts.URL + "/do") 336 | require.Nil(t, err) 337 | 338 | result := map[string]string{} 339 | require.Nil(t, json.NewDecoder(resp.Body).Decode(&result)) 340 | assert.Equal(t, foo["foo"], result["foo"]) 341 | assert.Equal(t, http.StatusCreated, resp.StatusCode) 342 | assert.Equal(t, "/new", resp.Header.Get("Location")) 343 | } 344 | 345 | func TestWriteCodeJSON(t *testing.T) { 346 | foo := map[string]string{"foo": "bar"} 347 | 348 | h := NewJSONWriter(nil) 349 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 350 | h.WriteCode(w, r, 400, &foo) 351 | })) 352 | defer ts.Close() 353 | 354 | resp, err := http.Get(ts.URL + "/do") 355 | require.Nil(t, err) 356 | 357 | result := map[string]string{} 358 | require.Nil(t, json.NewDecoder(resp.Body).Decode(&result)) 359 | assert.Equal(t, foo["foo"], result["foo"]) 360 | assert.Equal(t, 400, resp.StatusCode) 361 | } 362 | 363 | func TestWriteCodeJSONDefault(t *testing.T) { 364 | foo := map[string]string{"foo": "bar"} 365 | 366 | h := NewJSONWriter(nil) 367 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 368 | h.WriteCode(w, r, 0, &foo) 369 | })) 370 | defer ts.Close() 371 | 372 | resp, err := http.Get(ts.URL + "/do") 373 | require.Nil(t, err) 374 | 375 | result := map[string]string{} 376 | require.Nil(t, json.NewDecoder(resp.Body).Decode(&result)) 377 | assert.Equal(t, foo["foo"], result["foo"]) 378 | assert.Equal(t, http.StatusOK, resp.StatusCode) 379 | } 380 | 381 | func TestWriteCodeJSONUnescapedHTML(t *testing.T) { 382 | foo := "b&r" 383 | 384 | h := NewJSONWriter(nil) 385 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 386 | h.WriteCode(w, r, 0, &foo, UnescapedHTML) 387 | })) 388 | defer ts.Close() 389 | 390 | resp, err := http.Get(ts.URL + "/do") 391 | require.Nil(t, err) 392 | 393 | result, err := io.ReadAll(resp.Body) 394 | require.Nil(t, err) 395 | assert.Equal(t, fmt.Sprintf("\"%s\"\n", foo), string(result)) 396 | assert.Equal(t, http.StatusOK, resp.StatusCode) 397 | } 398 | 399 | func TestCanceledJSON(t *testing.T) { 400 | h := NewJSONWriter(nil) 401 | rec := httptest.NewRecorder() 402 | done := make(chan struct{}) 403 | ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { 404 | defer close(done) 405 | <-r.Context().Done() 406 | h.WriteError(rec, r, errors.New("some unrelated error")) 407 | })) 408 | defer ts.Close() 409 | 410 | ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) 411 | defer cancel() 412 | req, err := http.NewRequestWithContext(ctx, "GET", ts.URL, nil) 413 | require.NoError(t, err) 414 | 415 | _, err = ts.Client().Do(req) 416 | require.ErrorIs(t, err, context.DeadlineExceeded) 417 | 418 | <-done 419 | resp := rec.Result() 420 | body, err := io.ReadAll(resp.Body) 421 | require.NoError(t, err) 422 | assert.Contains(t, string(body), "some unrelated error") 423 | assert.Equal(t, 499, resp.StatusCode) 424 | } 425 | -------------------------------------------------------------------------------- /negotiator.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "net/http" 8 | 9 | "github.com/ory/herodot/httputil" 10 | ) 11 | 12 | // NegotiationHandler automatically negotiates the content type with the request client. 13 | type NegotiationHandler struct { 14 | json *JSONWriter 15 | plain *TextWriter 16 | html *TextWriter 17 | types []string 18 | } 19 | 20 | // NewNegotiationHandler creates a new NewNegotiationHandler. 21 | func NewNegotiationHandler(reporter ErrorReporter) *NegotiationHandler { 22 | return &NegotiationHandler{ 23 | json: NewJSONWriter(reporter), 24 | plain: NewTextWriter(reporter, "plain"), 25 | html: NewTextWriter(reporter, "html"), 26 | types: []string{ 27 | "application/json", 28 | }, 29 | } 30 | } 31 | 32 | // Write a response object to the ResponseWriter with status code 200. 33 | func (h *NegotiationHandler) Write(w http.ResponseWriter, r *http.Request, e interface{}) { 34 | switch httputil.NegotiateContentType(r, []string{}, "application/json") { 35 | case "text/html": 36 | h.html.Write(w, r, e) 37 | return 38 | case "text/plain": 39 | h.plain.Write(w, r, e) 40 | return 41 | case "application/json": 42 | h.json.Write(w, r, e) 43 | return 44 | default: 45 | h.json.Write(w, r, e) 46 | return 47 | } 48 | } 49 | 50 | // WriteCode writes a response object to the ResponseWriter and sets a response code. 51 | func (h *NegotiationHandler) WriteCode(w http.ResponseWriter, r *http.Request, code int, e interface{}) { 52 | switch httputil.NegotiateContentType(r, []string{}, "application/json") { 53 | case "text/html": 54 | h.html.WriteCode(w, r, code, e) 55 | return 56 | case "text/plain": 57 | h.plain.WriteCode(w, r, code, e) 58 | return 59 | case "application/json": 60 | h.json.WriteCode(w, r, code, e) 61 | return 62 | default: 63 | h.json.WriteCode(w, r, code, e) 64 | return 65 | } 66 | } 67 | 68 | // WriteCreated writes a response object to the ResponseWriter with status code 201 and 69 | // the Location header set to location. 70 | func (h *NegotiationHandler) WriteCreated(w http.ResponseWriter, r *http.Request, location string, e interface{}) { 71 | switch httputil.NegotiateContentType(r, []string{}, "application/json") { 72 | case "text/html": 73 | h.html.WriteCreated(w, r, location, e) 74 | return 75 | case "text/plain": 76 | h.plain.WriteCreated(w, r, location, e) 77 | return 78 | case "application/json": 79 | h.json.WriteCreated(w, r, location, e) 80 | return 81 | default: 82 | h.json.WriteCreated(w, r, location, e) 83 | return 84 | } 85 | } 86 | 87 | // WriteError writes an error to ResponseWriter and tries to extract the error's status code by 88 | // asserting statusCodeCarrier. If the error does not implement statusCodeCarrier, the status code 89 | // is set to 500. 90 | func (h *NegotiationHandler) WriteError(w http.ResponseWriter, r *http.Request, err error) { 91 | switch httputil.NegotiateContentType(r, []string{}, "application/json") { 92 | case "text/html": 93 | h.html.WriteError(w, r, err) 94 | return 95 | case "text/plain": 96 | h.plain.WriteError(w, r, err) 97 | return 98 | case "application/json": 99 | h.json.WriteError(w, r, err) 100 | return 101 | default: 102 | h.json.WriteError(w, r, err) 103 | return 104 | } 105 | } 106 | 107 | // WriteErrorCode writes an error to ResponseWriter and forces an error code. 108 | func (h *NegotiationHandler) WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err error) { 109 | switch httputil.NegotiateContentType(r, []string{}, "application/json") { 110 | case "text/html": 111 | h.html.WriteErrorCode(w, r, code, err) 112 | return 113 | case "text/plain": 114 | h.plain.WriteErrorCode(w, r, code, err) 115 | return 116 | case "application/json": 117 | h.json.WriteErrorCode(w, r, code, err) 118 | return 119 | default: 120 | h.json.WriteErrorCode(w, r, code, err) 121 | return 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /options.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | func NoLog() Option { 7 | return func(o *options) { 8 | o.noLog = true 9 | } 10 | } 11 | 12 | func newOptions(opts []Option) *options { 13 | o := new(options) 14 | for _, oo := range opts { 15 | oo(o) 16 | } 17 | return o 18 | } 19 | 20 | type Option func(*options) 21 | 22 | type options struct { 23 | noLog bool 24 | } 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "prettier": "ory-prettier-styles", 4 | "devDependencies": { 5 | "license-checker": "^25.0.1", 6 | "ory-prettier-styles": "1.3.0", 7 | "prettier": "2.7.1" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /plain.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "context" 8 | "fmt" 9 | "net/http" 10 | 11 | "github.com/pkg/errors" 12 | ) 13 | 14 | // TextWriter outputs plain text 15 | type TextWriter struct { 16 | Reporter ErrorReporter 17 | contentType string 18 | } 19 | 20 | var _ Writer = (*TextWriter)(nil) 21 | 22 | // NewTextWriter returns a plain text writer 23 | func NewTextWriter(reporter ErrorReporter, contentType string) *TextWriter { 24 | if contentType == "" { 25 | contentType = "plain" 26 | } 27 | 28 | writer := &TextWriter{ 29 | Reporter: reporter, 30 | contentType: "text/" + contentType, 31 | } 32 | 33 | return writer 34 | } 35 | 36 | // Write a response object to the ResponseWriter with status code 200. 37 | func (h *TextWriter) Write(w http.ResponseWriter, r *http.Request, e interface{}, _ ...EncoderOptions) { 38 | h.WriteCode(w, r, http.StatusOK, e) 39 | } 40 | 41 | // WriteCode writes a response object to the ResponseWriter and sets a response code. 42 | func (h *TextWriter) WriteCode(w http.ResponseWriter, r *http.Request, code int, e interface{}, _ ...EncoderOptions) { 43 | if code == 0 { 44 | code = http.StatusOK 45 | } 46 | 47 | if errors.Is(r.Context().Err(), context.Canceled) { 48 | code = StatusClientClosedRequest 49 | } 50 | 51 | w.Header().Set("Content-Type", h.contentType) 52 | w.WriteHeader(code) 53 | fmt.Fprintf(w, "%s", e) 54 | } 55 | 56 | // WriteCreated writes a response object to the ResponseWriter with status code 201 and 57 | // the Location header set to location. 58 | func (h *TextWriter) WriteCreated(w http.ResponseWriter, r *http.Request, location string, e interface{}) { 59 | w.Header().Set("Location", location) 60 | h.WriteCode(w, r, http.StatusCreated, e) 61 | } 62 | 63 | // WriteError writes an error to ResponseWriter and tries to extract the error's status code by 64 | // asserting statusCodeCarrier. If the error does not implement statusCodeCarrier, the status code 65 | // is set to 500. 66 | func (h *TextWriter) WriteError(w http.ResponseWriter, r *http.Request, err error, _ ...Option) { 67 | if s, ok := errors.Cause(coalesceError(err)).(StatusCodeCarrier); ok { 68 | h.WriteErrorCode(w, r, s.StatusCode(), err) 69 | return 70 | } else { 71 | h.WriteErrorCode(w, r, http.StatusInternalServerError, err) 72 | } 73 | } 74 | 75 | // WriteErrorCode writes an error to ResponseWriter and forces an error code. 76 | func (h *TextWriter) WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err error, _ ...Option) { 77 | err = coalesceError(err) 78 | 79 | if code == 0 { 80 | code = http.StatusInternalServerError 81 | } 82 | 83 | if errors.Is(r.Context().Err(), context.Canceled) { 84 | code = StatusClientClosedRequest 85 | } 86 | 87 | // All errors land here, so it's a really good idea to do the logging here as well! 88 | h.Reporter.ReportError(r, code, err, "An error occurred while handling a request") 89 | 90 | w.Header().Set("Content-Type", h.contentType) 91 | w.WriteHeader(code) 92 | fmt.Fprintf(w, "%s", err) 93 | } 94 | -------------------------------------------------------------------------------- /writer.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Ory Corp 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package herodot 5 | 6 | import ( 7 | "net/http" 8 | ) 9 | 10 | // Writer is a helper to write arbitrary data to a ResponseWriter 11 | type Writer interface { 12 | // Write a response object to the ResponseWriter with status code 200. 13 | Write(w http.ResponseWriter, r *http.Request, e interface{}, opts ...EncoderOptions) 14 | 15 | // WriteCode writes a response object to the ResponseWriter and sets a response code. 16 | WriteCode(w http.ResponseWriter, r *http.Request, code int, e interface{}, opts ...EncoderOptions) 17 | 18 | // WriteCreated writes a response object to the ResponseWriter with status code 201 and 19 | // the Location header set to location. 20 | WriteCreated(w http.ResponseWriter, r *http.Request, location string, e interface{}) 21 | 22 | // WriteError writes an error to ResponseWriter and tries to extract the error's status code by 23 | // asserting statusCodeCarrier. If the error does not implement statusCodeCarrier, the status code 24 | // is set to 500. 25 | WriteError(w http.ResponseWriter, r *http.Request, err error, opts ...Option) 26 | 27 | // WriteErrorCode writes an error to ResponseWriter and forces an error code. 28 | WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err error, opts ...Option) 29 | } 30 | --------------------------------------------------------------------------------